babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274
  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. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5260. var newWidth = width;
  5261. var newHeight = newWidth / ratio;
  5262. if (newHeight > height) {
  5263. newHeight = height;
  5264. newWidth = newHeight * ratio;
  5265. }
  5266. var offsetX = Math.max(0, width - newWidth) / 2;
  5267. var offsetY = Math.max(0, height - newHeight) / 2;
  5268. renderContext.fillStyle = camera.getScene().clearColor.toHexString();
  5269. renderContext.fillRect(0, 0, width, height);
  5270. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5271. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5272. };
  5273. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5274. if (mimeType === void 0) { mimeType = "image/png"; }
  5275. var width;
  5276. var height;
  5277. //If a precision value is specified
  5278. if (size.precision) {
  5279. width = Math.round(engine.getRenderWidth() * size.precision);
  5280. height = Math.round(width / engine.getAspectRatio(camera));
  5281. size = { width: width, height: height };
  5282. }
  5283. else if (size.width && size.height) {
  5284. width = size.width;
  5285. height = size.height;
  5286. }
  5287. else if (size.width && !size.height) {
  5288. width = size.width;
  5289. height = Math.round(width / engine.getAspectRatio(camera));
  5290. size = { width: width, height: height };
  5291. }
  5292. else if (size.height && !size.width) {
  5293. height = size.height;
  5294. width = Math.round(height * engine.getAspectRatio(camera));
  5295. size = { width: width, height: height };
  5296. }
  5297. else if (!isNaN(size)) {
  5298. height = size;
  5299. width = size;
  5300. }
  5301. else {
  5302. Tools.Error("Invalid 'size' parameter !");
  5303. return;
  5304. }
  5305. var scene = camera.getScene();
  5306. var previousCamera = null;
  5307. if (scene.activeCamera !== camera) {
  5308. previousCamera = scene.activeCamera;
  5309. scene.activeCamera = camera;
  5310. }
  5311. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5312. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5313. texture.renderList = scene.meshes;
  5314. texture.onAfterRenderObservable.add(function () {
  5315. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5316. });
  5317. scene.incrementRenderId();
  5318. scene.resetCachedMaterial();
  5319. texture.render(true);
  5320. texture.dispose();
  5321. if (previousCamera) {
  5322. scene.activeCamera = previousCamera;
  5323. }
  5324. camera.getProjectionMatrix(true); // Force cache refresh;
  5325. };
  5326. // XHR response validator for local file scenario
  5327. Tools.ValidateXHRData = function (xhr, dataType) {
  5328. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5329. if (dataType === void 0) { dataType = 7; }
  5330. try {
  5331. if (dataType & 1) {
  5332. if (xhr.responseText && xhr.responseText.length > 0) {
  5333. return true;
  5334. }
  5335. else if (dataType === 1) {
  5336. return false;
  5337. }
  5338. }
  5339. if (dataType & 2) {
  5340. // Check header width and height since there is no "TGA" magic number
  5341. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5342. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5343. return true;
  5344. }
  5345. else if (dataType === 2) {
  5346. return false;
  5347. }
  5348. }
  5349. if (dataType & 4) {
  5350. // Check for the "DDS" magic number
  5351. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5352. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5353. return true;
  5354. }
  5355. else {
  5356. return false;
  5357. }
  5358. }
  5359. }
  5360. catch (e) {
  5361. }
  5362. return false;
  5363. };
  5364. /**
  5365. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5366. * Be aware Math.random() could cause collisions, but:
  5367. * "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"
  5368. */
  5369. Tools.RandomId = function () {
  5370. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5371. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5372. return v.toString(16);
  5373. });
  5374. };
  5375. Object.defineProperty(Tools, "NoneLogLevel", {
  5376. get: function () {
  5377. return Tools._NoneLogLevel;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Tools, "MessageLogLevel", {
  5383. get: function () {
  5384. return Tools._MessageLogLevel;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Tools, "WarningLogLevel", {
  5390. get: function () {
  5391. return Tools._WarningLogLevel;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Tools, "ErrorLogLevel", {
  5397. get: function () {
  5398. return Tools._ErrorLogLevel;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Tools, "AllLogLevel", {
  5404. get: function () {
  5405. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Tools._AddLogEntry = function (entry) {
  5411. Tools._LogCache = entry + Tools._LogCache;
  5412. if (Tools.OnNewCacheEntry) {
  5413. Tools.OnNewCacheEntry(entry);
  5414. }
  5415. };
  5416. Tools._FormatMessage = function (message) {
  5417. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5418. var date = new Date();
  5419. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5420. };
  5421. Tools._LogDisabled = function (message) {
  5422. // nothing to do
  5423. };
  5424. Tools._LogEnabled = function (message) {
  5425. var formattedMessage = Tools._FormatMessage(message);
  5426. console.log("BJS - " + formattedMessage);
  5427. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5428. Tools._AddLogEntry(entry);
  5429. };
  5430. Tools._WarnDisabled = function (message) {
  5431. // nothing to do
  5432. };
  5433. Tools._WarnEnabled = function (message) {
  5434. var formattedMessage = Tools._FormatMessage(message);
  5435. console.warn("BJS - " + formattedMessage);
  5436. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5437. Tools._AddLogEntry(entry);
  5438. };
  5439. Tools._ErrorDisabled = function (message) {
  5440. // nothing to do
  5441. };
  5442. Tools._ErrorEnabled = function (message) {
  5443. Tools.errorsCount++;
  5444. var formattedMessage = Tools._FormatMessage(message);
  5445. console.error("BJS - " + formattedMessage);
  5446. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5447. Tools._AddLogEntry(entry);
  5448. };
  5449. Object.defineProperty(Tools, "LogCache", {
  5450. get: function () {
  5451. return Tools._LogCache;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. Tools.ClearLogCache = function () {
  5457. Tools._LogCache = "";
  5458. Tools.errorsCount = 0;
  5459. };
  5460. Object.defineProperty(Tools, "LogLevels", {
  5461. set: function (level) {
  5462. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5463. Tools.Log = Tools._LogEnabled;
  5464. }
  5465. else {
  5466. Tools.Log = Tools._LogDisabled;
  5467. }
  5468. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5469. Tools.Warn = Tools._WarnEnabled;
  5470. }
  5471. else {
  5472. Tools.Warn = Tools._WarnDisabled;
  5473. }
  5474. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5475. Tools.Error = Tools._ErrorEnabled;
  5476. }
  5477. else {
  5478. Tools.Error = Tools._ErrorDisabled;
  5479. }
  5480. },
  5481. enumerable: true,
  5482. configurable: true
  5483. });
  5484. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5485. get: function () {
  5486. return Tools._PerformanceNoneLogLevel;
  5487. },
  5488. enumerable: true,
  5489. configurable: true
  5490. });
  5491. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5492. get: function () {
  5493. return Tools._PerformanceUserMarkLogLevel;
  5494. },
  5495. enumerable: true,
  5496. configurable: true
  5497. });
  5498. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5499. get: function () {
  5500. return Tools._PerformanceConsoleLogLevel;
  5501. },
  5502. enumerable: true,
  5503. configurable: true
  5504. });
  5505. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5506. set: function (level) {
  5507. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5508. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5509. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5510. return;
  5511. }
  5512. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5513. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5514. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5515. return;
  5516. }
  5517. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5518. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5519. },
  5520. enumerable: true,
  5521. configurable: true
  5522. });
  5523. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5524. };
  5525. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5526. };
  5527. Tools._StartUserMark = function (counterName, condition) {
  5528. if (condition === void 0) { condition = true; }
  5529. if (!condition || !Tools._performance.mark) {
  5530. return;
  5531. }
  5532. Tools._performance.mark(counterName + "-Begin");
  5533. };
  5534. Tools._EndUserMark = function (counterName, condition) {
  5535. if (condition === void 0) { condition = true; }
  5536. if (!condition || !Tools._performance.mark) {
  5537. return;
  5538. }
  5539. Tools._performance.mark(counterName + "-End");
  5540. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5541. };
  5542. Tools._StartPerformanceConsole = function (counterName, condition) {
  5543. if (condition === void 0) { condition = true; }
  5544. if (!condition) {
  5545. return;
  5546. }
  5547. Tools._StartUserMark(counterName, condition);
  5548. if (console.time) {
  5549. console.time(counterName);
  5550. }
  5551. };
  5552. Tools._EndPerformanceConsole = function (counterName, condition) {
  5553. if (condition === void 0) { condition = true; }
  5554. if (!condition) {
  5555. return;
  5556. }
  5557. Tools._EndUserMark(counterName, condition);
  5558. if (console.time) {
  5559. console.timeEnd(counterName);
  5560. }
  5561. };
  5562. Object.defineProperty(Tools, "Now", {
  5563. get: function () {
  5564. if (window.performance && window.performance.now) {
  5565. return window.performance.now();
  5566. }
  5567. return new Date().getTime();
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. /**
  5573. * This method will return the name of the class used to create the instance of the given object.
  5574. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5575. * @param object the object to get the class name from
  5576. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5577. */
  5578. Tools.getClassName = function (object, isType) {
  5579. if (isType === void 0) { isType = false; }
  5580. var name = null;
  5581. if (!isType && object.getClassName) {
  5582. name = object.getClassName();
  5583. }
  5584. else {
  5585. if (object instanceof Object) {
  5586. var classObj = isType ? object : Object.getPrototypeOf(object);
  5587. name = classObj.constructor["__bjsclassName__"];
  5588. }
  5589. if (!name) {
  5590. name = typeof object;
  5591. }
  5592. }
  5593. return name;
  5594. };
  5595. Tools.first = function (array, predicate) {
  5596. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5597. var el = array_1[_i];
  5598. if (predicate(el)) {
  5599. return el;
  5600. }
  5601. }
  5602. };
  5603. /**
  5604. * This method will return the name of the full name of the class, including its owning module (if any).
  5605. * 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).
  5606. * @param object the object to get the class name from
  5607. * @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.
  5608. */
  5609. Tools.getFullClassName = function (object, isType) {
  5610. if (isType === void 0) { isType = false; }
  5611. var className = null;
  5612. var moduleName = null;
  5613. if (!isType && object.getClassName) {
  5614. className = object.getClassName();
  5615. }
  5616. else {
  5617. if (object instanceof Object) {
  5618. var classObj = isType ? object : Object.getPrototypeOf(object);
  5619. className = classObj.constructor["__bjsclassName__"];
  5620. moduleName = classObj.constructor["__bjsmoduleName__"];
  5621. }
  5622. if (!className) {
  5623. className = typeof object;
  5624. }
  5625. }
  5626. if (!className) {
  5627. return null;
  5628. }
  5629. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5630. };
  5631. /**
  5632. * 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.
  5633. * @param array
  5634. */
  5635. Tools.arrayOrStringFeeder = function (array) {
  5636. return function (index) {
  5637. if (index >= array.length) {
  5638. return null;
  5639. }
  5640. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5641. if (val && val.getHashCode) {
  5642. val = val.getHashCode();
  5643. }
  5644. if (typeof val === "string") {
  5645. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5646. }
  5647. return val;
  5648. };
  5649. };
  5650. /**
  5651. * Compute the hashCode of a stream of number
  5652. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5653. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5654. * @return the hash code computed
  5655. */
  5656. Tools.hashCodeFromStream = function (feeder) {
  5657. // Based from here: http://stackoverflow.com/a/7616484/802124
  5658. var hash = 0;
  5659. var index = 0;
  5660. var chr = feeder(index++);
  5661. while (chr != null) {
  5662. hash = ((hash << 5) - hash) + chr;
  5663. hash |= 0; // Convert to 32bit integer
  5664. chr = feeder(index++);
  5665. }
  5666. return hash;
  5667. };
  5668. Tools.BaseUrl = "";
  5669. Tools.CorsBehavior = "anonymous";
  5670. Tools.UseFallbackTexture = true;
  5671. // Logs
  5672. Tools._NoneLogLevel = 0;
  5673. Tools._MessageLogLevel = 1;
  5674. Tools._WarningLogLevel = 2;
  5675. Tools._ErrorLogLevel = 4;
  5676. Tools._LogCache = "";
  5677. Tools.errorsCount = 0;
  5678. Tools.Log = Tools._LogEnabled;
  5679. Tools.Warn = Tools._WarnEnabled;
  5680. Tools.Error = Tools._ErrorEnabled;
  5681. // Performances
  5682. Tools._PerformanceNoneLogLevel = 0;
  5683. Tools._PerformanceUserMarkLogLevel = 1;
  5684. Tools._PerformanceConsoleLogLevel = 2;
  5685. Tools._performance = window.performance;
  5686. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5687. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5688. return Tools;
  5689. }());
  5690. BABYLON.Tools = Tools;
  5691. /**
  5692. * This class is used to track a performance counter which is number based.
  5693. * The user has access to many properties which give statistics of different nature
  5694. *
  5695. * The implementer can track two kinds of Performance Counter: time and count
  5696. * 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.
  5697. * 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.
  5698. */
  5699. var PerfCounter = (function () {
  5700. function PerfCounter() {
  5701. this._startMonitoringTime = 0;
  5702. this._min = 0;
  5703. this._max = 0;
  5704. this._average = 0;
  5705. this._lastSecAverage = 0;
  5706. this._current = 0;
  5707. this._totalValueCount = 0;
  5708. this._totalAccumulated = 0;
  5709. this._lastSecAccumulated = 0;
  5710. this._lastSecTime = 0;
  5711. this._lastSecValueCount = 0;
  5712. }
  5713. Object.defineProperty(PerfCounter.prototype, "min", {
  5714. /**
  5715. * Returns the smallest value ever
  5716. */
  5717. get: function () {
  5718. return this._min;
  5719. },
  5720. enumerable: true,
  5721. configurable: true
  5722. });
  5723. Object.defineProperty(PerfCounter.prototype, "max", {
  5724. /**
  5725. * Returns the biggest value ever
  5726. */
  5727. get: function () {
  5728. return this._max;
  5729. },
  5730. enumerable: true,
  5731. configurable: true
  5732. });
  5733. Object.defineProperty(PerfCounter.prototype, "average", {
  5734. /**
  5735. * Returns the average value since the performance counter is running
  5736. */
  5737. get: function () {
  5738. return this._average;
  5739. },
  5740. enumerable: true,
  5741. configurable: true
  5742. });
  5743. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5744. /**
  5745. * Returns the average value of the last second the counter was monitored
  5746. */
  5747. get: function () {
  5748. return this._lastSecAverage;
  5749. },
  5750. enumerable: true,
  5751. configurable: true
  5752. });
  5753. Object.defineProperty(PerfCounter.prototype, "current", {
  5754. /**
  5755. * Returns the current value
  5756. */
  5757. get: function () {
  5758. return this._current;
  5759. },
  5760. enumerable: true,
  5761. configurable: true
  5762. });
  5763. Object.defineProperty(PerfCounter.prototype, "total", {
  5764. get: function () {
  5765. return this._totalAccumulated;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. /**
  5771. * Call this method to start monitoring a new frame.
  5772. * 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.
  5773. */
  5774. PerfCounter.prototype.fetchNewFrame = function () {
  5775. this._totalValueCount++;
  5776. this._current = 0;
  5777. this._lastSecValueCount++;
  5778. };
  5779. /**
  5780. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5781. * @param newCount the count value to add to the monitored count
  5782. * @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.
  5783. */
  5784. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5785. this._current += newCount;
  5786. if (fetchResult) {
  5787. this._fetchResult();
  5788. }
  5789. };
  5790. /**
  5791. * Start monitoring this performance counter
  5792. */
  5793. PerfCounter.prototype.beginMonitoring = function () {
  5794. this._startMonitoringTime = Tools.Now;
  5795. };
  5796. /**
  5797. * Compute the time lapsed since the previous beginMonitoring() call.
  5798. * @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
  5799. */
  5800. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5801. if (newFrame === void 0) { newFrame = true; }
  5802. if (newFrame) {
  5803. this.fetchNewFrame();
  5804. }
  5805. var currentTime = Tools.Now;
  5806. this._current = currentTime - this._startMonitoringTime;
  5807. if (newFrame) {
  5808. this._fetchResult();
  5809. }
  5810. };
  5811. PerfCounter.prototype._fetchResult = function () {
  5812. this._totalAccumulated += this._current;
  5813. this._lastSecAccumulated += this._current;
  5814. // Min/Max update
  5815. this._min = Math.min(this._min, this._current);
  5816. this._max = Math.max(this._max, this._current);
  5817. this._average = this._totalAccumulated / this._totalValueCount;
  5818. // Reset last sec?
  5819. var now = Tools.Now;
  5820. if ((now - this._lastSecTime) > 1000) {
  5821. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5822. this._lastSecTime = now;
  5823. this._lastSecAccumulated = 0;
  5824. this._lastSecValueCount = 0;
  5825. }
  5826. };
  5827. return PerfCounter;
  5828. }());
  5829. BABYLON.PerfCounter = PerfCounter;
  5830. /**
  5831. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5832. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5833. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5834. * @param name The name of the class, case should be preserved
  5835. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5836. */
  5837. function className(name, module) {
  5838. return function (target) {
  5839. target["__bjsclassName__"] = name;
  5840. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5841. };
  5842. }
  5843. BABYLON.className = className;
  5844. /**
  5845. * An implementation of a loop for asynchronous functions.
  5846. */
  5847. var AsyncLoop = (function () {
  5848. /**
  5849. * Constroctor.
  5850. * @param iterations the number of iterations.
  5851. * @param _fn the function to run each iteration
  5852. * @param _successCallback the callback that will be called upon succesful execution
  5853. * @param offset starting offset.
  5854. */
  5855. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5856. if (offset === void 0) { offset = 0; }
  5857. this.iterations = iterations;
  5858. this._fn = _fn;
  5859. this._successCallback = _successCallback;
  5860. this.index = offset - 1;
  5861. this._done = false;
  5862. }
  5863. /**
  5864. * Execute the next iteration. Must be called after the last iteration was finished.
  5865. */
  5866. AsyncLoop.prototype.executeNext = function () {
  5867. if (!this._done) {
  5868. if (this.index + 1 < this.iterations) {
  5869. ++this.index;
  5870. this._fn(this);
  5871. }
  5872. else {
  5873. this.breakLoop();
  5874. }
  5875. }
  5876. };
  5877. /**
  5878. * Break the loop and run the success callback.
  5879. */
  5880. AsyncLoop.prototype.breakLoop = function () {
  5881. this._done = true;
  5882. this._successCallback();
  5883. };
  5884. /**
  5885. * Helper function
  5886. */
  5887. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5888. if (offset === void 0) { offset = 0; }
  5889. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5890. loop.executeNext();
  5891. return loop;
  5892. };
  5893. /**
  5894. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5895. * @param iterations total number of iterations
  5896. * @param syncedIterations number of synchronous iterations in each async iteration.
  5897. * @param fn the function to call each iteration.
  5898. * @param callback a success call back that will be called when iterating stops.
  5899. * @param breakFunction a break condition (optional)
  5900. * @param timeout timeout settings for the setTimeout function. default - 0.
  5901. * @constructor
  5902. */
  5903. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5904. if (timeout === void 0) { timeout = 0; }
  5905. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5906. if (breakFunction && breakFunction())
  5907. loop.breakLoop();
  5908. else {
  5909. setTimeout(function () {
  5910. for (var i = 0; i < syncedIterations; ++i) {
  5911. var iteration = (loop.index * syncedIterations) + i;
  5912. if (iteration >= iterations)
  5913. break;
  5914. fn(iteration);
  5915. if (breakFunction && breakFunction()) {
  5916. loop.breakLoop();
  5917. break;
  5918. }
  5919. }
  5920. loop.executeNext();
  5921. }, timeout);
  5922. }
  5923. }, callback);
  5924. };
  5925. return AsyncLoop;
  5926. }());
  5927. BABYLON.AsyncLoop = AsyncLoop;
  5928. })(BABYLON || (BABYLON = {}));
  5929. //# sourceMappingURL=babylon.tools.js.map
  5930. var BABYLON;
  5931. (function (BABYLON) {
  5932. var Internals;
  5933. (function (Internals) {
  5934. var _AlphaState = (function () {
  5935. /**
  5936. * Initializes the state.
  5937. */
  5938. function _AlphaState() {
  5939. this._isAlphaBlendDirty = false;
  5940. this._isBlendFunctionParametersDirty = false;
  5941. this._alphaBlend = false;
  5942. this._blendFunctionParameters = new Array(4);
  5943. this.reset();
  5944. }
  5945. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5946. get: function () {
  5947. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5948. },
  5949. enumerable: true,
  5950. configurable: true
  5951. });
  5952. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5953. get: function () {
  5954. return this._alphaBlend;
  5955. },
  5956. set: function (value) {
  5957. if (this._alphaBlend === value) {
  5958. return;
  5959. }
  5960. this._alphaBlend = value;
  5961. this._isAlphaBlendDirty = true;
  5962. },
  5963. enumerable: true,
  5964. configurable: true
  5965. });
  5966. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5967. if (this._blendFunctionParameters[0] === value0 &&
  5968. this._blendFunctionParameters[1] === value1 &&
  5969. this._blendFunctionParameters[2] === value2 &&
  5970. this._blendFunctionParameters[3] === value3) {
  5971. return;
  5972. }
  5973. this._blendFunctionParameters[0] = value0;
  5974. this._blendFunctionParameters[1] = value1;
  5975. this._blendFunctionParameters[2] = value2;
  5976. this._blendFunctionParameters[3] = value3;
  5977. this._isBlendFunctionParametersDirty = true;
  5978. };
  5979. _AlphaState.prototype.reset = function () {
  5980. this._alphaBlend = false;
  5981. this._blendFunctionParameters[0] = null;
  5982. this._blendFunctionParameters[1] = null;
  5983. this._blendFunctionParameters[2] = null;
  5984. this._blendFunctionParameters[3] = null;
  5985. this._isAlphaBlendDirty = true;
  5986. this._isBlendFunctionParametersDirty = false;
  5987. };
  5988. _AlphaState.prototype.apply = function (gl) {
  5989. if (!this.isDirty) {
  5990. return;
  5991. }
  5992. // Alpha blend
  5993. if (this._isAlphaBlendDirty) {
  5994. if (this._alphaBlend) {
  5995. gl.enable(gl.BLEND);
  5996. }
  5997. else {
  5998. gl.disable(gl.BLEND);
  5999. }
  6000. this._isAlphaBlendDirty = false;
  6001. }
  6002. // Alpha function
  6003. if (this._isBlendFunctionParametersDirty) {
  6004. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6005. this._isBlendFunctionParametersDirty = false;
  6006. }
  6007. };
  6008. return _AlphaState;
  6009. }());
  6010. Internals._AlphaState = _AlphaState;
  6011. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6012. })(BABYLON || (BABYLON = {}));
  6013. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6014. var BABYLON;
  6015. (function (BABYLON) {
  6016. var Internals;
  6017. (function (Internals) {
  6018. var _DepthCullingState = (function () {
  6019. /**
  6020. * Initializes the state.
  6021. */
  6022. function _DepthCullingState() {
  6023. this._isDepthTestDirty = false;
  6024. this._isDepthMaskDirty = false;
  6025. this._isDepthFuncDirty = false;
  6026. this._isCullFaceDirty = false;
  6027. this._isCullDirty = false;
  6028. this._isZOffsetDirty = false;
  6029. this.reset();
  6030. }
  6031. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6032. get: function () {
  6033. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6039. get: function () {
  6040. return this._zOffset;
  6041. },
  6042. set: function (value) {
  6043. if (this._zOffset === value) {
  6044. return;
  6045. }
  6046. this._zOffset = value;
  6047. this._isZOffsetDirty = true;
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6053. get: function () {
  6054. return this._cullFace;
  6055. },
  6056. set: function (value) {
  6057. if (this._cullFace === value) {
  6058. return;
  6059. }
  6060. this._cullFace = value;
  6061. this._isCullFaceDirty = true;
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6067. get: function () {
  6068. return this._cull;
  6069. },
  6070. set: function (value) {
  6071. if (this._cull === value) {
  6072. return;
  6073. }
  6074. this._cull = value;
  6075. this._isCullDirty = true;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6081. get: function () {
  6082. return this._depthFunc;
  6083. },
  6084. set: function (value) {
  6085. if (this._depthFunc === value) {
  6086. return;
  6087. }
  6088. this._depthFunc = value;
  6089. this._isDepthFuncDirty = true;
  6090. },
  6091. enumerable: true,
  6092. configurable: true
  6093. });
  6094. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6095. get: function () {
  6096. return this._depthMask;
  6097. },
  6098. set: function (value) {
  6099. if (this._depthMask === value) {
  6100. return;
  6101. }
  6102. this._depthMask = value;
  6103. this._isDepthMaskDirty = true;
  6104. },
  6105. enumerable: true,
  6106. configurable: true
  6107. });
  6108. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6109. get: function () {
  6110. return this._depthTest;
  6111. },
  6112. set: function (value) {
  6113. if (this._depthTest === value) {
  6114. return;
  6115. }
  6116. this._depthTest = value;
  6117. this._isDepthTestDirty = true;
  6118. },
  6119. enumerable: true,
  6120. configurable: true
  6121. });
  6122. _DepthCullingState.prototype.reset = function () {
  6123. this._depthMask = true;
  6124. this._depthTest = true;
  6125. this._depthFunc = null;
  6126. this._cullFace = null;
  6127. this._cull = null;
  6128. this._zOffset = 0;
  6129. this._isDepthTestDirty = true;
  6130. this._isDepthMaskDirty = true;
  6131. this._isDepthFuncDirty = false;
  6132. this._isCullFaceDirty = false;
  6133. this._isCullDirty = false;
  6134. this._isZOffsetDirty = false;
  6135. };
  6136. _DepthCullingState.prototype.apply = function (gl) {
  6137. if (!this.isDirty) {
  6138. return;
  6139. }
  6140. // Cull
  6141. if (this._isCullDirty) {
  6142. if (this.cull) {
  6143. gl.enable(gl.CULL_FACE);
  6144. }
  6145. else {
  6146. gl.disable(gl.CULL_FACE);
  6147. }
  6148. this._isCullDirty = false;
  6149. }
  6150. // Cull face
  6151. if (this._isCullFaceDirty) {
  6152. gl.cullFace(this.cullFace);
  6153. this._isCullFaceDirty = false;
  6154. }
  6155. // Depth mask
  6156. if (this._isDepthMaskDirty) {
  6157. gl.depthMask(this.depthMask);
  6158. this._isDepthMaskDirty = false;
  6159. }
  6160. // Depth test
  6161. if (this._isDepthTestDirty) {
  6162. if (this.depthTest) {
  6163. gl.enable(gl.DEPTH_TEST);
  6164. }
  6165. else {
  6166. gl.disable(gl.DEPTH_TEST);
  6167. }
  6168. this._isDepthTestDirty = false;
  6169. }
  6170. // Depth func
  6171. if (this._isDepthFuncDirty) {
  6172. gl.depthFunc(this.depthFunc);
  6173. this._isDepthFuncDirty = false;
  6174. }
  6175. // zOffset
  6176. if (this._isZOffsetDirty) {
  6177. if (this.zOffset) {
  6178. gl.enable(gl.POLYGON_OFFSET_FILL);
  6179. gl.polygonOffset(this.zOffset, 0);
  6180. }
  6181. else {
  6182. gl.disable(gl.POLYGON_OFFSET_FILL);
  6183. }
  6184. this._isZOffsetDirty = false;
  6185. }
  6186. };
  6187. return _DepthCullingState;
  6188. }());
  6189. Internals._DepthCullingState = _DepthCullingState;
  6190. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6191. })(BABYLON || (BABYLON = {}));
  6192. //# sourceMappingURL=babylon.depthCullingState.js.map
  6193. var BABYLON;
  6194. (function (BABYLON) {
  6195. var Internals;
  6196. (function (Internals) {
  6197. var _StencilState = (function () {
  6198. function _StencilState() {
  6199. this._isStencilTestDirty = false;
  6200. this._isStencilMaskDirty = false;
  6201. this._isStencilFuncDirty = false;
  6202. this._isStencilOpDirty = false;
  6203. this.reset();
  6204. }
  6205. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6206. get: function () {
  6207. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6208. },
  6209. enumerable: true,
  6210. configurable: true
  6211. });
  6212. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6213. get: function () {
  6214. return this._stencilFunc;
  6215. },
  6216. set: function (value) {
  6217. if (this._stencilFunc === value) {
  6218. return;
  6219. }
  6220. this._stencilFunc = value;
  6221. this._isStencilFuncDirty = true;
  6222. },
  6223. enumerable: true,
  6224. configurable: true
  6225. });
  6226. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6227. get: function () {
  6228. return this._stencilFuncRef;
  6229. },
  6230. set: function (value) {
  6231. if (this._stencilFuncRef === value) {
  6232. return;
  6233. }
  6234. this._stencilFuncRef = value;
  6235. this._isStencilFuncDirty = true;
  6236. },
  6237. enumerable: true,
  6238. configurable: true
  6239. });
  6240. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6241. get: function () {
  6242. return this._stencilFuncMask;
  6243. },
  6244. set: function (value) {
  6245. if (this._stencilFuncMask === value) {
  6246. return;
  6247. }
  6248. this._stencilFuncMask = value;
  6249. this._isStencilFuncDirty = true;
  6250. },
  6251. enumerable: true,
  6252. configurable: true
  6253. });
  6254. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6255. get: function () {
  6256. return this._stencilOpStencilFail;
  6257. },
  6258. set: function (value) {
  6259. if (this._stencilOpStencilFail === value) {
  6260. return;
  6261. }
  6262. this._stencilOpStencilFail = value;
  6263. this._isStencilOpDirty = true;
  6264. },
  6265. enumerable: true,
  6266. configurable: true
  6267. });
  6268. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6269. get: function () {
  6270. return this._stencilOpDepthFail;
  6271. },
  6272. set: function (value) {
  6273. if (this._stencilOpDepthFail === value) {
  6274. return;
  6275. }
  6276. this._stencilOpDepthFail = value;
  6277. this._isStencilOpDirty = true;
  6278. },
  6279. enumerable: true,
  6280. configurable: true
  6281. });
  6282. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6283. get: function () {
  6284. return this._stencilOpStencilDepthPass;
  6285. },
  6286. set: function (value) {
  6287. if (this._stencilOpStencilDepthPass === value) {
  6288. return;
  6289. }
  6290. this._stencilOpStencilDepthPass = value;
  6291. this._isStencilOpDirty = true;
  6292. },
  6293. enumerable: true,
  6294. configurable: true
  6295. });
  6296. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6297. get: function () {
  6298. return this._stencilMask;
  6299. },
  6300. set: function (value) {
  6301. if (this._stencilMask === value) {
  6302. return;
  6303. }
  6304. this._stencilMask = value;
  6305. this._isStencilMaskDirty = true;
  6306. },
  6307. enumerable: true,
  6308. configurable: true
  6309. });
  6310. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6311. get: function () {
  6312. return this._stencilTest;
  6313. },
  6314. set: function (value) {
  6315. if (this._stencilTest === value) {
  6316. return;
  6317. }
  6318. this._stencilTest = value;
  6319. this._isStencilTestDirty = true;
  6320. },
  6321. enumerable: true,
  6322. configurable: true
  6323. });
  6324. _StencilState.prototype.reset = function () {
  6325. this._stencilTest = false;
  6326. this._stencilMask = 0xFF;
  6327. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6328. this._stencilFuncRef = 1;
  6329. this._stencilFuncMask = 0xFF;
  6330. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6331. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6332. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6333. this._isStencilTestDirty = true;
  6334. this._isStencilMaskDirty = true;
  6335. this._isStencilFuncDirty = true;
  6336. this._isStencilOpDirty = true;
  6337. };
  6338. _StencilState.prototype.apply = function (gl) {
  6339. if (!this.isDirty) {
  6340. return;
  6341. }
  6342. // Stencil test
  6343. if (this._isStencilTestDirty) {
  6344. if (this.stencilTest) {
  6345. gl.enable(gl.STENCIL_TEST);
  6346. }
  6347. else {
  6348. gl.disable(gl.STENCIL_TEST);
  6349. }
  6350. this._isStencilTestDirty = false;
  6351. }
  6352. // Stencil mask
  6353. if (this._isStencilMaskDirty) {
  6354. gl.stencilMask(this.stencilMask);
  6355. this._isStencilMaskDirty = false;
  6356. }
  6357. // Stencil func
  6358. if (this._isStencilFuncDirty) {
  6359. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6360. this._isStencilFuncDirty = false;
  6361. }
  6362. // Stencil op
  6363. if (this._isStencilOpDirty) {
  6364. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6365. this._isStencilOpDirty = false;
  6366. }
  6367. };
  6368. return _StencilState;
  6369. }());
  6370. Internals._StencilState = _StencilState;
  6371. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6372. })(BABYLON || (BABYLON = {}));
  6373. //# sourceMappingURL=babylon.stencilState.js.map
  6374. var BABYLON;
  6375. (function (BABYLON) {
  6376. var compileShader = function (gl, source, type, defines) {
  6377. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6378. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6379. gl.compileShader(shader);
  6380. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6381. throw new Error(gl.getShaderInfoLog(shader));
  6382. }
  6383. return shader;
  6384. };
  6385. var HALF_FLOAT_OES = 0x8D61;
  6386. var getWebGLTextureType = function (gl, type) {
  6387. if (type === Engine.TEXTURETYPE_FLOAT) {
  6388. return gl.FLOAT;
  6389. }
  6390. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6391. // Add Half Float Constant.
  6392. return HALF_FLOAT_OES;
  6393. }
  6394. return gl.UNSIGNED_BYTE;
  6395. };
  6396. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6397. var magFilter = gl.NEAREST;
  6398. var minFilter = gl.NEAREST;
  6399. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6400. magFilter = gl.LINEAR;
  6401. if (generateMipMaps) {
  6402. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6403. }
  6404. else {
  6405. minFilter = gl.LINEAR;
  6406. }
  6407. }
  6408. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6409. magFilter = gl.LINEAR;
  6410. if (generateMipMaps) {
  6411. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6412. }
  6413. else {
  6414. minFilter = gl.LINEAR;
  6415. }
  6416. }
  6417. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6418. magFilter = gl.NEAREST;
  6419. if (generateMipMaps) {
  6420. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6421. }
  6422. else {
  6423. minFilter = gl.NEAREST;
  6424. }
  6425. }
  6426. return {
  6427. min: minFilter,
  6428. mag: magFilter
  6429. };
  6430. };
  6431. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6433. var engine = scene.getEngine();
  6434. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6435. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6436. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6437. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6438. texture._baseWidth = width;
  6439. texture._baseHeight = height;
  6440. texture._width = potWidth;
  6441. texture._height = potHeight;
  6442. texture.isReady = true;
  6443. processFunction(potWidth, potHeight);
  6444. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6447. if (!noMipmap && !isCompressed) {
  6448. gl.generateMipmap(gl.TEXTURE_2D);
  6449. }
  6450. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6451. engine.resetTextureCache();
  6452. scene._removePendingData(texture);
  6453. texture.onLoadedCallbacks.forEach(function (callback) {
  6454. callback();
  6455. });
  6456. texture.onLoadedCallbacks = [];
  6457. };
  6458. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6459. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6460. var img;
  6461. var onload = function () {
  6462. loadedImages[index] = img;
  6463. loadedImages._internalCount++;
  6464. scene._removePendingData(img);
  6465. if (loadedImages._internalCount === 6) {
  6466. onfinish(loadedImages);
  6467. }
  6468. };
  6469. var onerror = function () {
  6470. scene._removePendingData(img);
  6471. if (onErrorCallBack) {
  6472. onErrorCallBack();
  6473. }
  6474. };
  6475. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6476. scene._addPendingData(img);
  6477. };
  6478. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6479. if (onError === void 0) { onError = null; }
  6480. var loadedImages = [];
  6481. loadedImages._internalCount = 0;
  6482. for (var index = 0; index < 6; index++) {
  6483. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6484. }
  6485. };
  6486. var InstancingAttributeInfo = (function () {
  6487. function InstancingAttributeInfo() {
  6488. }
  6489. return InstancingAttributeInfo;
  6490. }());
  6491. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6492. var EngineCapabilities = (function () {
  6493. function EngineCapabilities() {
  6494. }
  6495. return EngineCapabilities;
  6496. }());
  6497. BABYLON.EngineCapabilities = EngineCapabilities;
  6498. /**
  6499. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6500. */
  6501. var Engine = (function () {
  6502. /**
  6503. * @constructor
  6504. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6505. * @param {boolean} [antialias] - enable antialias
  6506. * @param options - further options to be sent to the getContext function
  6507. */
  6508. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6509. var _this = this;
  6510. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6511. // Public members
  6512. this.isFullscreen = false;
  6513. this.isPointerLock = false;
  6514. this.cullBackFaces = true;
  6515. this.renderEvenInBackground = true;
  6516. // To enable/disable IDB support and avoid XHR on .manifest
  6517. this.enableOfflineSupport = true;
  6518. this.scenes = new Array();
  6519. this._windowIsBackground = false;
  6520. this._webGLVersion = "1.0";
  6521. this._badOS = false;
  6522. this._drawCalls = new BABYLON.PerfCounter();
  6523. this._renderingQueueLaunched = false;
  6524. this._activeRenderLoops = [];
  6525. // FPS
  6526. this.fpsRange = 60;
  6527. this.previousFramesDuration = [];
  6528. this.fps = 60;
  6529. this.deltaTime = 0;
  6530. // States
  6531. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6532. this._stencilState = new BABYLON.Internals._StencilState();
  6533. this._alphaState = new BABYLON.Internals._AlphaState();
  6534. this._alphaMode = Engine.ALPHA_DISABLE;
  6535. // Cache
  6536. this._loadedTexturesCache = new Array();
  6537. this._maxTextureChannels = 16;
  6538. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6539. this._compiledEffects = {};
  6540. this._vertexAttribArraysEnabled = [];
  6541. this._uintIndicesCurrentlySet = false;
  6542. this._currentBoundBuffer = new Array();
  6543. this._currentBufferPointers = [];
  6544. this._currentInstanceLocations = new Array();
  6545. this._currentInstanceBuffers = new Array();
  6546. // Hardware supported Compressed Textures
  6547. this._texturesSupported = new Array();
  6548. this._onVRFullScreenTriggered = function () {
  6549. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6550. //get the old size before we change
  6551. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6552. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6553. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6554. //But actually, no browser follow the specs...
  6555. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6556. //get the width and height, change the render size
  6557. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6558. var width, height;
  6559. _this.setHardwareScalingLevel(1);
  6560. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6561. }
  6562. else {
  6563. //When the specs are implemented, need to uncomment this.
  6564. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6565. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6566. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6567. _this._vrDisplayEnabled = undefined;
  6568. }
  6569. };
  6570. this._renderingCanvas = canvas;
  6571. this._externalData = new BABYLON.StringDictionary();
  6572. options = options || {};
  6573. if (antialias != null) {
  6574. options.antialias = antialias;
  6575. }
  6576. if (options.preserveDrawingBuffer === undefined) {
  6577. options.preserveDrawingBuffer = false;
  6578. }
  6579. // Checks if some of the format renders first to allow the use of webgl inspector.
  6580. var renderToFullFloat = this._canRenderToFloatTexture();
  6581. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6582. // GL
  6583. //try {
  6584. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6585. // if (this._gl) {
  6586. // this._webGLVersion = "2.0";
  6587. // }
  6588. //} catch (e) {
  6589. // // Do nothing
  6590. //}
  6591. if (!this._gl) {
  6592. if (!canvas) {
  6593. throw new Error("The provided canvas is null or undefined.");
  6594. }
  6595. try {
  6596. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6597. }
  6598. catch (e) {
  6599. throw new Error("WebGL not supported");
  6600. }
  6601. }
  6602. if (!this._gl) {
  6603. throw new Error("WebGL not supported");
  6604. }
  6605. this._onBlur = function () {
  6606. _this._windowIsBackground = true;
  6607. };
  6608. this._onFocus = function () {
  6609. _this._windowIsBackground = false;
  6610. };
  6611. window.addEventListener("blur", this._onBlur);
  6612. window.addEventListener("focus", this._onFocus);
  6613. // Viewport
  6614. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6615. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6616. this.resize();
  6617. // Caps
  6618. this._isStencilEnable = options.stencil;
  6619. this._caps = new EngineCapabilities();
  6620. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6621. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6622. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6623. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6624. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6625. // Infos
  6626. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6627. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6628. if (rendererInfo != null) {
  6629. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6630. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6631. }
  6632. if (!this._glVendor) {
  6633. this._glVendor = "Unknown vendor";
  6634. }
  6635. if (!this._glRenderer) {
  6636. this._glRenderer = "Unknown renderer";
  6637. }
  6638. // Extensions
  6639. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6640. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
  6641. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6642. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
  6643. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
  6644. 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
  6645. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6646. 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');
  6647. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6648. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6649. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6650. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6651. this._caps.highPrecisionShaderSupported = true;
  6652. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6653. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6654. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6655. this._caps.textureFloatRender = renderToFullFloat;
  6656. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6657. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6658. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6659. // Intelligently add supported commpressed formats in order to check for.
  6660. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6661. // Next PVR & S3, which are probably superior to ETC1/2.
  6662. // Likely no hardware which supports both PVR & S3, so order matters little.
  6663. // ETC2 is newer and handles ETC1, so check for first.
  6664. if (this._caps.astc)
  6665. this.texturesSupported.push('.astc');
  6666. if (this._caps.s3tc)
  6667. this.texturesSupported.push('.dds');
  6668. if (this._caps.pvrtc)
  6669. this.texturesSupported.push('.pvr');
  6670. if (this._caps.etc2)
  6671. this.texturesSupported.push('.etc2');
  6672. if (this._caps.etc1)
  6673. this.texturesSupported.push('.etc1');
  6674. if (this._gl.getShaderPrecisionFormat) {
  6675. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6676. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6677. }
  6678. // Depth buffer
  6679. this.setDepthBuffer(true);
  6680. this.setDepthFunctionToLessOrEqual();
  6681. this.setDepthWrite(true);
  6682. // Fullscreen
  6683. this._onFullscreenChange = function () {
  6684. if (document.fullscreen !== undefined) {
  6685. _this.isFullscreen = document.fullscreen;
  6686. }
  6687. else if (document.mozFullScreen !== undefined) {
  6688. _this.isFullscreen = document.mozFullScreen;
  6689. }
  6690. else if (document.webkitIsFullScreen !== undefined) {
  6691. _this.isFullscreen = document.webkitIsFullScreen;
  6692. }
  6693. else if (document.msIsFullScreen !== undefined) {
  6694. _this.isFullscreen = document.msIsFullScreen;
  6695. }
  6696. // Pointer lock
  6697. if (_this.isFullscreen && _this._pointerLockRequested) {
  6698. canvas.requestPointerLock = canvas.requestPointerLock ||
  6699. canvas.msRequestPointerLock ||
  6700. canvas.mozRequestPointerLock ||
  6701. canvas.webkitRequestPointerLock;
  6702. if (canvas.requestPointerLock) {
  6703. canvas.requestPointerLock();
  6704. }
  6705. }
  6706. };
  6707. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6708. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6709. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6710. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6711. // Pointer lock
  6712. this._onPointerLockChange = function () {
  6713. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6714. document.webkitPointerLockElement === canvas ||
  6715. document.msPointerLockElement === canvas ||
  6716. document.pointerLockElement === canvas);
  6717. };
  6718. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6719. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6720. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6721. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6722. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6723. Engine.audioEngine = new BABYLON.AudioEngine();
  6724. }
  6725. //default loading screen
  6726. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6727. //Load WebVR Devices
  6728. if (options.autoEnableWebVR) {
  6729. this.initWebVR();
  6730. }
  6731. //Detect if we are running on a faulty buggy OS.
  6732. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6733. //ua sniffing is the tool of the devil.
  6734. this._badOS = regexp.test(navigator.userAgent);
  6735. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6736. }
  6737. Object.defineProperty(Engine, "NEVER", {
  6738. get: function () {
  6739. return Engine._NEVER;
  6740. },
  6741. enumerable: true,
  6742. configurable: true
  6743. });
  6744. Object.defineProperty(Engine, "ALWAYS", {
  6745. get: function () {
  6746. return Engine._ALWAYS;
  6747. },
  6748. enumerable: true,
  6749. configurable: true
  6750. });
  6751. Object.defineProperty(Engine, "LESS", {
  6752. get: function () {
  6753. return Engine._LESS;
  6754. },
  6755. enumerable: true,
  6756. configurable: true
  6757. });
  6758. Object.defineProperty(Engine, "EQUAL", {
  6759. get: function () {
  6760. return Engine._EQUAL;
  6761. },
  6762. enumerable: true,
  6763. configurable: true
  6764. });
  6765. Object.defineProperty(Engine, "LEQUAL", {
  6766. get: function () {
  6767. return Engine._LEQUAL;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(Engine, "GREATER", {
  6773. get: function () {
  6774. return Engine._GREATER;
  6775. },
  6776. enumerable: true,
  6777. configurable: true
  6778. });
  6779. Object.defineProperty(Engine, "GEQUAL", {
  6780. get: function () {
  6781. return Engine._GEQUAL;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(Engine, "NOTEQUAL", {
  6787. get: function () {
  6788. return Engine._NOTEQUAL;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Engine, "KEEP", {
  6794. get: function () {
  6795. return Engine._KEEP;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Engine, "REPLACE", {
  6801. get: function () {
  6802. return Engine._REPLACE;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Engine, "INCR", {
  6808. get: function () {
  6809. return Engine._INCR;
  6810. },
  6811. enumerable: true,
  6812. configurable: true
  6813. });
  6814. Object.defineProperty(Engine, "DECR", {
  6815. get: function () {
  6816. return Engine._DECR;
  6817. },
  6818. enumerable: true,
  6819. configurable: true
  6820. });
  6821. Object.defineProperty(Engine, "INVERT", {
  6822. get: function () {
  6823. return Engine._INVERT;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(Engine, "INCR_WRAP", {
  6829. get: function () {
  6830. return Engine._INCR_WRAP;
  6831. },
  6832. enumerable: true,
  6833. configurable: true
  6834. });
  6835. Object.defineProperty(Engine, "DECR_WRAP", {
  6836. get: function () {
  6837. return Engine._DECR_WRAP;
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6843. get: function () {
  6844. return Engine._ALPHA_DISABLE;
  6845. },
  6846. enumerable: true,
  6847. configurable: true
  6848. });
  6849. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6850. get: function () {
  6851. return Engine._ALPHA_ONEONE;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. Object.defineProperty(Engine, "ALPHA_ADD", {
  6857. get: function () {
  6858. return Engine._ALPHA_ADD;
  6859. },
  6860. enumerable: true,
  6861. configurable: true
  6862. });
  6863. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6864. get: function () {
  6865. return Engine._ALPHA_COMBINE;
  6866. },
  6867. enumerable: true,
  6868. configurable: true
  6869. });
  6870. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6871. get: function () {
  6872. return Engine._ALPHA_SUBTRACT;
  6873. },
  6874. enumerable: true,
  6875. configurable: true
  6876. });
  6877. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6878. get: function () {
  6879. return Engine._ALPHA_MULTIPLY;
  6880. },
  6881. enumerable: true,
  6882. configurable: true
  6883. });
  6884. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6885. get: function () {
  6886. return Engine._ALPHA_MAXIMIZED;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6892. get: function () {
  6893. return Engine._DELAYLOADSTATE_NONE;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6899. get: function () {
  6900. return Engine._DELAYLOADSTATE_LOADED;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6906. get: function () {
  6907. return Engine._DELAYLOADSTATE_LOADING;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6913. get: function () {
  6914. return Engine._DELAYLOADSTATE_NOTLOADED;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6920. get: function () {
  6921. return Engine._TEXTUREFORMAT_ALPHA;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6927. get: function () {
  6928. return Engine._TEXTUREFORMAT_LUMINANCE;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6934. get: function () {
  6935. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6941. get: function () {
  6942. return Engine._TEXTUREFORMAT_RGB;
  6943. },
  6944. enumerable: true,
  6945. configurable: true
  6946. });
  6947. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6948. get: function () {
  6949. return Engine._TEXTUREFORMAT_RGBA;
  6950. },
  6951. enumerable: true,
  6952. configurable: true
  6953. });
  6954. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6955. get: function () {
  6956. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6962. get: function () {
  6963. return Engine._TEXTURETYPE_FLOAT;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6969. get: function () {
  6970. return Engine._TEXTURETYPE_HALF_FLOAT;
  6971. },
  6972. enumerable: true,
  6973. configurable: true
  6974. });
  6975. Object.defineProperty(Engine, "Version", {
  6976. get: function () {
  6977. return "2.6-alpha";
  6978. },
  6979. enumerable: true,
  6980. configurable: true
  6981. });
  6982. Object.defineProperty(Engine.prototype, "texturesSupported", {
  6983. get: function () {
  6984. return this._texturesSupported;
  6985. },
  6986. enumerable: true,
  6987. configurable: true
  6988. });
  6989. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  6990. get: function () {
  6991. return this._textureFormatInUse;
  6992. },
  6993. enumerable: true,
  6994. configurable: true
  6995. });
  6996. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6997. get: function () {
  6998. return this._webGLVersion;
  6999. },
  7000. enumerable: true,
  7001. configurable: true
  7002. });
  7003. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7004. /**
  7005. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7006. */
  7007. get: function () {
  7008. return this._isStencilEnable;
  7009. },
  7010. enumerable: true,
  7011. configurable: true
  7012. });
  7013. Engine.prototype._prepareWorkingCanvas = function () {
  7014. if (this._workingCanvas) {
  7015. return;
  7016. }
  7017. this._workingCanvas = document.createElement("canvas");
  7018. this._workingContext = this._workingCanvas.getContext("2d");
  7019. };
  7020. Engine.prototype.resetTextureCache = function () {
  7021. for (var index = 0; index < this._maxTextureChannels; index++) {
  7022. this._activeTexturesCache[index] = null;
  7023. }
  7024. };
  7025. Engine.prototype.getGlInfo = function () {
  7026. return {
  7027. vendor: this._glVendor,
  7028. renderer: this._glRenderer,
  7029. version: this._glVersion
  7030. };
  7031. };
  7032. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7033. if (useScreen === void 0) { useScreen = false; }
  7034. var viewport = camera.viewport;
  7035. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7036. };
  7037. Engine.prototype.getRenderWidth = function (useScreen) {
  7038. if (useScreen === void 0) { useScreen = false; }
  7039. if (!useScreen && this._currentRenderTarget) {
  7040. return this._currentRenderTarget._width;
  7041. }
  7042. return this._renderingCanvas.width;
  7043. };
  7044. Engine.prototype.getRenderHeight = function (useScreen) {
  7045. if (useScreen === void 0) { useScreen = false; }
  7046. if (!useScreen && this._currentRenderTarget) {
  7047. return this._currentRenderTarget._height;
  7048. }
  7049. return this._renderingCanvas.height;
  7050. };
  7051. Engine.prototype.getRenderingCanvas = function () {
  7052. return this._renderingCanvas;
  7053. };
  7054. Engine.prototype.getRenderingCanvasClientRect = function () {
  7055. return this._renderingCanvas.getBoundingClientRect();
  7056. };
  7057. Engine.prototype.setHardwareScalingLevel = function (level) {
  7058. this._hardwareScalingLevel = level;
  7059. this.resize();
  7060. };
  7061. Engine.prototype.getHardwareScalingLevel = function () {
  7062. return this._hardwareScalingLevel;
  7063. };
  7064. Engine.prototype.getLoadedTexturesCache = function () {
  7065. return this._loadedTexturesCache;
  7066. };
  7067. Engine.prototype.getCaps = function () {
  7068. return this._caps;
  7069. };
  7070. Object.defineProperty(Engine.prototype, "drawCalls", {
  7071. get: function () {
  7072. return this._drawCalls.current;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7078. get: function () {
  7079. return this._drawCalls;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Engine.prototype.getDepthFunction = function () {
  7085. return this._depthCullingState.depthFunc;
  7086. };
  7087. Engine.prototype.setDepthFunction = function (depthFunc) {
  7088. this._depthCullingState.depthFunc = depthFunc;
  7089. };
  7090. Engine.prototype.setDepthFunctionToGreater = function () {
  7091. this._depthCullingState.depthFunc = this._gl.GREATER;
  7092. };
  7093. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7094. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7095. };
  7096. Engine.prototype.setDepthFunctionToLess = function () {
  7097. this._depthCullingState.depthFunc = this._gl.LESS;
  7098. };
  7099. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7100. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7101. };
  7102. Engine.prototype.getStencilBuffer = function () {
  7103. return this._stencilState.stencilTest;
  7104. };
  7105. Engine.prototype.setStencilBuffer = function (enable) {
  7106. this._stencilState.stencilTest = enable;
  7107. };
  7108. Engine.prototype.getStencilMask = function () {
  7109. return this._stencilState.stencilMask;
  7110. };
  7111. Engine.prototype.setStencilMask = function (mask) {
  7112. this._stencilState.stencilMask = mask;
  7113. };
  7114. Engine.prototype.getStencilFunction = function () {
  7115. return this._stencilState.stencilFunc;
  7116. };
  7117. Engine.prototype.getStencilFunctionReference = function () {
  7118. return this._stencilState.stencilFuncRef;
  7119. };
  7120. Engine.prototype.getStencilFunctionMask = function () {
  7121. return this._stencilState.stencilFuncMask;
  7122. };
  7123. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7124. this._stencilState.stencilFunc = stencilFunc;
  7125. };
  7126. Engine.prototype.setStencilFunctionReference = function (reference) {
  7127. this._stencilState.stencilFuncRef = reference;
  7128. };
  7129. Engine.prototype.setStencilFunctionMask = function (mask) {
  7130. this._stencilState.stencilFuncMask = mask;
  7131. };
  7132. Engine.prototype.getStencilOperationFail = function () {
  7133. return this._stencilState.stencilOpStencilFail;
  7134. };
  7135. Engine.prototype.getStencilOperationDepthFail = function () {
  7136. return this._stencilState.stencilOpDepthFail;
  7137. };
  7138. Engine.prototype.getStencilOperationPass = function () {
  7139. return this._stencilState.stencilOpStencilDepthPass;
  7140. };
  7141. Engine.prototype.setStencilOperationFail = function (operation) {
  7142. this._stencilState.stencilOpStencilFail = operation;
  7143. };
  7144. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7145. this._stencilState.stencilOpDepthFail = operation;
  7146. };
  7147. Engine.prototype.setStencilOperationPass = function (operation) {
  7148. this._stencilState.stencilOpStencilDepthPass = operation;
  7149. };
  7150. /**
  7151. * stop executing a render loop function and remove it from the execution array
  7152. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7153. */
  7154. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7155. if (!renderFunction) {
  7156. this._activeRenderLoops = [];
  7157. return;
  7158. }
  7159. var index = this._activeRenderLoops.indexOf(renderFunction);
  7160. if (index >= 0) {
  7161. this._activeRenderLoops.splice(index, 1);
  7162. }
  7163. };
  7164. Engine.prototype._renderLoop = function () {
  7165. var shouldRender = true;
  7166. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7167. shouldRender = false;
  7168. }
  7169. if (shouldRender) {
  7170. // Start new frame
  7171. this.beginFrame();
  7172. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7173. var renderFunction = this._activeRenderLoops[index];
  7174. renderFunction();
  7175. }
  7176. // Present
  7177. this.endFrame();
  7178. }
  7179. if (this._activeRenderLoops.length > 0) {
  7180. // Register new frame
  7181. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7182. }
  7183. else {
  7184. this._renderingQueueLaunched = false;
  7185. }
  7186. };
  7187. /**
  7188. * Register and execute a render loop. The engine can have more than one render function.
  7189. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7190. * @example
  7191. * engine.runRenderLoop(function () {
  7192. * scene.render()
  7193. * })
  7194. */
  7195. Engine.prototype.runRenderLoop = function (renderFunction) {
  7196. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7197. return;
  7198. }
  7199. this._activeRenderLoops.push(renderFunction);
  7200. if (!this._renderingQueueLaunched) {
  7201. this._renderingQueueLaunched = true;
  7202. this._bindedRenderFunction = this._renderLoop.bind(this);
  7203. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7204. }
  7205. };
  7206. /**
  7207. * Toggle full screen mode.
  7208. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7209. * @param {any} options - an options object to be sent to the requestFullscreen function
  7210. */
  7211. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7212. if (this.isFullscreen) {
  7213. BABYLON.Tools.ExitFullscreen();
  7214. }
  7215. else {
  7216. this._pointerLockRequested = requestPointerLock;
  7217. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7218. }
  7219. };
  7220. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7221. if (stencil === void 0) { stencil = false; }
  7222. this.applyStates();
  7223. var mode = 0;
  7224. if (backBuffer) {
  7225. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7226. mode |= this._gl.COLOR_BUFFER_BIT;
  7227. }
  7228. if (depth) {
  7229. this._gl.clearDepth(1.0);
  7230. mode |= this._gl.DEPTH_BUFFER_BIT;
  7231. }
  7232. if (stencil) {
  7233. this._gl.clearStencil(0);
  7234. mode |= this._gl.STENCIL_BUFFER_BIT;
  7235. }
  7236. this._gl.clear(mode);
  7237. };
  7238. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7239. var gl = this._gl;
  7240. // Save state
  7241. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7242. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7243. // Change state
  7244. gl.enable(gl.SCISSOR_TEST);
  7245. gl.scissor(x, y, width, height);
  7246. // Clear
  7247. this.clear(clearColor, true, true, true);
  7248. // Restore state
  7249. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7250. if (curScissor === true) {
  7251. gl.enable(gl.SCISSOR_TEST);
  7252. }
  7253. else {
  7254. gl.disable(gl.SCISSOR_TEST);
  7255. }
  7256. };
  7257. /**
  7258. * Set the WebGL's viewport
  7259. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7260. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7261. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7262. */
  7263. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7264. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7265. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7266. var x = viewport.x || 0;
  7267. var y = viewport.y || 0;
  7268. this._cachedViewport = viewport;
  7269. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7270. };
  7271. /**
  7272. * Directly set the WebGL Viewport
  7273. * The x, y, width & height are directly passed to the WebGL call
  7274. * @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.
  7275. */
  7276. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7277. var currentViewport = this._cachedViewport;
  7278. this._cachedViewport = null;
  7279. this._gl.viewport(x, y, width, height);
  7280. return currentViewport;
  7281. };
  7282. Engine.prototype.beginFrame = function () {
  7283. this._measureFps();
  7284. };
  7285. Engine.prototype.endFrame = function () {
  7286. //force a flush in case we are using a bad OS.
  7287. if (this._badOS) {
  7288. this.flushFramebuffer();
  7289. }
  7290. //submit frame to the vr device, if enabled
  7291. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7292. this._vrDisplayEnabled.submitFrame();
  7293. }
  7294. };
  7295. /**
  7296. * resize the view according to the canvas' size.
  7297. * @example
  7298. * window.addEventListener("resize", function () {
  7299. * engine.resize();
  7300. * });
  7301. */
  7302. Engine.prototype.resize = function () {
  7303. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7304. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7305. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7306. };
  7307. /**
  7308. * force a specific size of the canvas
  7309. * @param {number} width - the new canvas' width
  7310. * @param {number} height - the new canvas' height
  7311. */
  7312. Engine.prototype.setSize = function (width, height) {
  7313. this._renderingCanvas.width = width;
  7314. this._renderingCanvas.height = height;
  7315. for (var index = 0; index < this.scenes.length; index++) {
  7316. var scene = this.scenes[index];
  7317. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7318. var cam = scene.cameras[camIndex];
  7319. cam._currentRenderId = 0;
  7320. }
  7321. }
  7322. };
  7323. //WebVR functions
  7324. Engine.prototype.initWebVR = function () {
  7325. if (!this.vrDisplaysPromise) {
  7326. this._getVRDisplays();
  7327. }
  7328. };
  7329. Engine.prototype.enableVR = function (vrDevice) {
  7330. this._vrDisplayEnabled = vrDevice;
  7331. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7332. };
  7333. Engine.prototype.disableVR = function () {
  7334. if (this._vrDisplayEnabled) {
  7335. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7336. }
  7337. };
  7338. Engine.prototype._getVRDisplays = function () {
  7339. var _this = this;
  7340. var getWebVRDevices = function (devices) {
  7341. var size = devices.length;
  7342. var i = 0;
  7343. _this._vrDisplays = devices.filter(function (device) {
  7344. return devices[i] instanceof VRDisplay;
  7345. });
  7346. return _this._vrDisplays;
  7347. };
  7348. //using a key due to typescript
  7349. if (navigator.getVRDisplays) {
  7350. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7351. }
  7352. };
  7353. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7354. this._currentRenderTarget = texture;
  7355. this.bindUnboundFramebuffer(texture._framebuffer);
  7356. var gl = this._gl;
  7357. if (texture.isCube) {
  7358. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7359. }
  7360. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7361. this.wipeCaches();
  7362. };
  7363. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7364. if (this._currentFramebuffer !== framebuffer) {
  7365. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7366. this._currentFramebuffer = framebuffer;
  7367. }
  7368. };
  7369. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7370. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7371. this._currentRenderTarget = null;
  7372. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7373. var gl = this._gl;
  7374. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7375. gl.generateMipmap(gl.TEXTURE_2D);
  7376. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7377. }
  7378. this.bindUnboundFramebuffer(null);
  7379. };
  7380. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7381. if (texture.generateMipMaps) {
  7382. var gl = this._gl;
  7383. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7384. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7385. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7386. }
  7387. };
  7388. Engine.prototype.flushFramebuffer = function () {
  7389. this._gl.flush();
  7390. };
  7391. Engine.prototype.restoreDefaultFramebuffer = function () {
  7392. this._currentRenderTarget = null;
  7393. this.bindUnboundFramebuffer(null);
  7394. this.setViewport(this._cachedViewport);
  7395. this.wipeCaches();
  7396. };
  7397. // VBOs
  7398. Engine.prototype._resetVertexBufferBinding = function () {
  7399. this.bindArrayBuffer(null);
  7400. this._cachedVertexBuffers = null;
  7401. };
  7402. Engine.prototype.createVertexBuffer = function (vertices) {
  7403. var vbo = this._gl.createBuffer();
  7404. this.bindArrayBuffer(vbo);
  7405. if (vertices instanceof Float32Array) {
  7406. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7407. }
  7408. else {
  7409. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7410. }
  7411. this._resetVertexBufferBinding();
  7412. vbo.references = 1;
  7413. return vbo;
  7414. };
  7415. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7416. var vbo = this._gl.createBuffer();
  7417. this.bindArrayBuffer(vbo);
  7418. if (vertices instanceof Float32Array) {
  7419. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7420. }
  7421. else {
  7422. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7423. }
  7424. this._resetVertexBufferBinding();
  7425. vbo.references = 1;
  7426. return vbo;
  7427. };
  7428. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7429. this.bindArrayBuffer(vertexBuffer);
  7430. if (offset === undefined) {
  7431. offset = 0;
  7432. }
  7433. if (count === undefined) {
  7434. if (vertices instanceof Float32Array) {
  7435. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7436. }
  7437. else {
  7438. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7439. }
  7440. }
  7441. else {
  7442. if (vertices instanceof Float32Array) {
  7443. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7444. }
  7445. else {
  7446. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7447. }
  7448. }
  7449. this._resetVertexBufferBinding();
  7450. };
  7451. Engine.prototype._resetIndexBufferBinding = function () {
  7452. this.bindIndexBuffer(null);
  7453. this._cachedIndexBuffer = null;
  7454. };
  7455. Engine.prototype.createIndexBuffer = function (indices) {
  7456. var vbo = this._gl.createBuffer();
  7457. this.bindIndexBuffer(vbo);
  7458. // Check for 32 bits indices
  7459. var arrayBuffer;
  7460. var need32Bits = false;
  7461. if (this._caps.uintIndices) {
  7462. for (var index = 0; index < indices.length; index++) {
  7463. if (indices[index] > 65535) {
  7464. need32Bits = true;
  7465. break;
  7466. }
  7467. }
  7468. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7469. }
  7470. else {
  7471. arrayBuffer = new Uint16Array(indices);
  7472. }
  7473. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7474. this._resetIndexBufferBinding();
  7475. vbo.references = 1;
  7476. vbo.is32Bits = need32Bits;
  7477. return vbo;
  7478. };
  7479. Engine.prototype.bindArrayBuffer = function (buffer) {
  7480. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7481. };
  7482. Engine.prototype.bindIndexBuffer = function (buffer) {
  7483. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7484. };
  7485. Engine.prototype.bindBuffer = function (buffer, target) {
  7486. if (this._currentBoundBuffer[target] !== buffer) {
  7487. this._gl.bindBuffer(target, buffer);
  7488. this._currentBoundBuffer[target] = buffer;
  7489. }
  7490. };
  7491. Engine.prototype.updateArrayBuffer = function (data) {
  7492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7493. };
  7494. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7495. var pointer = this._currentBufferPointers[indx];
  7496. var changed = false;
  7497. if (!pointer) {
  7498. changed = true;
  7499. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7500. }
  7501. else {
  7502. if (pointer.buffer !== buffer) {
  7503. pointer.buffer = buffer;
  7504. changed = true;
  7505. }
  7506. if (pointer.size !== size) {
  7507. pointer.size = size;
  7508. changed = true;
  7509. }
  7510. if (pointer.type !== type) {
  7511. pointer.type = type;
  7512. changed = true;
  7513. }
  7514. if (pointer.normalized !== normalized) {
  7515. pointer.normalized = normalized;
  7516. changed = true;
  7517. }
  7518. if (pointer.stride !== stride) {
  7519. pointer.stride = stride;
  7520. changed = true;
  7521. }
  7522. if (pointer.offset !== offset) {
  7523. pointer.offset = offset;
  7524. changed = true;
  7525. }
  7526. }
  7527. if (changed) {
  7528. this.bindArrayBuffer(buffer);
  7529. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7530. }
  7531. };
  7532. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7533. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7534. this._cachedVertexBuffers = vertexBuffer;
  7535. this._cachedEffectForVertexBuffers = effect;
  7536. var attributesCount = effect.getAttributesCount();
  7537. var offset = 0;
  7538. for (var index = 0; index < attributesCount; index++) {
  7539. if (index < vertexDeclaration.length) {
  7540. var order = effect.getAttributeLocation(index);
  7541. if (order >= 0) {
  7542. if (!this._vertexAttribArraysEnabled[order]) {
  7543. this._gl.enableVertexAttribArray(order);
  7544. this._vertexAttribArraysEnabled[order] = true;
  7545. }
  7546. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7547. }
  7548. offset += vertexDeclaration[index] * 4;
  7549. }
  7550. else {
  7551. //disable effect attributes that have no data
  7552. var order = effect.getAttributeLocation(index);
  7553. if (this._vertexAttribArraysEnabled[order]) {
  7554. this._gl.disableVertexAttribArray(order);
  7555. this._vertexAttribArraysEnabled[order] = false;
  7556. }
  7557. }
  7558. }
  7559. }
  7560. if (this._cachedIndexBuffer !== indexBuffer) {
  7561. this._cachedIndexBuffer = indexBuffer;
  7562. this.bindIndexBuffer(indexBuffer);
  7563. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7564. }
  7565. };
  7566. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7567. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7568. this._cachedVertexBuffers = vertexBuffers;
  7569. this._cachedEffectForVertexBuffers = effect;
  7570. var attributes = effect.getAttributesNames();
  7571. for (var index = 0; index < attributes.length; index++) {
  7572. var order = effect.getAttributeLocation(index);
  7573. if (order >= 0) {
  7574. var vertexBuffer = vertexBuffers[attributes[index]];
  7575. if (!vertexBuffer) {
  7576. if (this._vertexAttribArraysEnabled[order]) {
  7577. this._gl.disableVertexAttribArray(order);
  7578. this._vertexAttribArraysEnabled[order] = false;
  7579. }
  7580. continue;
  7581. }
  7582. if (!this._vertexAttribArraysEnabled[order]) {
  7583. this._gl.enableVertexAttribArray(order);
  7584. this._vertexAttribArraysEnabled[order] = true;
  7585. }
  7586. var buffer = vertexBuffer.getBuffer();
  7587. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7588. if (vertexBuffer.getIsInstanced()) {
  7589. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7590. this._currentInstanceLocations.push(order);
  7591. this._currentInstanceBuffers.push(buffer);
  7592. }
  7593. }
  7594. }
  7595. }
  7596. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7597. this._cachedIndexBuffer = indexBuffer;
  7598. this.bindIndexBuffer(indexBuffer);
  7599. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7600. }
  7601. };
  7602. Engine.prototype.unbindInstanceAttributes = function () {
  7603. var boundBuffer;
  7604. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7605. var instancesBuffer = this._currentInstanceBuffers[i];
  7606. if (boundBuffer != instancesBuffer) {
  7607. boundBuffer = instancesBuffer;
  7608. this.bindArrayBuffer(instancesBuffer);
  7609. }
  7610. var offsetLocation = this._currentInstanceLocations[i];
  7611. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7612. }
  7613. this._currentInstanceBuffers.length = 0;
  7614. this._currentInstanceLocations.length = 0;
  7615. };
  7616. Engine.prototype._releaseBuffer = function (buffer) {
  7617. buffer.references--;
  7618. if (buffer.references === 0) {
  7619. this._gl.deleteBuffer(buffer);
  7620. return true;
  7621. }
  7622. return false;
  7623. };
  7624. Engine.prototype.createInstancesBuffer = function (capacity) {
  7625. var buffer = this._gl.createBuffer();
  7626. buffer.capacity = capacity;
  7627. this.bindArrayBuffer(buffer);
  7628. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7629. return buffer;
  7630. };
  7631. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7632. this._gl.deleteBuffer(buffer);
  7633. };
  7634. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7635. this.bindArrayBuffer(instancesBuffer);
  7636. if (data) {
  7637. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7638. }
  7639. if (offsetLocations[0].index !== undefined) {
  7640. var stride = 0;
  7641. for (var i = 0; i < offsetLocations.length; i++) {
  7642. var ai = offsetLocations[i];
  7643. stride += ai.attributeSize * 4;
  7644. }
  7645. for (var i = 0; i < offsetLocations.length; i++) {
  7646. var ai = offsetLocations[i];
  7647. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7648. this._gl.enableVertexAttribArray(ai.index);
  7649. this._vertexAttribArraysEnabled[ai.index] = true;
  7650. }
  7651. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7652. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7653. this._currentInstanceLocations.push(ai.index);
  7654. this._currentInstanceBuffers.push(instancesBuffer);
  7655. }
  7656. }
  7657. else {
  7658. for (var index = 0; index < 4; index++) {
  7659. var offsetLocation = offsetLocations[index];
  7660. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7661. this._gl.enableVertexAttribArray(offsetLocation);
  7662. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7663. }
  7664. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7665. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7666. this._currentInstanceLocations.push(offsetLocation);
  7667. this._currentInstanceBuffers.push(instancesBuffer);
  7668. }
  7669. }
  7670. };
  7671. Engine.prototype.applyStates = function () {
  7672. this._depthCullingState.apply(this._gl);
  7673. this._stencilState.apply(this._gl);
  7674. this._alphaState.apply(this._gl);
  7675. };
  7676. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7677. // Apply states
  7678. this.applyStates();
  7679. this._drawCalls.addCount(1, false);
  7680. // Render
  7681. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7682. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7683. if (instancesCount) {
  7684. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7685. return;
  7686. }
  7687. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7688. };
  7689. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7690. // Apply states
  7691. this.applyStates();
  7692. this._drawCalls.addCount(1, false);
  7693. if (instancesCount) {
  7694. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7695. return;
  7696. }
  7697. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7698. };
  7699. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7700. // Apply states
  7701. this.applyStates();
  7702. this._drawCalls.addCount(1, false);
  7703. if (instancesCount) {
  7704. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7705. return;
  7706. }
  7707. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7708. };
  7709. // Shaders
  7710. Engine.prototype._releaseEffect = function (effect) {
  7711. if (this._compiledEffects[effect._key]) {
  7712. delete this._compiledEffects[effect._key];
  7713. if (effect.getProgram()) {
  7714. this._gl.deleteProgram(effect.getProgram());
  7715. }
  7716. }
  7717. };
  7718. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7719. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7720. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7721. var name = vertex + "+" + fragment + "@" + defines;
  7722. if (this._compiledEffects[name]) {
  7723. return this._compiledEffects[name];
  7724. }
  7725. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7726. effect._key = name;
  7727. this._compiledEffects[name] = effect;
  7728. return effect;
  7729. };
  7730. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7731. if (uniformsNames === void 0) { uniformsNames = []; }
  7732. if (samplers === void 0) { samplers = []; }
  7733. if (defines === void 0) { defines = ""; }
  7734. return this.createEffect({
  7735. vertex: "particles",
  7736. fragmentElement: fragmentName
  7737. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7738. };
  7739. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7740. context = context || this._gl;
  7741. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7742. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7743. var shaderProgram = context.createProgram();
  7744. context.attachShader(shaderProgram, vertexShader);
  7745. context.attachShader(shaderProgram, fragmentShader);
  7746. context.linkProgram(shaderProgram);
  7747. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7748. if (!linked) {
  7749. var error = context.getProgramInfoLog(shaderProgram);
  7750. if (error) {
  7751. throw new Error(error);
  7752. }
  7753. }
  7754. context.deleteShader(vertexShader);
  7755. context.deleteShader(fragmentShader);
  7756. return shaderProgram;
  7757. };
  7758. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7759. var results = [];
  7760. for (var index = 0; index < uniformsNames.length; index++) {
  7761. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7762. }
  7763. return results;
  7764. };
  7765. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7766. var results = [];
  7767. for (var index = 0; index < attributesNames.length; index++) {
  7768. try {
  7769. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7770. }
  7771. catch (e) {
  7772. results.push(-1);
  7773. }
  7774. }
  7775. return results;
  7776. };
  7777. Engine.prototype.enableEffect = function (effect) {
  7778. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7779. // if (effect && effect.onBind) {
  7780. // effect.onBind(effect);
  7781. // }
  7782. // return;
  7783. //}
  7784. // Use program
  7785. this.setProgram(effect.getProgram());
  7786. this._currentEffect = effect;
  7787. if (effect.onBind) {
  7788. effect.onBind(effect);
  7789. }
  7790. };
  7791. Engine.prototype.setIntArray = function (uniform, array) {
  7792. if (!uniform)
  7793. return;
  7794. this._gl.uniform1iv(uniform, array);
  7795. };
  7796. Engine.prototype.setIntArray2 = function (uniform, array) {
  7797. if (!uniform || array.length % 2 !== 0)
  7798. return;
  7799. this._gl.uniform2iv(uniform, array);
  7800. };
  7801. Engine.prototype.setIntArray3 = function (uniform, array) {
  7802. if (!uniform || array.length % 3 !== 0)
  7803. return;
  7804. this._gl.uniform3iv(uniform, array);
  7805. };
  7806. Engine.prototype.setIntArray4 = function (uniform, array) {
  7807. if (!uniform || array.length % 4 !== 0)
  7808. return;
  7809. this._gl.uniform4iv(uniform, array);
  7810. };
  7811. Engine.prototype.setFloatArray = function (uniform, array) {
  7812. if (!uniform)
  7813. return;
  7814. this._gl.uniform1fv(uniform, array);
  7815. };
  7816. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7817. if (!uniform || array.length % 2 !== 0)
  7818. return;
  7819. this._gl.uniform2fv(uniform, array);
  7820. };
  7821. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7822. if (!uniform || array.length % 3 !== 0)
  7823. return;
  7824. this._gl.uniform3fv(uniform, array);
  7825. };
  7826. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7827. if (!uniform || array.length % 4 !== 0)
  7828. return;
  7829. this._gl.uniform4fv(uniform, array);
  7830. };
  7831. Engine.prototype.setArray = function (uniform, array) {
  7832. if (!uniform)
  7833. return;
  7834. this._gl.uniform1fv(uniform, array);
  7835. };
  7836. Engine.prototype.setArray2 = function (uniform, array) {
  7837. if (!uniform || array.length % 2 !== 0)
  7838. return;
  7839. this._gl.uniform2fv(uniform, array);
  7840. };
  7841. Engine.prototype.setArray3 = function (uniform, array) {
  7842. if (!uniform || array.length % 3 !== 0)
  7843. return;
  7844. this._gl.uniform3fv(uniform, array);
  7845. };
  7846. Engine.prototype.setArray4 = function (uniform, array) {
  7847. if (!uniform || array.length % 4 !== 0)
  7848. return;
  7849. this._gl.uniform4fv(uniform, array);
  7850. };
  7851. Engine.prototype.setMatrices = function (uniform, matrices) {
  7852. if (!uniform)
  7853. return;
  7854. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7855. };
  7856. Engine.prototype.setMatrix = function (uniform, matrix) {
  7857. if (!uniform)
  7858. return;
  7859. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7860. };
  7861. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7862. if (!uniform)
  7863. return;
  7864. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7865. };
  7866. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7867. if (!uniform)
  7868. return;
  7869. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7870. };
  7871. Engine.prototype.setFloat = function (uniform, value) {
  7872. if (!uniform)
  7873. return;
  7874. this._gl.uniform1f(uniform, value);
  7875. };
  7876. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7877. if (!uniform)
  7878. return;
  7879. this._gl.uniform2f(uniform, x, y);
  7880. };
  7881. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7882. if (!uniform)
  7883. return;
  7884. this._gl.uniform3f(uniform, x, y, z);
  7885. };
  7886. Engine.prototype.setBool = function (uniform, bool) {
  7887. if (!uniform)
  7888. return;
  7889. this._gl.uniform1i(uniform, bool);
  7890. };
  7891. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7892. if (!uniform)
  7893. return;
  7894. this._gl.uniform4f(uniform, x, y, z, w);
  7895. };
  7896. Engine.prototype.setColor3 = function (uniform, color3) {
  7897. if (!uniform)
  7898. return;
  7899. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7900. };
  7901. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7902. if (!uniform)
  7903. return;
  7904. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7905. };
  7906. // States
  7907. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7908. if (zOffset === void 0) { zOffset = 0; }
  7909. if (reverseSide === void 0) { reverseSide = false; }
  7910. // Culling
  7911. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7912. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7913. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7914. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7915. if (culling) {
  7916. this._depthCullingState.cullFace = cullFace;
  7917. this._depthCullingState.cull = true;
  7918. }
  7919. else {
  7920. this._depthCullingState.cull = false;
  7921. }
  7922. }
  7923. // Z offset
  7924. this._depthCullingState.zOffset = zOffset;
  7925. };
  7926. Engine.prototype.setDepthBuffer = function (enable) {
  7927. this._depthCullingState.depthTest = enable;
  7928. };
  7929. Engine.prototype.getDepthWrite = function () {
  7930. return this._depthCullingState.depthMask;
  7931. };
  7932. Engine.prototype.setDepthWrite = function (enable) {
  7933. this._depthCullingState.depthMask = enable;
  7934. };
  7935. Engine.prototype.setColorWrite = function (enable) {
  7936. this._gl.colorMask(enable, enable, enable, enable);
  7937. };
  7938. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7939. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7940. if (this._alphaMode === mode) {
  7941. return;
  7942. }
  7943. switch (mode) {
  7944. case Engine.ALPHA_DISABLE:
  7945. this._alphaState.alphaBlend = false;
  7946. break;
  7947. case Engine.ALPHA_COMBINE:
  7948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7949. this._alphaState.alphaBlend = true;
  7950. break;
  7951. case Engine.ALPHA_ONEONE:
  7952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7953. this._alphaState.alphaBlend = true;
  7954. break;
  7955. case Engine.ALPHA_ADD:
  7956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7957. this._alphaState.alphaBlend = true;
  7958. break;
  7959. case Engine.ALPHA_SUBTRACT:
  7960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7961. this._alphaState.alphaBlend = true;
  7962. break;
  7963. case Engine.ALPHA_MULTIPLY:
  7964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7965. this._alphaState.alphaBlend = true;
  7966. break;
  7967. case Engine.ALPHA_MAXIMIZED:
  7968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7969. this._alphaState.alphaBlend = true;
  7970. break;
  7971. }
  7972. if (!noDepthWriteChange) {
  7973. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7974. }
  7975. this._alphaMode = mode;
  7976. };
  7977. Engine.prototype.getAlphaMode = function () {
  7978. return this._alphaMode;
  7979. };
  7980. Engine.prototype.setAlphaTesting = function (enable) {
  7981. this._alphaTest = enable;
  7982. };
  7983. Engine.prototype.getAlphaTesting = function () {
  7984. return this._alphaTest;
  7985. };
  7986. // Textures
  7987. Engine.prototype.wipeCaches = function () {
  7988. this.resetTextureCache();
  7989. this._currentEffect = null;
  7990. this._stencilState.reset();
  7991. this._depthCullingState.reset();
  7992. this.setDepthFunctionToLessOrEqual();
  7993. this._alphaState.reset();
  7994. this._cachedVertexBuffers = null;
  7995. this._cachedIndexBuffer = null;
  7996. this._cachedEffectForVertexBuffers = null;
  7997. };
  7998. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7999. var gl = this._gl;
  8000. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8001. var magFilter = gl.NEAREST;
  8002. var minFilter = gl.NEAREST;
  8003. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  8004. magFilter = gl.LINEAR;
  8005. minFilter = gl.LINEAR;
  8006. }
  8007. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  8008. magFilter = gl.LINEAR;
  8009. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8010. }
  8011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  8012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  8013. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8014. texture.samplingMode = samplingMode;
  8015. };
  8016. /**
  8017. * Set the compressed texture format to use, based on the formats you have,
  8018. * the formats supported by the hardware / browser, and those currently implemented
  8019. * in BJS.
  8020. *
  8021. * Note: The result of this call is not taken into account texture is base64 or when
  8022. * using a database / manifest.
  8023. *
  8024. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8025. * and order do not matter.
  8026. * @returns The extension selected.
  8027. */
  8028. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8029. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8030. // code to allow the formats to be added as they can be developed / hw tested
  8031. if (this._texturesSupported[i] === '.astc')
  8032. continue;
  8033. if (this._texturesSupported[i] === '.pvr')
  8034. continue;
  8035. if (this._texturesSupported[i] === '.etc1')
  8036. continue;
  8037. if (this._texturesSupported[i] === '.etc2')
  8038. continue;
  8039. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8040. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8041. return this._textureFormatInUse = this._texturesSupported[i];
  8042. }
  8043. }
  8044. }
  8045. // actively set format to nothing, to allow this to be called more than once
  8046. // and possibly fail the 2nd time
  8047. return this._textureFormatInUse = null;
  8048. };
  8049. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8050. var _this = this;
  8051. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8052. if (onLoad === void 0) { onLoad = null; }
  8053. if (onError === void 0) { onError = null; }
  8054. if (buffer === void 0) { buffer = null; }
  8055. var texture = this._gl.createTexture();
  8056. var extension;
  8057. var fromData = false;
  8058. if (url.substr(0, 5) === "data:") {
  8059. fromData = true;
  8060. }
  8061. if (!fromData) {
  8062. var lastDot = url.lastIndexOf('.');
  8063. extension = url.substring(lastDot).toLowerCase();
  8064. if (this._textureFormatInUse && !fromData && !scene.database) {
  8065. extension = this._textureFormatInUse;
  8066. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8067. }
  8068. }
  8069. else {
  8070. var oldUrl = url;
  8071. fromData = oldUrl.split(':');
  8072. url = oldUrl;
  8073. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8074. }
  8075. var isDDS = (extension === ".dds");
  8076. var isTGA = (extension === ".tga");
  8077. scene._addPendingData(texture);
  8078. texture.url = url;
  8079. texture.noMipmap = noMipmap;
  8080. texture.references = 1;
  8081. texture.samplingMode = samplingMode;
  8082. texture.onLoadedCallbacks = [onLoad];
  8083. this._loadedTexturesCache.push(texture);
  8084. var onerror = function () {
  8085. scene._removePendingData(texture);
  8086. if (onError) {
  8087. onError();
  8088. }
  8089. };
  8090. var callback;
  8091. if (isTGA) {
  8092. callback = function (arrayBuffer) {
  8093. var data = new Uint8Array(arrayBuffer);
  8094. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8095. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8096. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8097. }, samplingMode);
  8098. };
  8099. if (!(fromData instanceof Array))
  8100. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8101. callback(arrayBuffer);
  8102. }, null, scene.database, true, onerror);
  8103. else
  8104. callback(buffer);
  8105. }
  8106. else if (isDDS) {
  8107. callback = function (data) {
  8108. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8109. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8110. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8111. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8112. }, samplingMode);
  8113. };
  8114. if (!(fromData instanceof Array))
  8115. BABYLON.Tools.LoadFile(url, function (data) {
  8116. callback(data);
  8117. }, null, scene.database, true, onerror);
  8118. else
  8119. callback(buffer);
  8120. }
  8121. else {
  8122. var onload = function (img) {
  8123. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8124. var isPot = (img.width === potWidth && img.height === potHeight);
  8125. if (!isPot) {
  8126. _this._prepareWorkingCanvas();
  8127. _this._workingCanvas.width = potWidth;
  8128. _this._workingCanvas.height = potHeight;
  8129. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8130. _this._workingContext.imageSmoothingEnabled = false;
  8131. _this._workingContext.mozImageSmoothingEnabled = false;
  8132. _this._workingContext.oImageSmoothingEnabled = false;
  8133. _this._workingContext.webkitImageSmoothingEnabled = false;
  8134. _this._workingContext.msImageSmoothingEnabled = false;
  8135. }
  8136. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8137. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8138. _this._workingContext.imageSmoothingEnabled = true;
  8139. _this._workingContext.mozImageSmoothingEnabled = true;
  8140. _this._workingContext.oImageSmoothingEnabled = true;
  8141. _this._workingContext.webkitImageSmoothingEnabled = true;
  8142. _this._workingContext.msImageSmoothingEnabled = true;
  8143. }
  8144. }
  8145. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8146. }, samplingMode);
  8147. };
  8148. if (!(fromData instanceof Array))
  8149. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8150. else
  8151. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8152. }
  8153. return texture;
  8154. };
  8155. Engine.prototype._getInternalFormat = function (format) {
  8156. var internalFormat = this._gl.RGBA;
  8157. switch (format) {
  8158. case Engine.TEXTUREFORMAT_ALPHA:
  8159. internalFormat = this._gl.ALPHA;
  8160. break;
  8161. case Engine.TEXTUREFORMAT_LUMINANCE:
  8162. internalFormat = this._gl.LUMINANCE;
  8163. break;
  8164. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8165. internalFormat = this._gl.LUMINANCE_ALPHA;
  8166. break;
  8167. case Engine.TEXTUREFORMAT_RGB:
  8168. internalFormat = this._gl.RGB;
  8169. break;
  8170. case Engine.TEXTUREFORMAT_RGBA:
  8171. internalFormat = this._gl.RGBA;
  8172. break;
  8173. }
  8174. return internalFormat;
  8175. };
  8176. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8177. if (compression === void 0) { compression = null; }
  8178. var internalFormat = this._getInternalFormat(format);
  8179. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8180. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8181. if (texture._width % 4 !== 0) {
  8182. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8183. }
  8184. if (compression) {
  8185. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8186. }
  8187. else {
  8188. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8189. }
  8190. if (texture.generateMipMaps) {
  8191. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8192. }
  8193. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8194. this.resetTextureCache();
  8195. texture.isReady = true;
  8196. };
  8197. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8198. if (compression === void 0) { compression = null; }
  8199. var texture = this._gl.createTexture();
  8200. texture._baseWidth = width;
  8201. texture._baseHeight = height;
  8202. texture._width = width;
  8203. texture._height = height;
  8204. texture.references = 1;
  8205. this.updateRawTexture(texture, data, format, invertY, compression);
  8206. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8207. // Filters
  8208. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8211. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8212. texture.samplingMode = samplingMode;
  8213. this._loadedTexturesCache.push(texture);
  8214. return texture;
  8215. };
  8216. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8217. var texture = this._gl.createTexture();
  8218. texture._baseWidth = width;
  8219. texture._baseHeight = height;
  8220. if (generateMipMaps) {
  8221. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8222. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8223. }
  8224. this.resetTextureCache();
  8225. texture._width = width;
  8226. texture._height = height;
  8227. texture.isReady = false;
  8228. texture.generateMipMaps = generateMipMaps;
  8229. texture.references = 1;
  8230. texture.samplingMode = samplingMode;
  8231. this.updateTextureSamplingMode(samplingMode, texture);
  8232. this._loadedTexturesCache.push(texture);
  8233. return texture;
  8234. };
  8235. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8236. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8237. if (texture.isCube) {
  8238. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8239. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8240. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8241. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8242. }
  8243. else {
  8244. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8245. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8246. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8247. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8248. }
  8249. };
  8250. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8251. if (premulAlpha === void 0) { premulAlpha = false; }
  8252. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8253. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8254. if (premulAlpha) {
  8255. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8256. }
  8257. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8258. if (texture.generateMipMaps) {
  8259. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8260. }
  8261. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8262. if (premulAlpha) {
  8263. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8264. }
  8265. this.resetTextureCache();
  8266. texture.isReady = true;
  8267. };
  8268. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8269. if (texture._isDisabled) {
  8270. return;
  8271. }
  8272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8273. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8274. try {
  8275. // Testing video texture support
  8276. if (this._videoTextureSupported === undefined) {
  8277. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8278. if (this._gl.getError() !== 0) {
  8279. this._videoTextureSupported = false;
  8280. }
  8281. else {
  8282. this._videoTextureSupported = true;
  8283. }
  8284. }
  8285. // Copy video through the current working canvas if video texture is not supported
  8286. if (!this._videoTextureSupported) {
  8287. if (!texture._workingCanvas) {
  8288. texture._workingCanvas = document.createElement("canvas");
  8289. texture._workingContext = texture._workingCanvas.getContext("2d");
  8290. texture._workingCanvas.width = texture._width;
  8291. texture._workingCanvas.height = texture._height;
  8292. }
  8293. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8294. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8295. }
  8296. else {
  8297. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8298. }
  8299. if (texture.generateMipMaps) {
  8300. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8301. }
  8302. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8303. this.resetTextureCache();
  8304. texture.isReady = true;
  8305. }
  8306. catch (ex) {
  8307. // Something unexpected
  8308. // Let's disable the texture
  8309. texture._isDisabled = true;
  8310. }
  8311. };
  8312. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8313. // old version had a "generateMipMaps" arg instead of options.
  8314. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8315. // in the same way, generateDepthBuffer is defaulted to true
  8316. var generateMipMaps = false;
  8317. var generateDepthBuffer = true;
  8318. var generateStencilBuffer = false;
  8319. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8320. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8321. if (options !== undefined) {
  8322. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8323. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8324. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8325. type = options.type === undefined ? type : options.type;
  8326. if (options.samplingMode !== undefined) {
  8327. samplingMode = options.samplingMode;
  8328. }
  8329. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8330. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8331. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8332. }
  8333. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8334. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8335. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8336. }
  8337. }
  8338. var gl = this._gl;
  8339. var texture = gl.createTexture();
  8340. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8341. var width = size.width || size;
  8342. var height = size.height || size;
  8343. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8344. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8345. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8346. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8347. }
  8348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8350. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8352. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8353. var depthStencilBuffer;
  8354. // Create the depth/stencil buffer
  8355. if (generateStencilBuffer) {
  8356. depthStencilBuffer = gl.createRenderbuffer();
  8357. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8358. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8359. }
  8360. else if (generateDepthBuffer) {
  8361. depthStencilBuffer = gl.createRenderbuffer();
  8362. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8363. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8364. }
  8365. // Create the framebuffer
  8366. var framebuffer = gl.createFramebuffer();
  8367. this.bindUnboundFramebuffer(framebuffer);
  8368. // Manage attachments
  8369. if (generateStencilBuffer) {
  8370. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8371. }
  8372. else if (generateDepthBuffer) {
  8373. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8374. }
  8375. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8376. if (generateMipMaps) {
  8377. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8378. }
  8379. // Unbind
  8380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8381. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8382. this.bindUnboundFramebuffer(null);
  8383. texture._framebuffer = framebuffer;
  8384. if (generateDepthBuffer) {
  8385. texture._depthBuffer = depthStencilBuffer;
  8386. }
  8387. texture._baseWidth = width;
  8388. texture._baseHeight = height;
  8389. texture._width = width;
  8390. texture._height = height;
  8391. texture.isReady = true;
  8392. texture.generateMipMaps = generateMipMaps;
  8393. texture.references = 1;
  8394. texture.samplingMode = samplingMode;
  8395. texture.type = type;
  8396. this.resetTextureCache();
  8397. this._loadedTexturesCache.push(texture);
  8398. return texture;
  8399. };
  8400. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8401. var gl = this._gl;
  8402. var texture = gl.createTexture();
  8403. var generateMipMaps = true;
  8404. var generateDepthBuffer = true;
  8405. var generateStencilBuffer = false;
  8406. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8407. if (options !== undefined) {
  8408. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8409. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8410. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8411. if (options.samplingMode !== undefined) {
  8412. samplingMode = options.samplingMode;
  8413. }
  8414. }
  8415. texture.isCube = true;
  8416. texture.references = 1;
  8417. texture.generateMipMaps = generateMipMaps;
  8418. texture.references = 1;
  8419. texture.samplingMode = samplingMode;
  8420. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8421. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8422. for (var face = 0; face < 6; face++) {
  8423. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8424. }
  8425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8429. // Create the depth buffer
  8430. var depthStencilBuffer;
  8431. // Create the depth/stencil buffer
  8432. if (generateStencilBuffer) {
  8433. depthStencilBuffer = gl.createRenderbuffer();
  8434. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8435. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8436. }
  8437. else if (generateDepthBuffer) {
  8438. depthStencilBuffer = gl.createRenderbuffer();
  8439. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8440. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8441. }
  8442. // Create the framebuffer
  8443. var framebuffer = gl.createFramebuffer();
  8444. this.bindUnboundFramebuffer(framebuffer);
  8445. // Manage attachments
  8446. if (generateStencilBuffer) {
  8447. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8448. }
  8449. else if (generateDepthBuffer) {
  8450. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8451. }
  8452. // Mipmaps
  8453. if (texture.generateMipMaps) {
  8454. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8455. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8456. }
  8457. // Unbind
  8458. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8459. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8460. this.bindUnboundFramebuffer(null);
  8461. texture._framebuffer = framebuffer;
  8462. if (generateDepthBuffer) {
  8463. texture._depthBuffer = depthStencilBuffer;
  8464. }
  8465. texture._width = size;
  8466. texture._height = size;
  8467. texture.isReady = true;
  8468. this.resetTextureCache();
  8469. this._loadedTexturesCache.push(texture);
  8470. return texture;
  8471. };
  8472. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8473. var _this = this;
  8474. if (onLoad === void 0) { onLoad = null; }
  8475. if (onError === void 0) { onError = null; }
  8476. var gl = this._gl;
  8477. var texture = gl.createTexture();
  8478. texture.isCube = true;
  8479. texture.url = rootUrl;
  8480. texture.references = 1;
  8481. texture.onLoadedCallbacks = [];
  8482. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8483. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8484. if (isDDS) {
  8485. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8486. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8487. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8488. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8489. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8490. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8491. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8492. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8493. }
  8494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8498. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8499. _this.resetTextureCache();
  8500. texture._width = info.width;
  8501. texture._height = info.height;
  8502. texture.isReady = true;
  8503. }, null, null, true, onError);
  8504. }
  8505. else {
  8506. cascadeLoad(rootUrl, scene, function (imgs) {
  8507. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8508. var height = width;
  8509. _this._prepareWorkingCanvas();
  8510. _this._workingCanvas.width = width;
  8511. _this._workingCanvas.height = height;
  8512. var faces = [
  8513. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8514. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8515. ];
  8516. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8517. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8518. for (var index = 0; index < faces.length; index++) {
  8519. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8520. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8521. }
  8522. if (!noMipmap) {
  8523. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8524. }
  8525. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8529. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8530. _this.resetTextureCache();
  8531. texture._width = width;
  8532. texture._height = height;
  8533. texture.isReady = true;
  8534. texture.onLoadedCallbacks.forEach(function (callback) {
  8535. callback();
  8536. });
  8537. if (onLoad) {
  8538. onLoad();
  8539. }
  8540. }, files, onError);
  8541. }
  8542. this._loadedTexturesCache.push(texture);
  8543. return texture;
  8544. };
  8545. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8546. texture._width = width;
  8547. texture._height = height;
  8548. texture._size = width * height;
  8549. texture._baseWidth = width;
  8550. texture._baseHeight = height;
  8551. };
  8552. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8553. var _this = this;
  8554. var gl = this._gl;
  8555. var texture = gl.createTexture();
  8556. scene._addPendingData(texture);
  8557. texture.isCube = true;
  8558. texture.references = 1;
  8559. texture.url = url;
  8560. var internalFormat = this._getInternalFormat(format);
  8561. var textureType = gl.UNSIGNED_BYTE;
  8562. if (type === Engine.TEXTURETYPE_FLOAT) {
  8563. textureType = gl.FLOAT;
  8564. }
  8565. var width = size;
  8566. var height = width;
  8567. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8568. texture._width = width;
  8569. texture._height = height;
  8570. var onerror = function () {
  8571. scene._removePendingData(texture);
  8572. };
  8573. var internalCallback = function (data) {
  8574. var rgbeDataArrays = callback(data);
  8575. var facesIndex = [
  8576. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8577. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8578. ];
  8579. width = texture._width;
  8580. height = texture._height;
  8581. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8584. if (!noMipmap && isPot) {
  8585. if (mipmmapGenerator) {
  8586. var arrayTemp = [];
  8587. // Data are known to be in +X +Y +Z -X -Y -Z
  8588. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8589. arrayTemp.push(rgbeDataArrays[0]); // +X
  8590. arrayTemp.push(rgbeDataArrays[3]); // -X
  8591. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8592. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8593. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8594. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8595. var mipData = mipmmapGenerator(arrayTemp);
  8596. for (var level = 0; level < mipData.length; level++) {
  8597. var mipSize = width >> level;
  8598. // mipData is order in +X -X +Y -Y +Z -Z
  8599. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8600. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8601. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8602. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8603. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8604. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8605. }
  8606. }
  8607. else {
  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. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8612. }
  8613. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8614. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8615. // By following the webgl standard changes from Revision 7, 2014/11/24
  8616. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8617. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8618. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8619. // Data are known to be in +X +Y +Z -X -Y -Z
  8620. for (var index = 0; index < facesIndex.length; index++) {
  8621. var faceData = rgbeDataArrays[index];
  8622. // Create a new RGBA Face.
  8623. var newFaceData = new Float32Array(width * height * 4);
  8624. for (var x = 0; x < width; x++) {
  8625. for (var y = 0; y < height; y++) {
  8626. var index_1 = (y * width + x) * 3;
  8627. var newIndex = (y * width + x) * 4;
  8628. // Map Old Value to new value.
  8629. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8630. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8631. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8632. // Add fully opaque alpha channel.
  8633. newFaceData[newIndex + 3] = 1;
  8634. }
  8635. }
  8636. // Reupload the face.
  8637. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8638. }
  8639. // Try to generate mipmap again.
  8640. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8641. }
  8642. }
  8643. }
  8644. else {
  8645. noMipmap = true;
  8646. }
  8647. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8648. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8650. }
  8651. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8654. }
  8655. else {
  8656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8658. }
  8659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8661. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8662. texture.isReady = true;
  8663. _this.resetTextureCache();
  8664. scene._removePendingData(texture);
  8665. };
  8666. BABYLON.Tools.LoadFile(url, function (data) {
  8667. internalCallback(data);
  8668. }, onerror, scene.database, true);
  8669. return texture;
  8670. };
  8671. ;
  8672. Engine.prototype._releaseTexture = function (texture) {
  8673. var gl = this._gl;
  8674. if (texture._framebuffer) {
  8675. gl.deleteFramebuffer(texture._framebuffer);
  8676. }
  8677. if (texture._depthBuffer) {
  8678. gl.deleteRenderbuffer(texture._depthBuffer);
  8679. }
  8680. gl.deleteTexture(texture);
  8681. // Unbind channels
  8682. this.unbindAllTextures();
  8683. var index = this._loadedTexturesCache.indexOf(texture);
  8684. if (index !== -1) {
  8685. this._loadedTexturesCache.splice(index, 1);
  8686. }
  8687. };
  8688. Engine.prototype.setProgram = function (program) {
  8689. if (this._currentProgram !== program) {
  8690. this._gl.useProgram(program);
  8691. this._currentProgram = program;
  8692. }
  8693. };
  8694. Engine.prototype.bindSamplers = function (effect) {
  8695. this.setProgram(effect.getProgram());
  8696. var samplers = effect.getSamplers();
  8697. for (var index = 0; index < samplers.length; index++) {
  8698. var uniform = effect.getUniform(samplers[index]);
  8699. this._gl.uniform1i(uniform, index);
  8700. }
  8701. this._currentEffect = null;
  8702. };
  8703. Engine.prototype.activateTexture = function (texture) {
  8704. if (this._activeTexture !== texture) {
  8705. this._gl.activeTexture(texture);
  8706. this._activeTexture = texture;
  8707. }
  8708. };
  8709. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8710. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8711. this._gl.bindTexture(target, texture);
  8712. this._activeTexturesCache[this._activeTexture] = texture;
  8713. }
  8714. };
  8715. Engine.prototype._bindTexture = function (channel, texture) {
  8716. if (channel < 0) {
  8717. return;
  8718. }
  8719. this.activateTexture(this._gl["TEXTURE" + channel]);
  8720. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8721. };
  8722. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8723. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8724. };
  8725. Engine.prototype.unbindAllTextures = function () {
  8726. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8727. this.activateTexture(this._gl["TEXTURE" + channel]);
  8728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8729. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8730. }
  8731. };
  8732. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8733. if (channel < 0) {
  8734. return;
  8735. }
  8736. this._gl.uniform1i(uniform, channel);
  8737. this._setTexture(channel, texture);
  8738. };
  8739. Engine.prototype._setTexture = function (channel, texture) {
  8740. // Not ready?
  8741. if (!texture || !texture.isReady()) {
  8742. if (this._activeTexturesCache[channel] != null) {
  8743. this.activateTexture(this._gl["TEXTURE" + channel]);
  8744. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8745. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8746. }
  8747. return;
  8748. }
  8749. // Video
  8750. var alreadyActivated = false;
  8751. if (texture instanceof BABYLON.VideoTexture) {
  8752. this.activateTexture(this._gl["TEXTURE" + channel]);
  8753. alreadyActivated = true;
  8754. texture.update();
  8755. }
  8756. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8757. texture.delayLoad();
  8758. return;
  8759. }
  8760. var internalTexture = texture.getInternalTexture();
  8761. if (this._activeTexturesCache[channel] === internalTexture) {
  8762. return;
  8763. }
  8764. if (!alreadyActivated) {
  8765. this.activateTexture(this._gl["TEXTURE" + channel]);
  8766. }
  8767. if (internalTexture.isCube) {
  8768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8769. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8770. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8771. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8772. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8773. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8774. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8775. }
  8776. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8777. }
  8778. else {
  8779. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8780. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8781. internalTexture._cachedWrapU = texture.wrapU;
  8782. switch (texture.wrapU) {
  8783. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8784. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8785. break;
  8786. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8787. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8788. break;
  8789. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8791. break;
  8792. }
  8793. }
  8794. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8795. internalTexture._cachedWrapV = texture.wrapV;
  8796. switch (texture.wrapV) {
  8797. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8798. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8799. break;
  8800. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8801. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8802. break;
  8803. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8805. break;
  8806. }
  8807. }
  8808. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8809. }
  8810. };
  8811. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8812. if (channel < 0) {
  8813. return;
  8814. }
  8815. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8816. this._textureUnits = new Int32Array(textures.length);
  8817. }
  8818. for (var i = 0; i < textures.length; i++) {
  8819. this._textureUnits[i] = channel + i;
  8820. }
  8821. this._gl.uniform1iv(uniform, this._textureUnits);
  8822. for (var index = 0; index < textures.length; index++) {
  8823. this._setTexture(channel + index, textures[index]);
  8824. }
  8825. };
  8826. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8827. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8828. var value = texture.anisotropicFilteringLevel;
  8829. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8830. value = 1;
  8831. }
  8832. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8833. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8834. texture._cachedAnisotropicFilteringLevel = value;
  8835. }
  8836. };
  8837. Engine.prototype.readPixels = function (x, y, width, height) {
  8838. var data = new Uint8Array(height * width * 4);
  8839. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8840. return data;
  8841. };
  8842. /**
  8843. * Add an externaly attached data from its key.
  8844. * This method call will fail and return false, if such key already exists.
  8845. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8846. * @param key the unique key that identifies the data
  8847. * @param data the data object to associate to the key for this Engine instance
  8848. * @return true if no such key were already present and the data was added successfully, false otherwise
  8849. */
  8850. Engine.prototype.addExternalData = function (key, data) {
  8851. return this._externalData.add(key, data);
  8852. };
  8853. /**
  8854. * Get an externaly attached data from its key
  8855. * @param key the unique key that identifies the data
  8856. * @return the associated data, if present (can be null), or undefined if not present
  8857. */
  8858. Engine.prototype.getExternalData = function (key) {
  8859. return this._externalData.get(key);
  8860. };
  8861. /**
  8862. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8863. * @param key the unique key that identifies the data
  8864. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8865. * @return the associated data, can be null if the factory returned null.
  8866. */
  8867. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8868. return this._externalData.getOrAddWithFactory(key, factory);
  8869. };
  8870. /**
  8871. * Remove an externaly attached data from the Engine instance
  8872. * @param key the unique key that identifies the data
  8873. * @return true if the data was successfully removed, false if it doesn't exist
  8874. */
  8875. Engine.prototype.removeExternalData = function (key) {
  8876. return this._externalData.remove(key);
  8877. };
  8878. Engine.prototype.releaseInternalTexture = function (texture) {
  8879. if (!texture) {
  8880. return;
  8881. }
  8882. texture.references--;
  8883. // Final reference ?
  8884. if (texture.references === 0) {
  8885. var texturesCache = this.getLoadedTexturesCache();
  8886. var index = texturesCache.indexOf(texture);
  8887. if (index > -1) {
  8888. texturesCache.splice(index, 1);
  8889. }
  8890. this._releaseTexture(texture);
  8891. }
  8892. };
  8893. Engine.prototype.unbindAllAttributes = function () {
  8894. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8895. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8896. continue;
  8897. }
  8898. this._gl.disableVertexAttribArray(i);
  8899. this._vertexAttribArraysEnabled[i] = false;
  8900. }
  8901. };
  8902. // Dispose
  8903. Engine.prototype.dispose = function () {
  8904. this.hideLoadingUI();
  8905. this.stopRenderLoop();
  8906. // Release scenes
  8907. while (this.scenes.length) {
  8908. this.scenes[0].dispose();
  8909. }
  8910. // Release audio engine
  8911. Engine.audioEngine.dispose();
  8912. // Release effects
  8913. for (var name in this._compiledEffects) {
  8914. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8915. }
  8916. // Unbind
  8917. this.unbindAllAttributes();
  8918. this._gl = null;
  8919. //WebVR
  8920. this.disableVR();
  8921. // Events
  8922. window.removeEventListener("blur", this._onBlur);
  8923. window.removeEventListener("focus", this._onFocus);
  8924. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8925. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8926. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8927. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8928. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8929. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8930. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8931. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8932. };
  8933. // Loading screen
  8934. Engine.prototype.displayLoadingUI = function () {
  8935. this._loadingScreen.displayLoadingUI();
  8936. };
  8937. Engine.prototype.hideLoadingUI = function () {
  8938. this._loadingScreen.hideLoadingUI();
  8939. };
  8940. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8941. get: function () {
  8942. return this._loadingScreen;
  8943. },
  8944. set: function (loadingScreen) {
  8945. this._loadingScreen = loadingScreen;
  8946. },
  8947. enumerable: true,
  8948. configurable: true
  8949. });
  8950. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8951. set: function (text) {
  8952. this._loadingScreen.loadingUIText = text;
  8953. },
  8954. enumerable: true,
  8955. configurable: true
  8956. });
  8957. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8958. set: function (color) {
  8959. this._loadingScreen.loadingUIBackgroundColor = color;
  8960. },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Engine.prototype.attachContextLostEvent = function (callback) {
  8965. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8966. };
  8967. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8968. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8969. };
  8970. Engine.prototype.getVertexShaderSource = function (program) {
  8971. var shaders = this._gl.getAttachedShaders(program);
  8972. return this._gl.getShaderSource(shaders[0]);
  8973. };
  8974. Engine.prototype.getFragmentShaderSource = function (program) {
  8975. var shaders = this._gl.getAttachedShaders(program);
  8976. return this._gl.getShaderSource(shaders[1]);
  8977. };
  8978. // FPS
  8979. Engine.prototype.getFps = function () {
  8980. return this.fps;
  8981. };
  8982. Engine.prototype.getDeltaTime = function () {
  8983. return this.deltaTime;
  8984. };
  8985. Engine.prototype._measureFps = function () {
  8986. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8987. var length = this.previousFramesDuration.length;
  8988. if (length >= 2) {
  8989. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8990. }
  8991. if (length >= this.fpsRange) {
  8992. if (length > this.fpsRange) {
  8993. this.previousFramesDuration.splice(0, 1);
  8994. length = this.previousFramesDuration.length;
  8995. }
  8996. var sum = 0;
  8997. for (var id = 0; id < length - 1; id++) {
  8998. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8999. }
  9000. this.fps = 1000.0 / (sum / (length - 1));
  9001. }
  9002. };
  9003. Engine.prototype._canRenderToFloatTexture = function () {
  9004. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  9005. };
  9006. Engine.prototype._canRenderToHalfFloatTexture = function () {
  9007. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9008. };
  9009. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9010. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9011. var tempcanvas = document.createElement("canvas");
  9012. tempcanvas.height = 16;
  9013. tempcanvas.width = 16;
  9014. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9015. // extension.
  9016. var ext = gl.getExtension(extension);
  9017. if (!ext) {
  9018. return false;
  9019. }
  9020. // setup GLSL program
  9021. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9022. 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 }";
  9023. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9024. gl.useProgram(program);
  9025. // look up where the vertex data needs to go.
  9026. var positionLocation = gl.getAttribLocation(program, "a_position");
  9027. var colorLoc = gl.getUniformLocation(program, "u_color");
  9028. // provide texture coordinates for the rectangle.
  9029. var positionBuffer = gl.createBuffer();
  9030. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9031. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9032. -1.0, -1.0,
  9033. 1.0, -1.0,
  9034. -1.0, 1.0,
  9035. -1.0, 1.0,
  9036. 1.0, -1.0,
  9037. 1.0, 1.0]), gl.STATIC_DRAW);
  9038. gl.enableVertexAttribArray(positionLocation);
  9039. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9040. var whiteTex = gl.createTexture();
  9041. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9042. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9043. var tex = gl.createTexture();
  9044. gl.bindTexture(gl.TEXTURE_2D, tex);
  9045. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9048. var fb = gl.createFramebuffer();
  9049. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9050. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9051. var cleanup = function () {
  9052. gl.deleteProgram(program);
  9053. gl.disableVertexAttribArray(positionLocation);
  9054. gl.deleteBuffer(positionBuffer);
  9055. gl.deleteFramebuffer(fb);
  9056. gl.deleteTexture(whiteTex);
  9057. gl.deleteTexture(tex);
  9058. };
  9059. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9060. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9061. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9062. cleanup();
  9063. return false;
  9064. }
  9065. // Draw the rectangle.
  9066. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9067. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9068. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9069. gl.bindTexture(gl.TEXTURE_2D, tex);
  9070. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9071. gl.clearColor(1, 0, 0, 1);
  9072. gl.clear(gl.COLOR_BUFFER_BIT);
  9073. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9074. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9075. var pixel = new Uint8Array(4);
  9076. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9077. if (pixel[0] !== 0 ||
  9078. pixel[1] < 248 ||
  9079. pixel[2] < 248 ||
  9080. pixel[3] < 254) {
  9081. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9082. cleanup();
  9083. return false;
  9084. }
  9085. // Succesfully rendered to "format" texture.
  9086. cleanup();
  9087. return true;
  9088. };
  9089. // Statics
  9090. Engine.isSupported = function () {
  9091. try {
  9092. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9093. if (navigator.isCocoonJS) {
  9094. return true;
  9095. }
  9096. var tempcanvas = document.createElement("canvas");
  9097. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9098. return gl != null && !!window.WebGLRenderingContext;
  9099. }
  9100. catch (e) {
  9101. return false;
  9102. }
  9103. };
  9104. // Const statics
  9105. Engine._ALPHA_DISABLE = 0;
  9106. Engine._ALPHA_ADD = 1;
  9107. Engine._ALPHA_COMBINE = 2;
  9108. Engine._ALPHA_SUBTRACT = 3;
  9109. Engine._ALPHA_MULTIPLY = 4;
  9110. Engine._ALPHA_MAXIMIZED = 5;
  9111. Engine._ALPHA_ONEONE = 6;
  9112. Engine._DELAYLOADSTATE_NONE = 0;
  9113. Engine._DELAYLOADSTATE_LOADED = 1;
  9114. Engine._DELAYLOADSTATE_LOADING = 2;
  9115. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9116. Engine._TEXTUREFORMAT_ALPHA = 0;
  9117. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9118. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9119. Engine._TEXTUREFORMAT_RGB = 4;
  9120. Engine._TEXTUREFORMAT_RGBA = 5;
  9121. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9122. Engine._TEXTURETYPE_FLOAT = 1;
  9123. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9124. // Depht or Stencil test Constants.
  9125. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9126. 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.
  9127. 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.
  9128. 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.
  9129. 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.
  9130. 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.
  9131. 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.
  9132. 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.
  9133. // Stencil Actions Constants.
  9134. Engine._KEEP = 0x1E00;
  9135. Engine._REPLACE = 0x1E01;
  9136. Engine._INCR = 0x1E02;
  9137. Engine._DECR = 0x1E03;
  9138. Engine._INVERT = 0x150A;
  9139. Engine._INCR_WRAP = 0x8507;
  9140. Engine._DECR_WRAP = 0x8508;
  9141. // Updatable statics so stick with vars here
  9142. Engine.CollisionsEpsilon = 0.001;
  9143. Engine.CodeRepository = "src/";
  9144. Engine.ShadersRepository = "src/Shaders/";
  9145. return Engine;
  9146. }());
  9147. BABYLON.Engine = Engine;
  9148. })(BABYLON || (BABYLON = {}));
  9149. //# sourceMappingURL=babylon.engine.js.map
  9150. var BABYLON;
  9151. (function (BABYLON) {
  9152. /**
  9153. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9154. */
  9155. var Node = (function () {
  9156. /**
  9157. * @constructor
  9158. * @param {string} name - the name and id to be given to this node
  9159. * @param {BABYLON.Scene} the scene this node will be added to
  9160. */
  9161. function Node(name, scene) {
  9162. this.state = "";
  9163. this.metadata = null;
  9164. this.doNotSerialize = false;
  9165. this.animations = new Array();
  9166. this._ranges = {};
  9167. this._childrenFlag = -1;
  9168. this._isEnabled = true;
  9169. this._isReady = true;
  9170. this._currentRenderId = -1;
  9171. this._parentRenderId = -1;
  9172. /**
  9173. * An event triggered when the mesh is disposed.
  9174. * @type {BABYLON.Observable}
  9175. */
  9176. this.onDisposeObservable = new BABYLON.Observable();
  9177. this.name = name;
  9178. this.id = name;
  9179. this._scene = scene;
  9180. this._initCache();
  9181. }
  9182. Object.defineProperty(Node.prototype, "parent", {
  9183. get: function () {
  9184. return this._parentNode;
  9185. },
  9186. set: function (parent) {
  9187. if (this._parentNode === parent) {
  9188. return;
  9189. }
  9190. if (this._parentNode) {
  9191. var index = this._parentNode._children.indexOf(this);
  9192. if (index !== -1) {
  9193. this._parentNode._children.splice(index, 1);
  9194. }
  9195. }
  9196. this._parentNode = parent;
  9197. if (this._parentNode) {
  9198. if (!this._parentNode._children) {
  9199. this._parentNode._children = new Array();
  9200. }
  9201. this._parentNode._children.push(this);
  9202. }
  9203. },
  9204. enumerable: true,
  9205. configurable: true
  9206. });
  9207. Node.prototype.getClassName = function () {
  9208. return "Node";
  9209. };
  9210. Object.defineProperty(Node.prototype, "onDispose", {
  9211. set: function (callback) {
  9212. if (this._onDisposeObserver) {
  9213. this.onDisposeObservable.remove(this._onDisposeObserver);
  9214. }
  9215. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9216. },
  9217. enumerable: true,
  9218. configurable: true
  9219. });
  9220. Node.prototype.getScene = function () {
  9221. return this._scene;
  9222. };
  9223. Node.prototype.getEngine = function () {
  9224. return this._scene.getEngine();
  9225. };
  9226. // override it in derived class
  9227. Node.prototype.getWorldMatrix = function () {
  9228. return BABYLON.Matrix.Identity();
  9229. };
  9230. // override it in derived class if you add new variables to the cache
  9231. // and call the parent class method
  9232. Node.prototype._initCache = function () {
  9233. this._cache = {};
  9234. this._cache.parent = undefined;
  9235. };
  9236. Node.prototype.updateCache = function (force) {
  9237. if (!force && this.isSynchronized())
  9238. return;
  9239. this._cache.parent = this.parent;
  9240. this._updateCache();
  9241. };
  9242. // override it in derived class if you add new variables to the cache
  9243. // and call the parent class method if !ignoreParentClass
  9244. Node.prototype._updateCache = function (ignoreParentClass) {
  9245. };
  9246. // override it in derived class if you add new variables to the cache
  9247. Node.prototype._isSynchronized = function () {
  9248. return true;
  9249. };
  9250. Node.prototype._markSyncedWithParent = function () {
  9251. this._parentRenderId = this.parent._currentRenderId;
  9252. };
  9253. Node.prototype.isSynchronizedWithParent = function () {
  9254. if (!this.parent) {
  9255. return true;
  9256. }
  9257. if (this._parentRenderId !== this.parent._currentRenderId) {
  9258. return false;
  9259. }
  9260. return this.parent.isSynchronized();
  9261. };
  9262. Node.prototype.isSynchronized = function (updateCache) {
  9263. var check = this.hasNewParent();
  9264. check = check || !this.isSynchronizedWithParent();
  9265. check = check || !this._isSynchronized();
  9266. if (updateCache)
  9267. this.updateCache(true);
  9268. return !check;
  9269. };
  9270. Node.prototype.hasNewParent = function (update) {
  9271. if (this._cache.parent === this.parent)
  9272. return false;
  9273. if (update)
  9274. this._cache.parent = this.parent;
  9275. return true;
  9276. };
  9277. /**
  9278. * Is this node ready to be used/rendered
  9279. * @return {boolean} is it ready
  9280. */
  9281. Node.prototype.isReady = function () {
  9282. return this._isReady;
  9283. };
  9284. /**
  9285. * Is this node enabled.
  9286. * If the node has a parent and is enabled, the parent will be inspected as well.
  9287. * @return {boolean} whether this node (and its parent) is enabled.
  9288. * @see setEnabled
  9289. */
  9290. Node.prototype.isEnabled = function () {
  9291. if (!this._isEnabled) {
  9292. return false;
  9293. }
  9294. if (this.parent) {
  9295. return this.parent.isEnabled();
  9296. }
  9297. return true;
  9298. };
  9299. /**
  9300. * Set the enabled state of this node.
  9301. * @param {boolean} value - the new enabled state
  9302. * @see isEnabled
  9303. */
  9304. Node.prototype.setEnabled = function (value) {
  9305. this._isEnabled = value;
  9306. };
  9307. /**
  9308. * Is this node a descendant of the given node.
  9309. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9310. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9311. * @see parent
  9312. */
  9313. Node.prototype.isDescendantOf = function (ancestor) {
  9314. if (this.parent) {
  9315. if (this.parent === ancestor) {
  9316. return true;
  9317. }
  9318. return this.parent.isDescendantOf(ancestor);
  9319. }
  9320. return false;
  9321. };
  9322. /**
  9323. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9324. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9325. * @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.
  9326. * @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.
  9327. */
  9328. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9329. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9330. if (!this._children) {
  9331. return;
  9332. }
  9333. for (var index = 0; index < this._children.length; index++) {
  9334. var item = this._children[index];
  9335. if (!predicate || predicate(item)) {
  9336. results.push(item);
  9337. }
  9338. if (!directDescendantsOnly) {
  9339. item._getDescendants(results, false, predicate);
  9340. }
  9341. }
  9342. };
  9343. /**
  9344. * Will return all nodes that have this node as ascendant.
  9345. * @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.
  9346. * @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.
  9347. * @return {BABYLON.Node[]} all children nodes of all types.
  9348. */
  9349. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9350. var results = [];
  9351. this._getDescendants(results, directDescendantsOnly, predicate);
  9352. return results;
  9353. };
  9354. /**
  9355. * @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.
  9356. * @Deprecated, legacy support.
  9357. * use getDecendants instead.
  9358. */
  9359. Node.prototype.getChildren = function (predicate) {
  9360. return this.getDescendants(true, predicate);
  9361. };
  9362. /**
  9363. * Get all child-meshes of this node.
  9364. */
  9365. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9366. var results = [];
  9367. this._getDescendants(results, directDecendantsOnly, function (node) {
  9368. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9369. });
  9370. return results;
  9371. };
  9372. Node.prototype._setReady = function (state) {
  9373. if (state === this._isReady) {
  9374. return;
  9375. }
  9376. if (!state) {
  9377. this._isReady = false;
  9378. return;
  9379. }
  9380. this._isReady = true;
  9381. if (this.onReady) {
  9382. this.onReady(this);
  9383. }
  9384. };
  9385. Node.prototype.getAnimationByName = function (name) {
  9386. for (var i = 0; i < this.animations.length; i++) {
  9387. var animation = this.animations[i];
  9388. if (animation.name === name) {
  9389. return animation;
  9390. }
  9391. }
  9392. return null;
  9393. };
  9394. Node.prototype.createAnimationRange = function (name, from, to) {
  9395. // check name not already in use
  9396. if (!this._ranges[name]) {
  9397. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9398. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9399. if (this.animations[i]) {
  9400. this.animations[i].createRange(name, from, to);
  9401. }
  9402. }
  9403. }
  9404. };
  9405. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9406. if (deleteFrames === void 0) { deleteFrames = true; }
  9407. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9408. if (this.animations[i]) {
  9409. this.animations[i].deleteRange(name, deleteFrames);
  9410. }
  9411. }
  9412. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9413. };
  9414. Node.prototype.getAnimationRange = function (name) {
  9415. return this._ranges[name];
  9416. };
  9417. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9418. var range = this.getAnimationRange(name);
  9419. if (!range) {
  9420. return null;
  9421. }
  9422. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9423. };
  9424. Node.prototype.serializeAnimationRanges = function () {
  9425. var serializationRanges = [];
  9426. for (var name in this._ranges) {
  9427. var range = {};
  9428. range.name = name;
  9429. range.from = this._ranges[name].from;
  9430. range.to = this._ranges[name].to;
  9431. serializationRanges.push(range);
  9432. }
  9433. return serializationRanges;
  9434. };
  9435. Node.prototype.dispose = function () {
  9436. this.parent = null;
  9437. // Callback
  9438. this.onDisposeObservable.notifyObservers(this);
  9439. this.onDisposeObservable.clear();
  9440. };
  9441. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9442. if (parsedNode.ranges) {
  9443. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9444. var data = parsedNode.ranges[index];
  9445. node.createAnimationRange(data.name, data.from, data.to);
  9446. }
  9447. }
  9448. };
  9449. __decorate([
  9450. BABYLON.serialize()
  9451. ], Node.prototype, "name", void 0);
  9452. __decorate([
  9453. BABYLON.serialize()
  9454. ], Node.prototype, "id", void 0);
  9455. __decorate([
  9456. BABYLON.serialize()
  9457. ], Node.prototype, "uniqueId", void 0);
  9458. __decorate([
  9459. BABYLON.serialize()
  9460. ], Node.prototype, "state", void 0);
  9461. __decorate([
  9462. BABYLON.serialize()
  9463. ], Node.prototype, "metadata", void 0);
  9464. return Node;
  9465. }());
  9466. BABYLON.Node = Node;
  9467. })(BABYLON || (BABYLON = {}));
  9468. //# sourceMappingURL=babylon.node.js.map
  9469. var BABYLON;
  9470. (function (BABYLON) {
  9471. var FilesInput = (function () {
  9472. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9473. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9474. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9475. this._engine = p_engine;
  9476. this._canvas = p_canvas;
  9477. this._currentScene = p_scene;
  9478. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9479. this._progressCallback = p_progressCallback;
  9480. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9481. this._textureLoadingCallback = p_textureLoadingCallback;
  9482. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9483. }
  9484. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9485. var _this = this;
  9486. if (p_elementToMonitor) {
  9487. this._elementToMonitor = p_elementToMonitor;
  9488. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9489. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9490. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9491. }
  9492. };
  9493. FilesInput.prototype.renderFunction = function () {
  9494. if (this._additionnalRenderLoopLogicCallback) {
  9495. this._additionnalRenderLoopLogicCallback();
  9496. }
  9497. if (this._currentScene) {
  9498. if (this._textureLoadingCallback) {
  9499. var remaining = this._currentScene.getWaitingItemsCount();
  9500. if (remaining > 0) {
  9501. this._textureLoadingCallback(remaining);
  9502. }
  9503. }
  9504. this._currentScene.render();
  9505. }
  9506. };
  9507. FilesInput.prototype.drag = function (e) {
  9508. e.stopPropagation();
  9509. e.preventDefault();
  9510. };
  9511. FilesInput.prototype.drop = function (eventDrop) {
  9512. eventDrop.stopPropagation();
  9513. eventDrop.preventDefault();
  9514. this.loadFiles(eventDrop);
  9515. };
  9516. FilesInput.prototype.loadFiles = function (event) {
  9517. if (this._startingProcessingFilesCallback)
  9518. this._startingProcessingFilesCallback();
  9519. // Handling data transfer via drag'n'drop
  9520. if (event && event.dataTransfer && event.dataTransfer.files) {
  9521. this._filesToLoad = event.dataTransfer.files;
  9522. }
  9523. // Handling files from input files
  9524. if (event && event.target && event.target.files) {
  9525. this._filesToLoad = event.target.files;
  9526. }
  9527. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9528. for (var i = 0; i < this._filesToLoad.length; i++) {
  9529. switch (this._filesToLoad[i].type) {
  9530. case "image/jpeg":
  9531. case "image/png":
  9532. case "image/bmp":
  9533. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9534. break;
  9535. case "image/targa":
  9536. case "image/vnd.ms-dds":
  9537. case "audio/wav":
  9538. case "audio/x-wav":
  9539. case "audio/mp3":
  9540. case "audio/mpeg":
  9541. case "audio/mpeg3":
  9542. case "audio/x-mpeg-3":
  9543. case "audio/ogg":
  9544. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9545. break;
  9546. default:
  9547. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9548. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9549. }
  9550. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9551. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9552. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9553. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9554. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9555. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9556. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9557. this._sceneFileToLoad = this._filesToLoad[i];
  9558. }
  9559. break;
  9560. }
  9561. }
  9562. this.reload();
  9563. }
  9564. };
  9565. FilesInput.prototype.reload = function () {
  9566. var _this = this;
  9567. var that = this;
  9568. // If a ".babylon" file has been provided
  9569. if (this._sceneFileToLoad) {
  9570. if (this._currentScene) {
  9571. if (BABYLON.Tools.errorsCount > 0) {
  9572. BABYLON.Tools.ClearLogCache();
  9573. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9574. }
  9575. this._engine.stopRenderLoop();
  9576. this._currentScene.dispose();
  9577. }
  9578. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9579. that._currentScene = newScene;
  9580. // Wait for textures and shaders to be ready
  9581. that._currentScene.executeWhenReady(function () {
  9582. // Attach camera to canvas inputs
  9583. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9584. that._currentScene.createDefaultCameraOrLight();
  9585. }
  9586. that._currentScene.activeCamera.attachControl(that._canvas);
  9587. if (that._sceneLoadedCallback) {
  9588. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9589. }
  9590. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9591. });
  9592. }, function (progress) {
  9593. if (_this._progressCallback) {
  9594. _this._progressCallback(progress);
  9595. }
  9596. });
  9597. }
  9598. else {
  9599. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9600. }
  9601. };
  9602. FilesInput.FilesTextures = new Array();
  9603. FilesInput.FilesToLoad = new Array();
  9604. return FilesInput;
  9605. }());
  9606. BABYLON.FilesInput = FilesInput;
  9607. })(BABYLON || (BABYLON = {}));
  9608. //# sourceMappingURL=babylon.filesInput.js.map
  9609. var BABYLON;
  9610. (function (BABYLON) {
  9611. var IntersectionInfo = (function () {
  9612. function IntersectionInfo(bu, bv, distance) {
  9613. this.bu = bu;
  9614. this.bv = bv;
  9615. this.distance = distance;
  9616. this.faceId = 0;
  9617. this.subMeshId = 0;
  9618. }
  9619. return IntersectionInfo;
  9620. }());
  9621. BABYLON.IntersectionInfo = IntersectionInfo;
  9622. var PickingInfo = (function () {
  9623. function PickingInfo() {
  9624. this.hit = false;
  9625. this.distance = 0;
  9626. this.pickedPoint = null;
  9627. this.pickedMesh = null;
  9628. this.bu = 0;
  9629. this.bv = 0;
  9630. this.faceId = -1;
  9631. this.subMeshId = 0;
  9632. this.pickedSprite = null;
  9633. }
  9634. // Methods
  9635. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9636. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9637. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9638. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9639. return null;
  9640. }
  9641. var indices = this.pickedMesh.getIndices();
  9642. var result;
  9643. if (useVerticesNormals) {
  9644. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9645. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9646. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9647. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9648. normal0 = normal0.scale(this.bu);
  9649. normal1 = normal1.scale(this.bv);
  9650. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9651. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9652. }
  9653. else {
  9654. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9655. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9656. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9657. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9658. var p1p2 = vertex1.subtract(vertex2);
  9659. var p3p2 = vertex3.subtract(vertex2);
  9660. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9661. }
  9662. if (useWorldCoordinates) {
  9663. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9664. }
  9665. return BABYLON.Vector3.Normalize(result);
  9666. };
  9667. PickingInfo.prototype.getTextureCoordinates = function () {
  9668. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9669. return null;
  9670. }
  9671. var indices = this.pickedMesh.getIndices();
  9672. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9673. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9674. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9675. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9676. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9677. uv1 = uv1.scale(this.bu);
  9678. uv2 = uv2.scale(this.bv);
  9679. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9680. };
  9681. return PickingInfo;
  9682. }());
  9683. BABYLON.PickingInfo = PickingInfo;
  9684. })(BABYLON || (BABYLON = {}));
  9685. //# sourceMappingURL=babylon.pickingInfo.js.map
  9686. var BABYLON;
  9687. (function (BABYLON) {
  9688. var BoundingSphere = (function () {
  9689. function BoundingSphere(minimum, maximum) {
  9690. this.minimum = minimum;
  9691. this.maximum = maximum;
  9692. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9693. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9694. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9695. this.radius = distance * 0.5;
  9696. this.centerWorld = BABYLON.Vector3.Zero();
  9697. this._update(BABYLON.Matrix.Identity());
  9698. }
  9699. // Methods
  9700. BoundingSphere.prototype._update = function (world) {
  9701. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9702. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9703. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9704. };
  9705. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9706. for (var i = 0; i < 6; i++) {
  9707. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9708. return false;
  9709. }
  9710. return true;
  9711. };
  9712. BoundingSphere.prototype.intersectsPoint = function (point) {
  9713. var x = this.centerWorld.x - point.x;
  9714. var y = this.centerWorld.y - point.y;
  9715. var z = this.centerWorld.z - point.z;
  9716. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9717. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9718. return false;
  9719. return true;
  9720. };
  9721. // Statics
  9722. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9723. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9724. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9725. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9726. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9727. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9728. return false;
  9729. return true;
  9730. };
  9731. return BoundingSphere;
  9732. }());
  9733. BABYLON.BoundingSphere = BoundingSphere;
  9734. })(BABYLON || (BABYLON = {}));
  9735. //# sourceMappingURL=babylon.boundingSphere.js.map
  9736. var BABYLON;
  9737. (function (BABYLON) {
  9738. var BoundingBox = (function () {
  9739. function BoundingBox(minimum, maximum) {
  9740. this.minimum = minimum;
  9741. this.maximum = maximum;
  9742. this.vectors = new Array();
  9743. this.vectorsWorld = new Array();
  9744. // Bounding vectors
  9745. this.vectors.push(this.minimum.clone());
  9746. this.vectors.push(this.maximum.clone());
  9747. this.vectors.push(this.minimum.clone());
  9748. this.vectors[2].x = this.maximum.x;
  9749. this.vectors.push(this.minimum.clone());
  9750. this.vectors[3].y = this.maximum.y;
  9751. this.vectors.push(this.minimum.clone());
  9752. this.vectors[4].z = this.maximum.z;
  9753. this.vectors.push(this.maximum.clone());
  9754. this.vectors[5].z = this.minimum.z;
  9755. this.vectors.push(this.maximum.clone());
  9756. this.vectors[6].x = this.minimum.x;
  9757. this.vectors.push(this.maximum.clone());
  9758. this.vectors[7].y = this.minimum.y;
  9759. // OBB
  9760. this.center = this.maximum.add(this.minimum).scale(0.5);
  9761. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9762. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9763. // World
  9764. for (var index = 0; index < this.vectors.length; index++) {
  9765. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9766. }
  9767. this.minimumWorld = BABYLON.Vector3.Zero();
  9768. this.maximumWorld = BABYLON.Vector3.Zero();
  9769. this._update(BABYLON.Matrix.Identity());
  9770. }
  9771. // Methods
  9772. BoundingBox.prototype.getWorldMatrix = function () {
  9773. return this._worldMatrix;
  9774. };
  9775. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9776. this._worldMatrix.copyFrom(matrix);
  9777. return this;
  9778. };
  9779. BoundingBox.prototype._update = function (world) {
  9780. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9781. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9782. for (var index = 0; index < this.vectors.length; index++) {
  9783. var v = this.vectorsWorld[index];
  9784. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9785. if (v.x < this.minimumWorld.x)
  9786. this.minimumWorld.x = v.x;
  9787. if (v.y < this.minimumWorld.y)
  9788. this.minimumWorld.y = v.y;
  9789. if (v.z < this.minimumWorld.z)
  9790. this.minimumWorld.z = v.z;
  9791. if (v.x > this.maximumWorld.x)
  9792. this.maximumWorld.x = v.x;
  9793. if (v.y > this.maximumWorld.y)
  9794. this.maximumWorld.y = v.y;
  9795. if (v.z > this.maximumWorld.z)
  9796. this.maximumWorld.z = v.z;
  9797. }
  9798. // OBB
  9799. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9800. this.center.scaleInPlace(0.5);
  9801. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9802. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9804. this._worldMatrix = world;
  9805. };
  9806. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9807. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9808. };
  9809. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9810. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9811. };
  9812. BoundingBox.prototype.intersectsPoint = function (point) {
  9813. var delta = -BABYLON.Epsilon;
  9814. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9815. return false;
  9816. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9817. return false;
  9818. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9819. return false;
  9820. return true;
  9821. };
  9822. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9823. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9824. };
  9825. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9826. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9827. return false;
  9828. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9829. return false;
  9830. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9831. return false;
  9832. return true;
  9833. };
  9834. // Statics
  9835. BoundingBox.Intersects = function (box0, box1) {
  9836. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9837. return false;
  9838. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9839. return false;
  9840. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9841. return false;
  9842. return true;
  9843. };
  9844. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9845. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9846. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9847. return (num <= (sphereRadius * sphereRadius));
  9848. };
  9849. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9850. for (var p = 0; p < 6; p++) {
  9851. for (var i = 0; i < 8; i++) {
  9852. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9853. return false;
  9854. }
  9855. }
  9856. }
  9857. return true;
  9858. };
  9859. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9860. for (var p = 0; p < 6; p++) {
  9861. var inCount = 8;
  9862. for (var i = 0; i < 8; i++) {
  9863. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9864. --inCount;
  9865. }
  9866. else {
  9867. break;
  9868. }
  9869. }
  9870. if (inCount === 0)
  9871. return false;
  9872. }
  9873. return true;
  9874. };
  9875. return BoundingBox;
  9876. }());
  9877. BABYLON.BoundingBox = BoundingBox;
  9878. })(BABYLON || (BABYLON = {}));
  9879. //# sourceMappingURL=babylon.boundingBox.js.map
  9880. var BABYLON;
  9881. (function (BABYLON) {
  9882. var computeBoxExtents = function (axis, box) {
  9883. var p = BABYLON.Vector3.Dot(box.center, axis);
  9884. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9885. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9886. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9887. var r = r0 + r1 + r2;
  9888. return {
  9889. min: p - r,
  9890. max: p + r
  9891. };
  9892. };
  9893. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9894. var axisOverlap = function (axis, box0, box1) {
  9895. var result0 = computeBoxExtents(axis, box0);
  9896. var result1 = computeBoxExtents(axis, box1);
  9897. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9898. };
  9899. var BoundingInfo = (function () {
  9900. function BoundingInfo(minimum, maximum) {
  9901. this.minimum = minimum;
  9902. this.maximum = maximum;
  9903. this._isLocked = false;
  9904. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9905. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9906. }
  9907. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9908. get: function () {
  9909. return this._isLocked;
  9910. },
  9911. set: function (value) {
  9912. this._isLocked = value;
  9913. },
  9914. enumerable: true,
  9915. configurable: true
  9916. });
  9917. // Methods
  9918. BoundingInfo.prototype.update = function (world) {
  9919. if (this._isLocked) {
  9920. return;
  9921. }
  9922. this.boundingBox._update(world);
  9923. this.boundingSphere._update(world);
  9924. };
  9925. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9926. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9927. return false;
  9928. return this.boundingBox.isInFrustum(frustumPlanes);
  9929. };
  9930. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9931. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9932. };
  9933. BoundingInfo.prototype._checkCollision = function (collider) {
  9934. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9935. };
  9936. BoundingInfo.prototype.intersectsPoint = function (point) {
  9937. if (!this.boundingSphere.centerWorld) {
  9938. return false;
  9939. }
  9940. if (!this.boundingSphere.intersectsPoint(point)) {
  9941. return false;
  9942. }
  9943. if (!this.boundingBox.intersectsPoint(point)) {
  9944. return false;
  9945. }
  9946. return true;
  9947. };
  9948. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9949. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9950. return false;
  9951. }
  9952. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9953. return false;
  9954. }
  9955. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9956. return false;
  9957. }
  9958. if (!precise) {
  9959. return true;
  9960. }
  9961. var box0 = this.boundingBox;
  9962. var box1 = boundingInfo.boundingBox;
  9963. if (!axisOverlap(box0.directions[0], box0, box1))
  9964. return false;
  9965. if (!axisOverlap(box0.directions[1], box0, box1))
  9966. return false;
  9967. if (!axisOverlap(box0.directions[2], box0, box1))
  9968. return false;
  9969. if (!axisOverlap(box1.directions[0], box0, box1))
  9970. return false;
  9971. if (!axisOverlap(box1.directions[1], box0, box1))
  9972. return false;
  9973. if (!axisOverlap(box1.directions[2], box0, box1))
  9974. return false;
  9975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9976. return false;
  9977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9978. return false;
  9979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9980. return false;
  9981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9982. return false;
  9983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9984. return false;
  9985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9986. return false;
  9987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9988. return false;
  9989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9990. return false;
  9991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9992. return false;
  9993. return true;
  9994. };
  9995. return BoundingInfo;
  9996. }());
  9997. BABYLON.BoundingInfo = BoundingInfo;
  9998. })(BABYLON || (BABYLON = {}));
  9999. //# sourceMappingURL=babylon.boundingInfo.js.map
  10000. var BABYLON;
  10001. (function (BABYLON) {
  10002. var Ray = (function () {
  10003. function Ray(origin, direction, length) {
  10004. if (length === void 0) { length = Number.MAX_VALUE; }
  10005. this.origin = origin;
  10006. this.direction = direction;
  10007. this.length = length;
  10008. this._show = false;
  10009. }
  10010. // Methods
  10011. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10012. var d = 0.0;
  10013. var maxValue = Number.MAX_VALUE;
  10014. var inv;
  10015. var min;
  10016. var max;
  10017. var temp;
  10018. if (Math.abs(this.direction.x) < 0.0000001) {
  10019. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10020. return false;
  10021. }
  10022. }
  10023. else {
  10024. inv = 1.0 / this.direction.x;
  10025. min = (minimum.x - this.origin.x) * inv;
  10026. max = (maximum.x - this.origin.x) * inv;
  10027. if (max === -Infinity) {
  10028. max = Infinity;
  10029. }
  10030. if (min > max) {
  10031. temp = min;
  10032. min = max;
  10033. max = temp;
  10034. }
  10035. d = Math.max(min, d);
  10036. maxValue = Math.min(max, maxValue);
  10037. if (d > maxValue) {
  10038. return false;
  10039. }
  10040. }
  10041. if (Math.abs(this.direction.y) < 0.0000001) {
  10042. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10043. return false;
  10044. }
  10045. }
  10046. else {
  10047. inv = 1.0 / this.direction.y;
  10048. min = (minimum.y - this.origin.y) * inv;
  10049. max = (maximum.y - this.origin.y) * inv;
  10050. if (max === -Infinity) {
  10051. max = Infinity;
  10052. }
  10053. if (min > max) {
  10054. temp = min;
  10055. min = max;
  10056. max = temp;
  10057. }
  10058. d = Math.max(min, d);
  10059. maxValue = Math.min(max, maxValue);
  10060. if (d > maxValue) {
  10061. return false;
  10062. }
  10063. }
  10064. if (Math.abs(this.direction.z) < 0.0000001) {
  10065. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10066. return false;
  10067. }
  10068. }
  10069. else {
  10070. inv = 1.0 / this.direction.z;
  10071. min = (minimum.z - this.origin.z) * inv;
  10072. max = (maximum.z - this.origin.z) * inv;
  10073. if (max === -Infinity) {
  10074. max = Infinity;
  10075. }
  10076. if (min > max) {
  10077. temp = min;
  10078. min = max;
  10079. max = temp;
  10080. }
  10081. d = Math.max(min, d);
  10082. maxValue = Math.min(max, maxValue);
  10083. if (d > maxValue) {
  10084. return false;
  10085. }
  10086. }
  10087. return true;
  10088. };
  10089. Ray.prototype.intersectsBox = function (box) {
  10090. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10091. };
  10092. Ray.prototype.intersectsSphere = function (sphere) {
  10093. var x = sphere.center.x - this.origin.x;
  10094. var y = sphere.center.y - this.origin.y;
  10095. var z = sphere.center.z - this.origin.z;
  10096. var pyth = (x * x) + (y * y) + (z * z);
  10097. var rr = sphere.radius * sphere.radius;
  10098. if (pyth <= rr) {
  10099. return true;
  10100. }
  10101. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10102. if (dot < 0.0) {
  10103. return false;
  10104. }
  10105. var temp = pyth - (dot * dot);
  10106. return temp <= rr;
  10107. };
  10108. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10109. if (!this._edge1) {
  10110. this._edge1 = BABYLON.Vector3.Zero();
  10111. this._edge2 = BABYLON.Vector3.Zero();
  10112. this._pvec = BABYLON.Vector3.Zero();
  10113. this._tvec = BABYLON.Vector3.Zero();
  10114. this._qvec = BABYLON.Vector3.Zero();
  10115. }
  10116. vertex1.subtractToRef(vertex0, this._edge1);
  10117. vertex2.subtractToRef(vertex0, this._edge2);
  10118. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10119. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10120. if (det === 0) {
  10121. return null;
  10122. }
  10123. var invdet = 1 / det;
  10124. this.origin.subtractToRef(vertex0, this._tvec);
  10125. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10126. if (bu < 0 || bu > 1.0) {
  10127. return null;
  10128. }
  10129. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10130. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10131. if (bv < 0 || bu + bv > 1.0) {
  10132. return null;
  10133. }
  10134. //check if the distance is longer than the predefined length.
  10135. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10136. if (distance > this.length) {
  10137. return null;
  10138. }
  10139. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10140. };
  10141. Ray.prototype.intersectsPlane = function (plane) {
  10142. var distance;
  10143. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10144. if (Math.abs(result1) < 9.99999997475243E-07) {
  10145. return null;
  10146. }
  10147. else {
  10148. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10149. distance = (-plane.d - result2) / result1;
  10150. if (distance < 0.0) {
  10151. if (distance < -9.99999997475243E-07) {
  10152. return null;
  10153. }
  10154. else {
  10155. return 0;
  10156. }
  10157. }
  10158. return distance;
  10159. }
  10160. };
  10161. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10162. var tm = BABYLON.Tmp.Matrix[0];
  10163. mesh.getWorldMatrix().invertToRef(tm);
  10164. if (this._tmpRay) {
  10165. Ray.TransformToRef(this, tm, this._tmpRay);
  10166. }
  10167. else {
  10168. this._tmpRay = Ray.Transform(this, tm);
  10169. }
  10170. return mesh.intersects(this._tmpRay, fastCheck);
  10171. };
  10172. Ray.prototype.show = function (scene, color) {
  10173. if (!this._show) {
  10174. this._renderFunction = this._render.bind(this);
  10175. this._show = true;
  10176. this._scene = scene;
  10177. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10178. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10179. this._scene.registerBeforeRender(this._renderFunction);
  10180. }
  10181. if (color) {
  10182. this._renderLine.color.copyFrom(color);
  10183. }
  10184. };
  10185. Ray.prototype.hide = function () {
  10186. if (this._show) {
  10187. this._show = false;
  10188. this._scene.unregisterBeforeRender(this._renderFunction);
  10189. }
  10190. if (this._renderLine) {
  10191. this._renderLine.dispose();
  10192. this._renderLine = null;
  10193. this._renderPoints = null;
  10194. }
  10195. };
  10196. Ray.prototype._render = function () {
  10197. var point = this._renderPoints[1];
  10198. point.copyFrom(this.direction);
  10199. point.scaleInPlace(this.length);
  10200. point.addInPlace(this.origin);
  10201. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10202. };
  10203. /**
  10204. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10205. * @param sega the first point of the segment to test the intersection against
  10206. * @param segb the second point of the segment to test the intersection against
  10207. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10208. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10209. */
  10210. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10211. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10212. var u = segb.subtract(sega);
  10213. var v = rsegb.subtract(this.origin);
  10214. var w = sega.subtract(this.origin);
  10215. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10216. var b = BABYLON.Vector3.Dot(u, v);
  10217. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10218. var d = BABYLON.Vector3.Dot(u, w);
  10219. var e = BABYLON.Vector3.Dot(v, w);
  10220. var D = a * c - b * b; // always >= 0
  10221. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10222. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10223. // compute the line parameters of the two closest points
  10224. if (D < Ray.smallnum) {
  10225. sN = 0.0; // force using point P0 on segment S1
  10226. sD = 1.0; // to prevent possible division by 0.0 later
  10227. tN = e;
  10228. tD = c;
  10229. }
  10230. else {
  10231. sN = (b * e - c * d);
  10232. tN = (a * e - b * d);
  10233. if (sN < 0.0) {
  10234. sN = 0.0;
  10235. tN = e;
  10236. tD = c;
  10237. }
  10238. else if (sN > sD) {
  10239. sN = sD;
  10240. tN = e + b;
  10241. tD = c;
  10242. }
  10243. }
  10244. if (tN < 0.0) {
  10245. tN = 0.0;
  10246. // recompute sc for this edge
  10247. if (-d < 0.0) {
  10248. sN = 0.0;
  10249. }
  10250. else if (-d > a)
  10251. sN = sD;
  10252. else {
  10253. sN = -d;
  10254. sD = a;
  10255. }
  10256. }
  10257. else if (tN > tD) {
  10258. tN = tD;
  10259. // recompute sc for this edge
  10260. if ((-d + b) < 0.0) {
  10261. sN = 0;
  10262. }
  10263. else if ((-d + b) > a) {
  10264. sN = sD;
  10265. }
  10266. else {
  10267. sN = (-d + b);
  10268. sD = a;
  10269. }
  10270. }
  10271. // finally do the division to get sc and tc
  10272. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10273. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10274. // get the difference of the two closest points
  10275. var qtc = v.multiplyByFloats(tc, tc, tc);
  10276. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10277. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10278. if (isIntersected) {
  10279. return qtc.length();
  10280. }
  10281. return -1;
  10282. };
  10283. // Statics
  10284. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10285. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10286. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10287. var direction = end.subtract(start);
  10288. direction.normalize();
  10289. return new Ray(start, direction);
  10290. };
  10291. /**
  10292. * 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
  10293. * transformed to the given world matrix.
  10294. * @param origin The origin point
  10295. * @param end The end point
  10296. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10297. */
  10298. Ray.CreateNewFromTo = function (origin, end, world) {
  10299. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10300. var direction = end.subtract(origin);
  10301. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10302. direction.normalize();
  10303. return Ray.Transform(new Ray(origin, direction, length), world);
  10304. };
  10305. Ray.Transform = function (ray, matrix) {
  10306. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10307. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10308. newDirection.normalize();
  10309. return new Ray(newOrigin, newDirection, ray.length);
  10310. };
  10311. Ray.TransformToRef = function (ray, matrix, result) {
  10312. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10313. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10314. ray.direction.normalize();
  10315. };
  10316. Ray.smallnum = 0.00000001;
  10317. Ray.rayl = 10e8;
  10318. return Ray;
  10319. }());
  10320. BABYLON.Ray = Ray;
  10321. })(BABYLON || (BABYLON = {}));
  10322. //# sourceMappingURL=babylon.ray.js.map
  10323. var BABYLON;
  10324. (function (BABYLON) {
  10325. var AbstractMesh = (function (_super) {
  10326. __extends(AbstractMesh, _super);
  10327. // Constructor
  10328. function AbstractMesh(name, scene) {
  10329. var _this = this;
  10330. _super.call(this, name, scene);
  10331. // Events
  10332. /**
  10333. * An event triggered when this mesh collides with another one
  10334. * @type {BABYLON.Observable}
  10335. */
  10336. this.onCollideObservable = new BABYLON.Observable();
  10337. /**
  10338. * An event triggered when the collision's position changes
  10339. * @type {BABYLON.Observable}
  10340. */
  10341. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10342. /**
  10343. * An event triggered after the world matrix is updated
  10344. * @type {BABYLON.Observable}
  10345. */
  10346. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10347. // Properties
  10348. this.definedFacingForward = true; // orientation for POV movement & rotation
  10349. this.position = new BABYLON.Vector3(0, 0, 0);
  10350. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10351. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10352. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10353. this.visibility = 1.0;
  10354. this.alphaIndex = Number.MAX_VALUE;
  10355. this.infiniteDistance = false;
  10356. this.isVisible = true;
  10357. this.isPickable = true;
  10358. this.showBoundingBox = false;
  10359. this.showSubMeshesBoundingBox = false;
  10360. this.isBlocker = false;
  10361. this.renderingGroupId = 0;
  10362. this.receiveShadows = false;
  10363. this.renderOutline = false;
  10364. this.outlineColor = BABYLON.Color3.Red();
  10365. this.outlineWidth = 0.02;
  10366. this.renderOverlay = false;
  10367. this.overlayColor = BABYLON.Color3.Red();
  10368. this.overlayAlpha = 0.5;
  10369. this.hasVertexAlpha = false;
  10370. this.useVertexColors = true;
  10371. this.applyFog = true;
  10372. this.computeBonesUsingShaders = true;
  10373. this.scalingDeterminant = 1;
  10374. this.numBoneInfluencers = 4;
  10375. this.useOctreeForRenderingSelection = true;
  10376. this.useOctreeForPicking = true;
  10377. this.useOctreeForCollisions = true;
  10378. this.layerMask = 0x0FFFFFFF;
  10379. this.alwaysSelectAsActiveMesh = false;
  10380. // Collisions
  10381. this._checkCollisions = false;
  10382. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10383. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10384. this._collider = new BABYLON.Collider();
  10385. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10386. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10387. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10388. // Edges
  10389. this.edgesWidth = 1;
  10390. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10391. // Cache
  10392. this._localWorld = BABYLON.Matrix.Zero();
  10393. this._worldMatrix = BABYLON.Matrix.Zero();
  10394. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10395. this._absolutePosition = BABYLON.Vector3.Zero();
  10396. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10397. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10398. this._isDirty = false;
  10399. this._pivotMatrix = BABYLON.Matrix.Identity();
  10400. this._isDisposed = false;
  10401. this._renderId = 0;
  10402. this._intersectionsInProgress = new Array();
  10403. this._isWorldMatrixFrozen = false;
  10404. this._unIndexed = false;
  10405. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10406. if (collidedMesh === void 0) { collidedMesh = null; }
  10407. //TODO move this to the collision coordinator!
  10408. if (_this.getScene().workerCollisions)
  10409. newPosition.multiplyInPlace(_this._collider.radius);
  10410. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10411. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10412. _this.position.addInPlace(_this._diffPositionForCollisions);
  10413. }
  10414. if (collidedMesh) {
  10415. _this.onCollideObservable.notifyObservers(collidedMesh);
  10416. }
  10417. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10418. };
  10419. scene.addMesh(this);
  10420. }
  10421. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10422. get: function () {
  10423. return AbstractMesh._BILLBOARDMODE_NONE;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10429. get: function () {
  10430. return AbstractMesh._BILLBOARDMODE_X;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10436. get: function () {
  10437. return AbstractMesh._BILLBOARDMODE_Y;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10443. get: function () {
  10444. return AbstractMesh._BILLBOARDMODE_Z;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10450. get: function () {
  10451. return AbstractMesh._BILLBOARDMODE_ALL;
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10457. set: function (callback) {
  10458. if (this._onCollideObserver) {
  10459. this.onCollideObservable.remove(this._onCollideObserver);
  10460. }
  10461. this._onCollideObserver = this.onCollideObservable.add(callback);
  10462. },
  10463. enumerable: true,
  10464. configurable: true
  10465. });
  10466. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10467. set: function (callback) {
  10468. if (this._onCollisionPositionChangeObserver) {
  10469. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10470. }
  10471. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10477. get: function () {
  10478. return this._skeleton;
  10479. },
  10480. set: function (value) {
  10481. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10482. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10483. }
  10484. if (value && value.needInitialSkinMatrix) {
  10485. value._registerMeshWithPoseMatrix(this);
  10486. }
  10487. this._skeleton = value;
  10488. if (!this._skeleton) {
  10489. this._bonesTransformMatrices = null;
  10490. }
  10491. },
  10492. enumerable: true,
  10493. configurable: true
  10494. });
  10495. AbstractMesh.prototype.getClassName = function () {
  10496. return "AbstractMesh";
  10497. };
  10498. /**
  10499. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10500. */
  10501. AbstractMesh.prototype.toString = function (fullDetails) {
  10502. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10503. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10504. if (this._skeleton) {
  10505. ret += ", skeleton: " + this._skeleton.name;
  10506. }
  10507. if (fullDetails) {
  10508. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10509. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10510. }
  10511. return ret;
  10512. };
  10513. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10514. /**
  10515. * Getting the rotation object.
  10516. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10517. */
  10518. get: function () {
  10519. return this._rotation;
  10520. },
  10521. set: function (newRotation) {
  10522. this._rotation = newRotation;
  10523. },
  10524. enumerable: true,
  10525. configurable: true
  10526. });
  10527. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10528. get: function () {
  10529. return this._scaling;
  10530. },
  10531. set: function (newScaling) {
  10532. this._scaling = newScaling;
  10533. if (this.physicsImpostor) {
  10534. this.physicsImpostor.forceUpdate();
  10535. }
  10536. },
  10537. enumerable: true,
  10538. configurable: true
  10539. });
  10540. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10541. get: function () {
  10542. return this._rotationQuaternion;
  10543. },
  10544. set: function (quaternion) {
  10545. this._rotationQuaternion = quaternion;
  10546. //reset the rotation vector.
  10547. if (quaternion && this.rotation.length()) {
  10548. this.rotation.copyFromFloats(0, 0, 0);
  10549. }
  10550. },
  10551. enumerable: true,
  10552. configurable: true
  10553. });
  10554. // Methods
  10555. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10556. this._poseMatrix.copyFrom(matrix);
  10557. };
  10558. AbstractMesh.prototype.getPoseMatrix = function () {
  10559. return this._poseMatrix;
  10560. };
  10561. AbstractMesh.prototype.disableEdgesRendering = function () {
  10562. if (this._edgesRenderer !== undefined) {
  10563. this._edgesRenderer.dispose();
  10564. this._edgesRenderer = undefined;
  10565. }
  10566. };
  10567. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10568. if (epsilon === void 0) { epsilon = 0.95; }
  10569. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10570. this.disableEdgesRendering();
  10571. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10572. };
  10573. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10574. get: function () {
  10575. return false;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. AbstractMesh.prototype.getLOD = function (camera) {
  10581. return this;
  10582. };
  10583. AbstractMesh.prototype.getTotalVertices = function () {
  10584. return 0;
  10585. };
  10586. AbstractMesh.prototype.getIndices = function () {
  10587. return null;
  10588. };
  10589. AbstractMesh.prototype.getVerticesData = function (kind) {
  10590. return null;
  10591. };
  10592. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10593. return false;
  10594. };
  10595. AbstractMesh.prototype.getBoundingInfo = function () {
  10596. if (this._masterMesh) {
  10597. return this._masterMesh.getBoundingInfo();
  10598. }
  10599. if (!this._boundingInfo) {
  10600. this._updateBoundingInfo();
  10601. }
  10602. return this._boundingInfo;
  10603. };
  10604. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10605. this._boundingInfo = boundingInfo;
  10606. };
  10607. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10608. get: function () {
  10609. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. AbstractMesh.prototype._preActivate = function () {
  10615. };
  10616. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10617. };
  10618. AbstractMesh.prototype._activate = function (renderId) {
  10619. this._renderId = renderId;
  10620. };
  10621. AbstractMesh.prototype.getWorldMatrix = function () {
  10622. if (this._masterMesh) {
  10623. return this._masterMesh.getWorldMatrix();
  10624. }
  10625. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10626. this.computeWorldMatrix();
  10627. }
  10628. return this._worldMatrix;
  10629. };
  10630. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10631. get: function () {
  10632. return this._worldMatrix;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10638. get: function () {
  10639. return this._absolutePosition;
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10645. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10646. this.computeWorldMatrix(true);
  10647. this._isWorldMatrixFrozen = true;
  10648. };
  10649. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10650. this._isWorldMatrixFrozen = false;
  10651. this.computeWorldMatrix(true);
  10652. };
  10653. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10654. get: function () {
  10655. return this._isWorldMatrixFrozen;
  10656. },
  10657. enumerable: true,
  10658. configurable: true
  10659. });
  10660. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10661. axis.normalize();
  10662. if (!this.rotationQuaternion) {
  10663. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10664. this.rotation = BABYLON.Vector3.Zero();
  10665. }
  10666. var rotationQuaternion;
  10667. if (!space || space === BABYLON.Space.LOCAL) {
  10668. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10669. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10670. }
  10671. else {
  10672. if (this.parent) {
  10673. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10674. invertParentWorldMatrix.invert();
  10675. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10676. }
  10677. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10678. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10679. }
  10680. };
  10681. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10682. var displacementVector = axis.scale(distance);
  10683. if (!space || space === BABYLON.Space.LOCAL) {
  10684. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10685. this.setPositionWithLocalVector(tempV3);
  10686. }
  10687. else {
  10688. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10689. }
  10690. };
  10691. AbstractMesh.prototype.getAbsolutePosition = function () {
  10692. this.computeWorldMatrix();
  10693. return this._absolutePosition;
  10694. };
  10695. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10696. if (!absolutePosition) {
  10697. return;
  10698. }
  10699. var absolutePositionX;
  10700. var absolutePositionY;
  10701. var absolutePositionZ;
  10702. if (absolutePosition.x === undefined) {
  10703. if (arguments.length < 3) {
  10704. return;
  10705. }
  10706. absolutePositionX = arguments[0];
  10707. absolutePositionY = arguments[1];
  10708. absolutePositionZ = arguments[2];
  10709. }
  10710. else {
  10711. absolutePositionX = absolutePosition.x;
  10712. absolutePositionY = absolutePosition.y;
  10713. absolutePositionZ = absolutePosition.z;
  10714. }
  10715. if (this.parent) {
  10716. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10717. invertParentWorldMatrix.invert();
  10718. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10719. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10720. }
  10721. else {
  10722. this.position.x = absolutePositionX;
  10723. this.position.y = absolutePositionY;
  10724. this.position.z = absolutePositionZ;
  10725. }
  10726. };
  10727. // ================================== Point of View Movement =================================
  10728. /**
  10729. * Perform relative position change from the point of view of behind the front of the mesh.
  10730. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10731. * Supports definition of mesh facing forward or backward.
  10732. * @param {number} amountRight
  10733. * @param {number} amountUp
  10734. * @param {number} amountForward
  10735. */
  10736. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10737. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10738. };
  10739. /**
  10740. * Calculate relative position change from the point of view of behind the front of the mesh.
  10741. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10742. * Supports definition of mesh facing forward or backward.
  10743. * @param {number} amountRight
  10744. * @param {number} amountUp
  10745. * @param {number} amountForward
  10746. */
  10747. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10748. var rotMatrix = new BABYLON.Matrix();
  10749. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10750. rotQuaternion.toRotationMatrix(rotMatrix);
  10751. var translationDelta = BABYLON.Vector3.Zero();
  10752. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10754. return translationDelta;
  10755. };
  10756. // ================================== Point of View Rotation =================================
  10757. /**
  10758. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10759. * Supports definition of mesh facing forward or backward.
  10760. * @param {number} flipBack
  10761. * @param {number} twirlClockwise
  10762. * @param {number} tiltRight
  10763. */
  10764. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10765. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10766. };
  10767. /**
  10768. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10769. * Supports definition of mesh facing forward or backward.
  10770. * @param {number} flipBack
  10771. * @param {number} twirlClockwise
  10772. * @param {number} tiltRight
  10773. */
  10774. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10775. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10776. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10777. };
  10778. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10779. this._pivotMatrix = matrix;
  10780. this._cache.pivotMatrixUpdated = true;
  10781. };
  10782. AbstractMesh.prototype.getPivotMatrix = function () {
  10783. return this._pivotMatrix;
  10784. };
  10785. AbstractMesh.prototype._isSynchronized = function () {
  10786. if (this._isDirty) {
  10787. return false;
  10788. }
  10789. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10790. return false;
  10791. if (this._cache.pivotMatrixUpdated) {
  10792. return false;
  10793. }
  10794. if (this.infiniteDistance) {
  10795. return false;
  10796. }
  10797. if (!this._cache.position.equals(this.position))
  10798. return false;
  10799. if (this.rotationQuaternion) {
  10800. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10801. return false;
  10802. }
  10803. if (!this._cache.rotation.equals(this.rotation))
  10804. return false;
  10805. if (!this._cache.scaling.equals(this.scaling))
  10806. return false;
  10807. return true;
  10808. };
  10809. AbstractMesh.prototype._initCache = function () {
  10810. _super.prototype._initCache.call(this);
  10811. this._cache.localMatrixUpdated = false;
  10812. this._cache.position = BABYLON.Vector3.Zero();
  10813. this._cache.scaling = BABYLON.Vector3.Zero();
  10814. this._cache.rotation = BABYLON.Vector3.Zero();
  10815. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10816. this._cache.billboardMode = -1;
  10817. };
  10818. AbstractMesh.prototype.markAsDirty = function (property) {
  10819. if (property === "rotation") {
  10820. this.rotationQuaternion = null;
  10821. }
  10822. this._currentRenderId = Number.MAX_VALUE;
  10823. this._isDirty = true;
  10824. };
  10825. AbstractMesh.prototype._updateBoundingInfo = function () {
  10826. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10827. this._boundingInfo.update(this.worldMatrixFromCache);
  10828. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10829. };
  10830. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10831. if (!this.subMeshes) {
  10832. return;
  10833. }
  10834. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10835. var subMesh = this.subMeshes[subIndex];
  10836. if (!subMesh.IsGlobal) {
  10837. subMesh.updateBoundingInfo(matrix);
  10838. }
  10839. }
  10840. };
  10841. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10842. if (this._isWorldMatrixFrozen) {
  10843. return this._worldMatrix;
  10844. }
  10845. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10846. this._currentRenderId = this.getScene().getRenderId();
  10847. return this._worldMatrix;
  10848. }
  10849. this._cache.position.copyFrom(this.position);
  10850. this._cache.scaling.copyFrom(this.scaling);
  10851. this._cache.pivotMatrixUpdated = false;
  10852. this._cache.billboardMode = this.billboardMode;
  10853. this._currentRenderId = this.getScene().getRenderId();
  10854. this._isDirty = false;
  10855. // Scaling
  10856. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10857. // Rotation
  10858. //rotate, if quaternion is set and rotation was used
  10859. if (this.rotationQuaternion) {
  10860. var len = this.rotation.length();
  10861. if (len) {
  10862. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10863. this.rotation.copyFromFloats(0, 0, 0);
  10864. }
  10865. }
  10866. if (this.rotationQuaternion) {
  10867. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10868. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10869. }
  10870. else {
  10871. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10872. this._cache.rotation.copyFrom(this.rotation);
  10873. }
  10874. // Translation
  10875. if (this.infiniteDistance && !this.parent) {
  10876. var camera = this.getScene().activeCamera;
  10877. if (camera) {
  10878. var cameraWorldMatrix = camera.getWorldMatrix();
  10879. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10880. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10881. }
  10882. }
  10883. else {
  10884. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10885. }
  10886. // Composing transformations
  10887. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10888. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10889. // Billboarding
  10890. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10891. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10892. var localPosition = BABYLON.Tmp.Vector3[0];
  10893. if (this.parent && this.parent.getWorldMatrix) {
  10894. this._markSyncedWithParent();
  10895. var parentMatrix;
  10896. if (this._meshToBoneReferal) {
  10897. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10898. parentMatrix = BABYLON.Tmp.Matrix[6];
  10899. }
  10900. else {
  10901. parentMatrix = this.parent.getWorldMatrix();
  10902. }
  10903. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10904. localPosition = BABYLON.Tmp.Vector3[1];
  10905. }
  10906. var zero = this.getScene().activeCamera.globalPosition.clone();
  10907. if (this.parent && this.parent.position) {
  10908. localPosition.addInPlace(this.parent.position);
  10909. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10910. }
  10911. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10912. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10913. zero.x = localPosition.x + BABYLON.Epsilon;
  10914. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10915. zero.y = localPosition.y + BABYLON.Epsilon;
  10916. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10917. zero.z = localPosition.z + BABYLON.Epsilon;
  10918. }
  10919. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10920. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10921. BABYLON.Tmp.Matrix[3].invert();
  10922. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10923. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10924. }
  10925. // Local world
  10926. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10927. // Parent
  10928. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10929. this._markSyncedWithParent();
  10930. if (this._meshToBoneReferal) {
  10931. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10932. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10933. }
  10934. else {
  10935. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10936. }
  10937. }
  10938. else {
  10939. this._worldMatrix.copyFrom(this._localWorld);
  10940. }
  10941. // Bounding info
  10942. this._updateBoundingInfo();
  10943. // Absolute position
  10944. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10945. // Callbacks
  10946. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10947. if (!this._poseMatrix) {
  10948. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10949. }
  10950. return this._worldMatrix;
  10951. };
  10952. /**
  10953. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10954. * @param func: callback function to add
  10955. */
  10956. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10957. this.onAfterWorldMatrixUpdateObservable.add(func);
  10958. };
  10959. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10960. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10961. };
  10962. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10963. this.computeWorldMatrix();
  10964. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10965. };
  10966. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10967. this.computeWorldMatrix();
  10968. var invLocalWorldMatrix = this._localWorld.clone();
  10969. invLocalWorldMatrix.invert();
  10970. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10971. };
  10972. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10973. this.computeWorldMatrix(true);
  10974. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10975. };
  10976. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10977. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10978. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10979. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10980. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10981. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10982. /// <returns>Mesh oriented towards targetMesh</returns>
  10983. if (yawCor === void 0) { yawCor = 0; }
  10984. if (pitchCor === void 0) { pitchCor = 0; }
  10985. if (rollCor === void 0) { rollCor = 0; }
  10986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10987. var dv = AbstractMesh._lookAtVectorCache;
  10988. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10989. targetPoint.subtractToRef(pos, dv);
  10990. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10991. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10992. var pitch = Math.atan2(dv.y, len);
  10993. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10994. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10995. };
  10996. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10997. this._meshToBoneReferal = affectedMesh;
  10998. this.parent = bone;
  10999. if (bone.getWorldMatrix().determinant() < 0) {
  11000. this.scalingDeterminant *= -1;
  11001. }
  11002. };
  11003. AbstractMesh.prototype.detachFromBone = function () {
  11004. if (this.parent.getWorldMatrix().determinant() < 0) {
  11005. this.scalingDeterminant *= -1;
  11006. }
  11007. this._meshToBoneReferal = null;
  11008. this.parent = null;
  11009. };
  11010. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11011. return this._boundingInfo.isInFrustum(frustumPlanes);
  11012. };
  11013. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11014. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11015. ;
  11016. };
  11017. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11018. if (!this._boundingInfo || !mesh._boundingInfo) {
  11019. return false;
  11020. }
  11021. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11022. };
  11023. AbstractMesh.prototype.intersectsPoint = function (point) {
  11024. if (!this._boundingInfo) {
  11025. return false;
  11026. }
  11027. return this._boundingInfo.intersectsPoint(point);
  11028. };
  11029. // Physics
  11030. /**
  11031. * @Deprecated. Use new PhysicsImpostor instead.
  11032. * */
  11033. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11034. //legacy support
  11035. if (impostor.impostor) {
  11036. options = impostor;
  11037. impostor = impostor.impostor;
  11038. }
  11039. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11040. return this.physicsImpostor.physicsBody;
  11041. };
  11042. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11043. return this.physicsImpostor;
  11044. };
  11045. /**
  11046. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11047. */
  11048. AbstractMesh.prototype.getPhysicsMass = function () {
  11049. return this.physicsImpostor.getParam("mass");
  11050. };
  11051. /**
  11052. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11053. */
  11054. AbstractMesh.prototype.getPhysicsFriction = function () {
  11055. return this.physicsImpostor.getParam("friction");
  11056. };
  11057. /**
  11058. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11059. */
  11060. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11061. return this.physicsImpostor.getParam("restitution");
  11062. };
  11063. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11064. if (!camera) {
  11065. camera = this.getScene().activeCamera;
  11066. }
  11067. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11068. };
  11069. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11070. if (!camera) {
  11071. camera = this.getScene().activeCamera;
  11072. }
  11073. return this.absolutePosition.subtract(camera.position).length();
  11074. };
  11075. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11076. if (!this.physicsImpostor) {
  11077. return;
  11078. }
  11079. this.physicsImpostor.applyImpulse(force, contactPoint);
  11080. };
  11081. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11082. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11083. return;
  11084. }
  11085. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11086. mainPivot: pivot1,
  11087. connectedPivot: pivot2,
  11088. nativeParams: options
  11089. });
  11090. };
  11091. /**
  11092. * @Deprecated
  11093. */
  11094. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11095. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11096. this.updatePhysicsBody();
  11097. };
  11098. /**
  11099. * @Deprecated
  11100. * Calling this function is not needed anymore.
  11101. * The physics engine takes care of transofmration automatically.
  11102. */
  11103. AbstractMesh.prototype.updatePhysicsBody = function () {
  11104. //Unneeded
  11105. };
  11106. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11107. // Collisions
  11108. get: function () {
  11109. return this._checkCollisions;
  11110. },
  11111. set: function (collisionEnabled) {
  11112. this._checkCollisions = collisionEnabled;
  11113. if (this.getScene().workerCollisions) {
  11114. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11115. }
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11121. var globalPosition = this.getAbsolutePosition();
  11122. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11123. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11124. this._collider.radius = this.ellipsoid;
  11125. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11126. };
  11127. // Submeshes octree
  11128. /**
  11129. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11130. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11131. */
  11132. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11133. if (maxCapacity === void 0) { maxCapacity = 64; }
  11134. if (maxDepth === void 0) { maxDepth = 2; }
  11135. if (!this._submeshesOctree) {
  11136. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11137. }
  11138. this.computeWorldMatrix(true);
  11139. // Update octree
  11140. var bbox = this.getBoundingInfo().boundingBox;
  11141. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11142. return this._submeshesOctree;
  11143. };
  11144. // Collisions
  11145. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11146. this._generatePointsArray();
  11147. // Transformation
  11148. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11149. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11150. subMesh._lastColliderWorldVertices = [];
  11151. subMesh._trianglePlanes = [];
  11152. var start = subMesh.verticesStart;
  11153. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11154. for (var i = start; i < end; i++) {
  11155. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11156. }
  11157. }
  11158. // Collide
  11159. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11160. if (collider.collisionFound) {
  11161. collider.collidedMesh = this;
  11162. }
  11163. };
  11164. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11165. var subMeshes;
  11166. var len;
  11167. // Octrees
  11168. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11169. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11170. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11171. len = intersections.length;
  11172. subMeshes = intersections.data;
  11173. }
  11174. else {
  11175. subMeshes = this.subMeshes;
  11176. len = subMeshes.length;
  11177. }
  11178. for (var index = 0; index < len; index++) {
  11179. var subMesh = subMeshes[index];
  11180. // Bounding test
  11181. if (len > 1 && !subMesh._checkCollision(collider))
  11182. continue;
  11183. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11184. }
  11185. };
  11186. AbstractMesh.prototype._checkCollision = function (collider) {
  11187. // Bounding box test
  11188. if (!this._boundingInfo._checkCollision(collider))
  11189. return;
  11190. // Transformation matrix
  11191. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11192. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11193. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11194. };
  11195. // Picking
  11196. AbstractMesh.prototype._generatePointsArray = function () {
  11197. return false;
  11198. };
  11199. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11200. var pickingInfo = new BABYLON.PickingInfo();
  11201. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11202. return pickingInfo;
  11203. }
  11204. if (!this._generatePointsArray()) {
  11205. return pickingInfo;
  11206. }
  11207. var intersectInfo = null;
  11208. // Octrees
  11209. var subMeshes;
  11210. var len;
  11211. if (this._submeshesOctree && this.useOctreeForPicking) {
  11212. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11213. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11214. len = intersections.length;
  11215. subMeshes = intersections.data;
  11216. }
  11217. else {
  11218. subMeshes = this.subMeshes;
  11219. len = subMeshes.length;
  11220. }
  11221. for (var index = 0; index < len; index++) {
  11222. var subMesh = subMeshes[index];
  11223. // Bounding test
  11224. if (len > 1 && !subMesh.canIntersects(ray))
  11225. continue;
  11226. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11227. if (currentIntersectInfo) {
  11228. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11229. intersectInfo = currentIntersectInfo;
  11230. intersectInfo.subMeshId = index;
  11231. if (fastCheck) {
  11232. break;
  11233. }
  11234. }
  11235. }
  11236. }
  11237. if (intersectInfo) {
  11238. // Get picked point
  11239. var world = this.getWorldMatrix();
  11240. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11241. var direction = ray.direction.clone();
  11242. direction = direction.scale(intersectInfo.distance);
  11243. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11244. var pickedPoint = worldOrigin.add(worldDirection);
  11245. // Return result
  11246. pickingInfo.hit = true;
  11247. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11248. pickingInfo.pickedPoint = pickedPoint;
  11249. pickingInfo.pickedMesh = this;
  11250. pickingInfo.bu = intersectInfo.bu;
  11251. pickingInfo.bv = intersectInfo.bv;
  11252. pickingInfo.faceId = intersectInfo.faceId;
  11253. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11254. return pickingInfo;
  11255. }
  11256. return pickingInfo;
  11257. };
  11258. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11259. return null;
  11260. };
  11261. AbstractMesh.prototype.releaseSubMeshes = function () {
  11262. if (this.subMeshes) {
  11263. while (this.subMeshes.length) {
  11264. this.subMeshes[0].dispose();
  11265. }
  11266. }
  11267. else {
  11268. this.subMeshes = new Array();
  11269. }
  11270. };
  11271. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11272. var _this = this;
  11273. var index;
  11274. // Action manager
  11275. if (this.actionManager) {
  11276. this.actionManager.dispose();
  11277. this.actionManager = null;
  11278. }
  11279. // Skeleton
  11280. this.skeleton = null;
  11281. // Animations
  11282. this.getScene().stopAnimation(this);
  11283. // Physics
  11284. if (this.physicsImpostor) {
  11285. this.physicsImpostor.dispose();
  11286. }
  11287. // Intersections in progress
  11288. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11289. var other = this._intersectionsInProgress[index];
  11290. var pos = other._intersectionsInProgress.indexOf(this);
  11291. other._intersectionsInProgress.splice(pos, 1);
  11292. }
  11293. this._intersectionsInProgress = [];
  11294. // Lights
  11295. var lights = this.getScene().lights;
  11296. lights.forEach(function (light) {
  11297. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11298. if (meshIndex !== -1) {
  11299. light.includedOnlyMeshes.splice(meshIndex, 1);
  11300. }
  11301. meshIndex = light.excludedMeshes.indexOf(_this);
  11302. if (meshIndex !== -1) {
  11303. light.excludedMeshes.splice(meshIndex, 1);
  11304. }
  11305. // Shadow generators
  11306. var generator = light.getShadowGenerator();
  11307. if (generator) {
  11308. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11309. if (meshIndex !== -1) {
  11310. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11311. }
  11312. }
  11313. });
  11314. // Edges
  11315. if (this._edgesRenderer) {
  11316. this._edgesRenderer.dispose();
  11317. this._edgesRenderer = null;
  11318. }
  11319. // SubMeshes
  11320. this.releaseSubMeshes();
  11321. // Engine
  11322. this.getScene().getEngine().unbindAllAttributes();
  11323. // Remove from scene
  11324. this.getScene().removeMesh(this);
  11325. if (!doNotRecurse) {
  11326. // Particles
  11327. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11328. if (this.getScene().particleSystems[index].emitter === this) {
  11329. this.getScene().particleSystems[index].dispose();
  11330. index--;
  11331. }
  11332. }
  11333. // Children
  11334. var objects = this.getDescendants(true);
  11335. for (index = 0; index < objects.length; index++) {
  11336. objects[index].dispose();
  11337. }
  11338. }
  11339. else {
  11340. var childMeshes = this.getChildMeshes(true);
  11341. for (index = 0; index < childMeshes.length; index++) {
  11342. var child = childMeshes[index];
  11343. child.parent = null;
  11344. child.computeWorldMatrix(true);
  11345. }
  11346. }
  11347. this.onAfterWorldMatrixUpdateObservable.clear();
  11348. this.onCollideObservable.clear();
  11349. this.onCollisionPositionChangeObservable.clear();
  11350. this._isDisposed = true;
  11351. _super.prototype.dispose.call(this);
  11352. };
  11353. AbstractMesh.prototype.getDirection = function (localAxis) {
  11354. var result = BABYLON.Vector3.Zero();
  11355. this.getDirectionToRef(localAxis, result);
  11356. return result;
  11357. };
  11358. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11359. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11360. };
  11361. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11362. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11363. if (this.getScene().getRenderId() == 0) {
  11364. this.computeWorldMatrix(true);
  11365. }
  11366. var wm = this.getWorldMatrix();
  11367. if (space == BABYLON.Space.WORLD) {
  11368. var tmat = BABYLON.Tmp.Matrix[0];
  11369. wm.invertToRef(tmat);
  11370. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11371. }
  11372. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11373. this._pivotMatrix.m[12] = -point.x;
  11374. this._pivotMatrix.m[13] = -point.y;
  11375. this._pivotMatrix.m[14] = -point.z;
  11376. this._cache.pivotMatrixUpdated = true;
  11377. };
  11378. AbstractMesh.prototype.getPivotPoint = function () {
  11379. var point = BABYLON.Vector3.Zero();
  11380. this.getPivotPointToRef(point);
  11381. return point;
  11382. };
  11383. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11384. result.x = -this._pivotMatrix.m[12];
  11385. result.y = -this._pivotMatrix.m[13];
  11386. result.z = -this._pivotMatrix.m[14];
  11387. };
  11388. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11389. var point = BABYLON.Vector3.Zero();
  11390. this.getAbsolutePivotPointToRef(point);
  11391. return point;
  11392. };
  11393. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11394. result.x = this._pivotMatrix.m[12];
  11395. result.y = this._pivotMatrix.m[13];
  11396. result.z = this._pivotMatrix.m[14];
  11397. this.getPivotPointToRef(result);
  11398. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11399. };
  11400. // Statics
  11401. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11402. AbstractMesh._BILLBOARDMODE_X = 1;
  11403. AbstractMesh._BILLBOARDMODE_Y = 2;
  11404. AbstractMesh._BILLBOARDMODE_Z = 4;
  11405. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11406. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11407. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11408. return AbstractMesh;
  11409. }(BABYLON.Node));
  11410. BABYLON.AbstractMesh = AbstractMesh;
  11411. })(BABYLON || (BABYLON = {}));
  11412. //# sourceMappingURL=babylon.abstractMesh.js.map
  11413. var BABYLON;
  11414. (function (BABYLON) {
  11415. var Light = (function (_super) {
  11416. __extends(Light, _super);
  11417. function Light(name, scene) {
  11418. _super.call(this, name, scene);
  11419. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11420. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11421. this.intensity = 1.0;
  11422. this.range = Number.MAX_VALUE;
  11423. this.includeOnlyWithLayerMask = 0;
  11424. this.includedOnlyMeshes = new Array();
  11425. this.excludedMeshes = new Array();
  11426. this.excludeWithLayerMask = 0;
  11427. this.lightmapMode = 0;
  11428. // PBR Properties.
  11429. this.radius = 0.00001;
  11430. this._excludedMeshesIds = new Array();
  11431. this._includedOnlyMeshesIds = new Array();
  11432. scene.addLight(this);
  11433. }
  11434. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11435. /**
  11436. * If every light affecting the material is in this lightmapMode,
  11437. * material.lightmapTexture adds or multiplies
  11438. * (depends on material.useLightmapAsShadowmap)
  11439. * after every other light calculations.
  11440. */
  11441. get: function () {
  11442. return Light._LIGHTMAP_DEFAULT;
  11443. },
  11444. enumerable: true,
  11445. configurable: true
  11446. });
  11447. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11448. /**
  11449. * material.lightmapTexture as only diffuse lighting from this light
  11450. * adds pnly specular lighting from this light
  11451. * adds dynamic shadows
  11452. */
  11453. get: function () {
  11454. return Light._LIGHTMAP_SPECULAR;
  11455. },
  11456. enumerable: true,
  11457. configurable: true
  11458. });
  11459. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11460. /**
  11461. * material.lightmapTexture as only lighting
  11462. * no light calculation from this light
  11463. * only adds dynamic shadows from this light
  11464. */
  11465. get: function () {
  11466. return Light._LIGHTMAP_SHADOWSONLY;
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Light.prototype.getClassName = function () {
  11472. return "Light";
  11473. };
  11474. /**
  11475. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11476. */
  11477. Light.prototype.toString = function (fullDetails) {
  11478. var ret = "Name: " + this.name;
  11479. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11480. if (this.animations) {
  11481. for (var i = 0; i < this.animations.length; i++) {
  11482. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11483. }
  11484. }
  11485. if (fullDetails) {
  11486. }
  11487. return ret;
  11488. };
  11489. Light.prototype.getShadowGenerator = function () {
  11490. return this._shadowGenerator;
  11491. };
  11492. Light.prototype.getAbsolutePosition = function () {
  11493. return BABYLON.Vector3.Zero();
  11494. };
  11495. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11496. };
  11497. Light.prototype._getWorldMatrix = function () {
  11498. return BABYLON.Matrix.Identity();
  11499. };
  11500. Light.prototype.canAffectMesh = function (mesh) {
  11501. if (!mesh) {
  11502. return true;
  11503. }
  11504. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11505. return false;
  11506. }
  11507. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11508. return false;
  11509. }
  11510. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11511. return false;
  11512. }
  11513. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11514. return false;
  11515. }
  11516. return true;
  11517. };
  11518. Light.prototype.getWorldMatrix = function () {
  11519. this._currentRenderId = this.getScene().getRenderId();
  11520. var worldMatrix = this._getWorldMatrix();
  11521. if (this.parent && this.parent.getWorldMatrix) {
  11522. if (!this._parentedWorldMatrix) {
  11523. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11524. }
  11525. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11526. this._markSyncedWithParent();
  11527. return this._parentedWorldMatrix;
  11528. }
  11529. return worldMatrix;
  11530. };
  11531. Light.prototype.dispose = function () {
  11532. if (this._shadowGenerator) {
  11533. this._shadowGenerator.dispose();
  11534. this._shadowGenerator = null;
  11535. }
  11536. // Animations
  11537. this.getScene().stopAnimation(this);
  11538. // Remove from scene
  11539. this.getScene().removeLight(this);
  11540. _super.prototype.dispose.call(this);
  11541. };
  11542. Light.prototype.getTypeID = function () {
  11543. return 0;
  11544. };
  11545. Light.prototype.clone = function (name) {
  11546. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11547. };
  11548. Light.prototype.serialize = function () {
  11549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11550. // Type
  11551. serializationObject.type = this.getTypeID();
  11552. // Parent
  11553. if (this.parent) {
  11554. serializationObject.parentId = this.parent.id;
  11555. }
  11556. // Inclusion / exclusions
  11557. if (this.excludedMeshes.length > 0) {
  11558. serializationObject.excludedMeshesIds = [];
  11559. this.excludedMeshes.forEach(function (mesh) {
  11560. serializationObject.excludedMeshesIds.push(mesh.id);
  11561. });
  11562. }
  11563. if (this.includedOnlyMeshes.length > 0) {
  11564. serializationObject.includedOnlyMeshesIds = [];
  11565. this.includedOnlyMeshes.forEach(function (mesh) {
  11566. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11567. });
  11568. }
  11569. // Animations
  11570. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11571. serializationObject.ranges = this.serializeAnimationRanges();
  11572. return serializationObject;
  11573. };
  11574. Light.GetConstructorFromName = function (type, name, scene) {
  11575. switch (type) {
  11576. case 0:
  11577. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11578. case 1:
  11579. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11580. case 2:
  11581. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11582. case 3:
  11583. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11584. }
  11585. };
  11586. Light.Parse = function (parsedLight, scene) {
  11587. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11588. // Inclusion / exclusions
  11589. if (parsedLight.excludedMeshesIds) {
  11590. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11591. }
  11592. if (parsedLight.includedOnlyMeshesIds) {
  11593. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11594. }
  11595. // Parent
  11596. if (parsedLight.parentId) {
  11597. light._waitingParentId = parsedLight.parentId;
  11598. }
  11599. // Animations
  11600. if (parsedLight.animations) {
  11601. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11602. var parsedAnimation = parsedLight.animations[animationIndex];
  11603. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11604. }
  11605. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11606. }
  11607. if (parsedLight.autoAnimate) {
  11608. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11609. }
  11610. return light;
  11611. };
  11612. //lightmapMode Consts
  11613. Light._LIGHTMAP_DEFAULT = 0;
  11614. Light._LIGHTMAP_SPECULAR = 1;
  11615. Light._LIGHTMAP_SHADOWSONLY = 2;
  11616. __decorate([
  11617. BABYLON.serializeAsColor3()
  11618. ], Light.prototype, "diffuse", void 0);
  11619. __decorate([
  11620. BABYLON.serializeAsColor3()
  11621. ], Light.prototype, "specular", void 0);
  11622. __decorate([
  11623. BABYLON.serialize()
  11624. ], Light.prototype, "intensity", void 0);
  11625. __decorate([
  11626. BABYLON.serialize()
  11627. ], Light.prototype, "range", void 0);
  11628. __decorate([
  11629. BABYLON.serialize()
  11630. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11631. __decorate([
  11632. BABYLON.serialize()
  11633. ], Light.prototype, "excludeWithLayerMask", void 0);
  11634. __decorate([
  11635. BABYLON.serialize()
  11636. ], Light.prototype, "lightmapMode", void 0);
  11637. __decorate([
  11638. BABYLON.serialize()
  11639. ], Light.prototype, "radius", void 0);
  11640. return Light;
  11641. }(BABYLON.Node));
  11642. BABYLON.Light = Light;
  11643. })(BABYLON || (BABYLON = {}));
  11644. //# sourceMappingURL=babylon.light.js.map
  11645. var BABYLON;
  11646. (function (BABYLON) {
  11647. var PointLight = (function (_super) {
  11648. __extends(PointLight, _super);
  11649. function PointLight(name, position, scene) {
  11650. _super.call(this, name, scene);
  11651. this.position = position;
  11652. }
  11653. PointLight.prototype.getClassName = function () {
  11654. return "PointLight";
  11655. };
  11656. PointLight.prototype.getAbsolutePosition = function () {
  11657. return this.transformedPosition ? this.transformedPosition : this.position;
  11658. };
  11659. PointLight.prototype.computeTransformedPosition = function () {
  11660. if (this.parent && this.parent.getWorldMatrix) {
  11661. if (!this.transformedPosition) {
  11662. this.transformedPosition = BABYLON.Vector3.Zero();
  11663. }
  11664. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11665. return true;
  11666. }
  11667. return false;
  11668. };
  11669. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11670. if (this.parent && this.parent.getWorldMatrix) {
  11671. this.computeTransformedPosition();
  11672. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11673. return;
  11674. }
  11675. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11676. };
  11677. PointLight.prototype.needCube = function () {
  11678. return true;
  11679. };
  11680. PointLight.prototype.supportsVSM = function () {
  11681. return false;
  11682. };
  11683. PointLight.prototype.needRefreshPerFrame = function () {
  11684. return false;
  11685. };
  11686. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11687. switch (faceIndex) {
  11688. case 0:
  11689. return new BABYLON.Vector3(1, 0, 0);
  11690. case 1:
  11691. return new BABYLON.Vector3(-1, 0, 0);
  11692. case 2:
  11693. return new BABYLON.Vector3(0, -1, 0);
  11694. case 3:
  11695. return new BABYLON.Vector3(0, 1, 0);
  11696. case 4:
  11697. return new BABYLON.Vector3(0, 0, 1);
  11698. case 5:
  11699. return new BABYLON.Vector3(0, 0, -1);
  11700. }
  11701. return BABYLON.Vector3.Zero();
  11702. };
  11703. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11704. var activeCamera = this.getScene().activeCamera;
  11705. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11706. };
  11707. PointLight.prototype._getWorldMatrix = function () {
  11708. if (!this._worldMatrix) {
  11709. this._worldMatrix = BABYLON.Matrix.Identity();
  11710. }
  11711. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11712. return this._worldMatrix;
  11713. };
  11714. PointLight.prototype.getTypeID = function () {
  11715. return 0;
  11716. };
  11717. __decorate([
  11718. BABYLON.serializeAsVector3()
  11719. ], PointLight.prototype, "position", void 0);
  11720. return PointLight;
  11721. }(BABYLON.Light));
  11722. BABYLON.PointLight = PointLight;
  11723. })(BABYLON || (BABYLON = {}));
  11724. //# sourceMappingURL=babylon.pointLight.js.map
  11725. var BABYLON;
  11726. (function (BABYLON) {
  11727. var SpotLight = (function (_super) {
  11728. __extends(SpotLight, _super);
  11729. function SpotLight(name, position, direction, angle, exponent, scene) {
  11730. _super.call(this, name, scene);
  11731. this.position = position;
  11732. this.direction = direction;
  11733. this.angle = angle;
  11734. this.exponent = exponent;
  11735. }
  11736. SpotLight.prototype.getClassName = function () {
  11737. return "SpotLight";
  11738. };
  11739. SpotLight.prototype.getAbsolutePosition = function () {
  11740. return this.transformedPosition ? this.transformedPosition : this.position;
  11741. };
  11742. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11743. var activeCamera = this.getScene().activeCamera;
  11744. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11745. };
  11746. SpotLight.prototype.needCube = function () {
  11747. return false;
  11748. };
  11749. SpotLight.prototype.supportsVSM = function () {
  11750. return true;
  11751. };
  11752. SpotLight.prototype.needRefreshPerFrame = function () {
  11753. return false;
  11754. };
  11755. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11756. return this.direction;
  11757. };
  11758. SpotLight.prototype.setDirectionToTarget = function (target) {
  11759. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11760. return this.direction;
  11761. };
  11762. SpotLight.prototype.computeTransformedPosition = function () {
  11763. if (this.parent && this.parent.getWorldMatrix) {
  11764. if (!this.transformedPosition) {
  11765. this.transformedPosition = BABYLON.Vector3.Zero();
  11766. }
  11767. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11768. return true;
  11769. }
  11770. return false;
  11771. };
  11772. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11773. var normalizeDirection;
  11774. if (this.parent && this.parent.getWorldMatrix) {
  11775. if (!this._transformedDirection) {
  11776. this._transformedDirection = BABYLON.Vector3.Zero();
  11777. }
  11778. this.computeTransformedPosition();
  11779. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11780. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11781. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11782. }
  11783. else {
  11784. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11785. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11786. }
  11787. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11788. };
  11789. SpotLight.prototype._getWorldMatrix = function () {
  11790. if (!this._worldMatrix) {
  11791. this._worldMatrix = BABYLON.Matrix.Identity();
  11792. }
  11793. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11794. return this._worldMatrix;
  11795. };
  11796. SpotLight.prototype.getTypeID = function () {
  11797. return 2;
  11798. };
  11799. SpotLight.prototype.getRotation = function () {
  11800. this.direction.normalize();
  11801. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11802. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11803. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11804. };
  11805. __decorate([
  11806. BABYLON.serializeAsVector3()
  11807. ], SpotLight.prototype, "position", void 0);
  11808. __decorate([
  11809. BABYLON.serializeAsVector3()
  11810. ], SpotLight.prototype, "direction", void 0);
  11811. __decorate([
  11812. BABYLON.serialize()
  11813. ], SpotLight.prototype, "angle", void 0);
  11814. __decorate([
  11815. BABYLON.serialize()
  11816. ], SpotLight.prototype, "exponent", void 0);
  11817. return SpotLight;
  11818. }(BABYLON.Light));
  11819. BABYLON.SpotLight = SpotLight;
  11820. })(BABYLON || (BABYLON = {}));
  11821. //# sourceMappingURL=babylon.spotLight.js.map
  11822. var BABYLON;
  11823. (function (BABYLON) {
  11824. var HemisphericLight = (function (_super) {
  11825. __extends(HemisphericLight, _super);
  11826. function HemisphericLight(name, direction, scene) {
  11827. _super.call(this, name, scene);
  11828. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11829. this.direction = direction;
  11830. }
  11831. HemisphericLight.prototype.getClassName = function () {
  11832. return "HemisphericLight";
  11833. };
  11834. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11835. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11836. return this.direction;
  11837. };
  11838. HemisphericLight.prototype.getShadowGenerator = function () {
  11839. return null;
  11840. };
  11841. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11842. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11843. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11844. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11845. };
  11846. HemisphericLight.prototype._getWorldMatrix = function () {
  11847. if (!this._worldMatrix) {
  11848. this._worldMatrix = BABYLON.Matrix.Identity();
  11849. }
  11850. return this._worldMatrix;
  11851. };
  11852. HemisphericLight.prototype.getTypeID = function () {
  11853. return 3;
  11854. };
  11855. __decorate([
  11856. BABYLON.serializeAsColor3()
  11857. ], HemisphericLight.prototype, "groundColor", void 0);
  11858. __decorate([
  11859. BABYLON.serializeAsVector3()
  11860. ], HemisphericLight.prototype, "direction", void 0);
  11861. return HemisphericLight;
  11862. }(BABYLON.Light));
  11863. BABYLON.HemisphericLight = HemisphericLight;
  11864. })(BABYLON || (BABYLON = {}));
  11865. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11866. var BABYLON;
  11867. (function (BABYLON) {
  11868. var DirectionalLight = (function (_super) {
  11869. __extends(DirectionalLight, _super);
  11870. function DirectionalLight(name, direction, scene) {
  11871. _super.call(this, name, scene);
  11872. this.shadowOrthoScale = 0.5;
  11873. this.autoUpdateExtends = true;
  11874. // Cache
  11875. this._orthoLeft = Number.MAX_VALUE;
  11876. this._orthoRight = Number.MIN_VALUE;
  11877. this._orthoTop = Number.MIN_VALUE;
  11878. this._orthoBottom = Number.MAX_VALUE;
  11879. this.position = direction.scale(-1);
  11880. this.direction = direction;
  11881. }
  11882. DirectionalLight.prototype.getClassName = function () {
  11883. return "DirectionalLight";
  11884. };
  11885. DirectionalLight.prototype.getAbsolutePosition = function () {
  11886. return this.transformedPosition ? this.transformedPosition : this.position;
  11887. };
  11888. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11889. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11890. return this.direction;
  11891. };
  11892. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11893. var activeCamera = this.getScene().activeCamera;
  11894. // Check extends
  11895. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11896. var tempVector3 = BABYLON.Vector3.Zero();
  11897. this._orthoLeft = Number.MAX_VALUE;
  11898. this._orthoRight = Number.MIN_VALUE;
  11899. this._orthoTop = Number.MIN_VALUE;
  11900. this._orthoBottom = Number.MAX_VALUE;
  11901. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11902. var mesh = renderList[meshIndex];
  11903. if (!mesh) {
  11904. continue;
  11905. }
  11906. var boundingInfo = mesh.getBoundingInfo();
  11907. if (!boundingInfo) {
  11908. continue;
  11909. }
  11910. var boundingBox = boundingInfo.boundingBox;
  11911. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11912. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11913. if (tempVector3.x < this._orthoLeft)
  11914. this._orthoLeft = tempVector3.x;
  11915. if (tempVector3.y < this._orthoBottom)
  11916. this._orthoBottom = tempVector3.y;
  11917. if (tempVector3.x > this._orthoRight)
  11918. this._orthoRight = tempVector3.x;
  11919. if (tempVector3.y > this._orthoTop)
  11920. this._orthoTop = tempVector3.y;
  11921. }
  11922. }
  11923. }
  11924. var xOffset = this._orthoRight - this._orthoLeft;
  11925. var yOffset = this._orthoTop - this._orthoBottom;
  11926. 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);
  11927. };
  11928. DirectionalLight.prototype.supportsVSM = function () {
  11929. return true;
  11930. };
  11931. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11932. return true;
  11933. };
  11934. DirectionalLight.prototype.needCube = function () {
  11935. return false;
  11936. };
  11937. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11938. return this.direction;
  11939. };
  11940. DirectionalLight.prototype.computeTransformedPosition = function () {
  11941. if (this.parent && this.parent.getWorldMatrix) {
  11942. if (!this.transformedPosition) {
  11943. this.transformedPosition = BABYLON.Vector3.Zero();
  11944. }
  11945. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11946. return true;
  11947. }
  11948. return false;
  11949. };
  11950. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11951. if (this.parent && this.parent.getWorldMatrix) {
  11952. if (!this._transformedDirection) {
  11953. this._transformedDirection = BABYLON.Vector3.Zero();
  11954. }
  11955. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11956. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11957. return;
  11958. }
  11959. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11960. };
  11961. DirectionalLight.prototype._getWorldMatrix = function () {
  11962. if (!this._worldMatrix) {
  11963. this._worldMatrix = BABYLON.Matrix.Identity();
  11964. }
  11965. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11966. return this._worldMatrix;
  11967. };
  11968. DirectionalLight.prototype.getTypeID = function () {
  11969. return 1;
  11970. };
  11971. __decorate([
  11972. BABYLON.serializeAsVector3()
  11973. ], DirectionalLight.prototype, "position", void 0);
  11974. __decorate([
  11975. BABYLON.serializeAsVector3()
  11976. ], DirectionalLight.prototype, "direction", void 0);
  11977. __decorate([
  11978. BABYLON.serialize()
  11979. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11980. __decorate([
  11981. BABYLON.serialize()
  11982. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11983. return DirectionalLight;
  11984. }(BABYLON.Light));
  11985. BABYLON.DirectionalLight = DirectionalLight;
  11986. })(BABYLON || (BABYLON = {}));
  11987. //# sourceMappingURL=babylon.directionalLight.js.map
  11988. var BABYLON;
  11989. (function (BABYLON) {
  11990. var ShadowGenerator = (function () {
  11991. function ShadowGenerator(mapSize, light) {
  11992. var _this = this;
  11993. // Members
  11994. this._filter = ShadowGenerator.FILTER_NONE;
  11995. this.blurScale = 2;
  11996. this._blurBoxOffset = 0;
  11997. this._bias = 0.00005;
  11998. this._lightDirection = BABYLON.Vector3.Zero();
  11999. this.forceBackFacesOnly = false;
  12000. this._darkness = 0;
  12001. this._transparencyShadow = false;
  12002. this._viewMatrix = BABYLON.Matrix.Zero();
  12003. this._projectionMatrix = BABYLON.Matrix.Zero();
  12004. this._transformMatrix = BABYLON.Matrix.Zero();
  12005. this._worldViewProjection = BABYLON.Matrix.Zero();
  12006. this._currentFaceIndex = 0;
  12007. this._currentFaceIndexCache = 0;
  12008. this._useFullFloat = true;
  12009. this._light = light;
  12010. this._scene = light.getScene();
  12011. this._mapSize = mapSize;
  12012. light._shadowGenerator = this;
  12013. // Texture type fallback from float to int if not supported.
  12014. var textureType;
  12015. var caps = this._scene.getEngine().getCaps();
  12016. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12017. this._useFullFloat = true;
  12018. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12019. }
  12020. else {
  12021. this._useFullFloat = false;
  12022. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12023. }
  12024. // Render target
  12025. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12026. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12027. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12028. this._shadowMap.anisotropicFilteringLevel = 1;
  12029. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12030. this._shadowMap.renderParticles = false;
  12031. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12032. _this._currentFaceIndex = faceIndex;
  12033. });
  12034. this._shadowMap.onAfterUnbindObservable.add(function () {
  12035. if (!_this.useBlurVarianceShadowMap) {
  12036. return;
  12037. }
  12038. if (!_this._shadowMap2) {
  12039. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12040. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12041. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12042. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12043. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12044. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12045. effect.setTexture("textureSampler", _this._shadowMap);
  12046. });
  12047. _this.blurBoxOffset = 1;
  12048. }
  12049. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12050. });
  12051. // Custom render function
  12052. var renderSubMesh = function (subMesh) {
  12053. var mesh = subMesh.getRenderingMesh();
  12054. var scene = _this._scene;
  12055. var engine = scene.getEngine();
  12056. // Culling
  12057. engine.setState(subMesh.getMaterial().backFaceCulling);
  12058. // Managing instances
  12059. var batch = mesh._getInstancesRenderList(subMesh._id);
  12060. if (batch.mustReturn) {
  12061. return;
  12062. }
  12063. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12064. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12065. engine.enableEffect(_this._effect);
  12066. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12067. var material = subMesh.getMaterial();
  12068. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12069. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12070. if (_this.getLight().needCube()) {
  12071. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12072. }
  12073. // Alpha test
  12074. if (material && material.needAlphaTesting()) {
  12075. var alphaTexture = material.getAlphaTestTexture();
  12076. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12077. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12078. }
  12079. // Bones
  12080. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12081. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12082. }
  12083. if (_this.forceBackFacesOnly) {
  12084. engine.setState(true, 0, false, true);
  12085. }
  12086. // Draw
  12087. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12088. if (_this.forceBackFacesOnly) {
  12089. engine.setState(true, 0, false, false);
  12090. }
  12091. }
  12092. else {
  12093. // Need to reset refresh rate of the shadowMap
  12094. _this._shadowMap.resetRefreshCounter();
  12095. }
  12096. };
  12097. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12098. var index;
  12099. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12100. renderSubMesh(opaqueSubMeshes.data[index]);
  12101. }
  12102. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12103. renderSubMesh(alphaTestSubMeshes.data[index]);
  12104. }
  12105. if (_this._transparencyShadow) {
  12106. for (index = 0; index < transparentSubMeshes.length; index++) {
  12107. renderSubMesh(transparentSubMeshes.data[index]);
  12108. }
  12109. }
  12110. };
  12111. this._shadowMap.onClearObservable.add(function (engine) {
  12112. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12113. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12114. }
  12115. else {
  12116. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12117. }
  12118. });
  12119. }
  12120. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12121. // Static
  12122. get: function () {
  12123. return ShadowGenerator._FILTER_NONE;
  12124. },
  12125. enumerable: true,
  12126. configurable: true
  12127. });
  12128. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12129. get: function () {
  12130. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12131. },
  12132. enumerable: true,
  12133. configurable: true
  12134. });
  12135. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12136. get: function () {
  12137. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12143. get: function () {
  12144. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12145. },
  12146. enumerable: true,
  12147. configurable: true
  12148. });
  12149. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12150. get: function () {
  12151. return this._bias;
  12152. },
  12153. set: function (bias) {
  12154. this._bias = bias;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12160. get: function () {
  12161. return this._blurBoxOffset;
  12162. },
  12163. set: function (value) {
  12164. var _this = this;
  12165. if (this._blurBoxOffset === value) {
  12166. return;
  12167. }
  12168. this._blurBoxOffset = value;
  12169. if (this._boxBlurPostprocess) {
  12170. this._boxBlurPostprocess.dispose();
  12171. }
  12172. 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);
  12173. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12174. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12175. });
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12181. get: function () {
  12182. return this._filter;
  12183. },
  12184. set: function (value) {
  12185. if (this._filter === value) {
  12186. return;
  12187. }
  12188. this._filter = value;
  12189. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12190. this._shadowMap.anisotropicFilteringLevel = 16;
  12191. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12192. }
  12193. else {
  12194. this._shadowMap.anisotropicFilteringLevel = 1;
  12195. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12196. }
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12202. get: function () {
  12203. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12204. },
  12205. set: function (value) {
  12206. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12212. get: function () {
  12213. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12214. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12215. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12216. },
  12217. set: function (value) {
  12218. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12224. get: function () {
  12225. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12226. },
  12227. set: function (value) {
  12228. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12234. var defines = [];
  12235. if (this._useFullFloat) {
  12236. defines.push("#define FULLFLOAT");
  12237. }
  12238. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12239. defines.push("#define VSM");
  12240. }
  12241. if (this.getLight().needCube()) {
  12242. defines.push("#define CUBEMAP");
  12243. }
  12244. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12245. var mesh = subMesh.getMesh();
  12246. var material = subMesh.getMaterial();
  12247. // Alpha test
  12248. if (material && material.needAlphaTesting()) {
  12249. defines.push("#define ALPHATEST");
  12250. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12251. attribs.push(BABYLON.VertexBuffer.UVKind);
  12252. defines.push("#define UV1");
  12253. }
  12254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12255. var alphaTexture = material.getAlphaTestTexture();
  12256. if (alphaTexture.coordinatesIndex === 1) {
  12257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12258. defines.push("#define UV2");
  12259. }
  12260. }
  12261. }
  12262. // Bones
  12263. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12264. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12265. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12266. if (mesh.numBoneInfluencers > 4) {
  12267. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12268. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12269. }
  12270. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12271. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12272. }
  12273. else {
  12274. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12275. }
  12276. // Instances
  12277. if (useInstances) {
  12278. defines.push("#define INSTANCES");
  12279. attribs.push("world0");
  12280. attribs.push("world1");
  12281. attribs.push("world2");
  12282. attribs.push("world3");
  12283. }
  12284. // Get correct effect
  12285. var join = defines.join("\n");
  12286. if (this._cachedDefines !== join) {
  12287. this._cachedDefines = join;
  12288. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12289. }
  12290. return this._effect.isReady();
  12291. };
  12292. ShadowGenerator.prototype.getShadowMap = function () {
  12293. return this._shadowMap;
  12294. };
  12295. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12296. if (this._shadowMap2) {
  12297. return this._shadowMap2;
  12298. }
  12299. return this._shadowMap;
  12300. };
  12301. ShadowGenerator.prototype.getLight = function () {
  12302. return this._light;
  12303. };
  12304. // Methods
  12305. ShadowGenerator.prototype.getTransformMatrix = function () {
  12306. var scene = this._scene;
  12307. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12308. return this._transformMatrix;
  12309. }
  12310. this._currentRenderID = scene.getRenderId();
  12311. this._currentFaceIndexCache = this._currentFaceIndex;
  12312. var lightPosition = this._light.position;
  12313. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12314. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12315. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12316. }
  12317. if (this._light.computeTransformedPosition()) {
  12318. lightPosition = this._light.transformedPosition;
  12319. }
  12320. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12321. this._cachedPosition = lightPosition.clone();
  12322. this._cachedDirection = this._lightDirection.clone();
  12323. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12324. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12325. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12326. }
  12327. return this._transformMatrix;
  12328. };
  12329. ShadowGenerator.prototype.getDarkness = function () {
  12330. return this._darkness;
  12331. };
  12332. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12333. if (darkness >= 1.0)
  12334. this._darkness = 1.0;
  12335. else if (darkness <= 0.0)
  12336. this._darkness = 0.0;
  12337. else
  12338. this._darkness = darkness;
  12339. };
  12340. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12341. this._transparencyShadow = hasShadow;
  12342. };
  12343. ShadowGenerator.prototype._packHalf = function (depth) {
  12344. var scale = depth * 255.0;
  12345. var fract = scale - Math.floor(scale);
  12346. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12347. };
  12348. ShadowGenerator.prototype.dispose = function () {
  12349. this._shadowMap.dispose();
  12350. if (this._shadowMap2) {
  12351. this._shadowMap2.dispose();
  12352. }
  12353. if (this._downSamplePostprocess) {
  12354. this._downSamplePostprocess.dispose();
  12355. }
  12356. if (this._boxBlurPostprocess) {
  12357. this._boxBlurPostprocess.dispose();
  12358. }
  12359. };
  12360. ShadowGenerator.prototype.serialize = function () {
  12361. var serializationObject = {};
  12362. serializationObject.lightId = this._light.id;
  12363. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12364. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12365. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12366. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12367. serializationObject.renderList = [];
  12368. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12369. var mesh = this.getShadowMap().renderList[meshIndex];
  12370. serializationObject.renderList.push(mesh.id);
  12371. }
  12372. return serializationObject;
  12373. };
  12374. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12375. //casting to point light, as light is missing the position attr and typescript complains.
  12376. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12377. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12378. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12379. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12380. meshes.forEach(function (mesh) {
  12381. shadowGenerator.getShadowMap().renderList.push(mesh);
  12382. });
  12383. }
  12384. if (parsedShadowGenerator.usePoissonSampling) {
  12385. shadowGenerator.usePoissonSampling = true;
  12386. }
  12387. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12388. shadowGenerator.useVarianceShadowMap = true;
  12389. }
  12390. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12391. shadowGenerator.useBlurVarianceShadowMap = true;
  12392. if (parsedShadowGenerator.blurScale) {
  12393. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12394. }
  12395. if (parsedShadowGenerator.blurBoxOffset) {
  12396. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12397. }
  12398. }
  12399. if (parsedShadowGenerator.bias !== undefined) {
  12400. shadowGenerator.bias = parsedShadowGenerator.bias;
  12401. }
  12402. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12403. return shadowGenerator;
  12404. };
  12405. ShadowGenerator._FILTER_NONE = 0;
  12406. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12407. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12408. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12409. return ShadowGenerator;
  12410. }());
  12411. BABYLON.ShadowGenerator = ShadowGenerator;
  12412. })(BABYLON || (BABYLON = {}));
  12413. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12414. var BABYLON;
  12415. (function (BABYLON) {
  12416. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12417. if (boxMin.x > sphereCenter.x + sphereRadius)
  12418. return false;
  12419. if (sphereCenter.x - sphereRadius > boxMax.x)
  12420. return false;
  12421. if (boxMin.y > sphereCenter.y + sphereRadius)
  12422. return false;
  12423. if (sphereCenter.y - sphereRadius > boxMax.y)
  12424. return false;
  12425. if (boxMin.z > sphereCenter.z + sphereRadius)
  12426. return false;
  12427. if (sphereCenter.z - sphereRadius > boxMax.z)
  12428. return false;
  12429. return true;
  12430. };
  12431. var getLowestRoot = (function () {
  12432. var result = { root: 0, found: false };
  12433. return function (a, b, c, maxR) {
  12434. result.root = 0;
  12435. result.found = false;
  12436. var determinant = b * b - 4.0 * a * c;
  12437. if (determinant < 0)
  12438. return result;
  12439. var sqrtD = Math.sqrt(determinant);
  12440. var r1 = (-b - sqrtD) / (2.0 * a);
  12441. var r2 = (-b + sqrtD) / (2.0 * a);
  12442. if (r1 > r2) {
  12443. var temp = r2;
  12444. r2 = r1;
  12445. r1 = temp;
  12446. }
  12447. if (r1 > 0 && r1 < maxR) {
  12448. result.root = r1;
  12449. result.found = true;
  12450. return result;
  12451. }
  12452. if (r2 > 0 && r2 < maxR) {
  12453. result.root = r2;
  12454. result.found = true;
  12455. return result;
  12456. }
  12457. return result;
  12458. };
  12459. })();
  12460. var Collider = (function () {
  12461. function Collider() {
  12462. this.radius = new BABYLON.Vector3(1, 1, 1);
  12463. this.retry = 0;
  12464. this.basePointWorld = BABYLON.Vector3.Zero();
  12465. this.velocityWorld = BABYLON.Vector3.Zero();
  12466. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12467. this._collisionPoint = BABYLON.Vector3.Zero();
  12468. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12469. this._tempVector = BABYLON.Vector3.Zero();
  12470. this._tempVector2 = BABYLON.Vector3.Zero();
  12471. this._tempVector3 = BABYLON.Vector3.Zero();
  12472. this._tempVector4 = BABYLON.Vector3.Zero();
  12473. this._edge = BABYLON.Vector3.Zero();
  12474. this._baseToVertex = BABYLON.Vector3.Zero();
  12475. this._destinationPoint = BABYLON.Vector3.Zero();
  12476. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12477. this._displacementVector = BABYLON.Vector3.Zero();
  12478. }
  12479. // Methods
  12480. Collider.prototype._initialize = function (source, dir, e) {
  12481. this.velocity = dir;
  12482. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12483. this.basePoint = source;
  12484. source.multiplyToRef(this.radius, this.basePointWorld);
  12485. dir.multiplyToRef(this.radius, this.velocityWorld);
  12486. this.velocityWorldLength = this.velocityWorld.length();
  12487. this.epsilon = e;
  12488. this.collisionFound = false;
  12489. };
  12490. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12491. pa.subtractToRef(point, this._tempVector);
  12492. pb.subtractToRef(point, this._tempVector2);
  12493. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12494. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12495. if (d < 0)
  12496. return false;
  12497. pc.subtractToRef(point, this._tempVector3);
  12498. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12499. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12500. if (d < 0)
  12501. return false;
  12502. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12503. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12504. return d >= 0;
  12505. };
  12506. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12507. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12508. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12509. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12510. return false;
  12511. }
  12512. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12513. return false;
  12514. return true;
  12515. };
  12516. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12517. var t0;
  12518. var embeddedInPlane = false;
  12519. //defensive programming, actually not needed.
  12520. if (!trianglePlaneArray) {
  12521. trianglePlaneArray = [];
  12522. }
  12523. if (!trianglePlaneArray[faceIndex]) {
  12524. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12525. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12526. }
  12527. var trianglePlane = trianglePlaneArray[faceIndex];
  12528. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12529. return;
  12530. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12531. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12532. if (normalDotVelocity == 0) {
  12533. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12534. return;
  12535. embeddedInPlane = true;
  12536. t0 = 0;
  12537. }
  12538. else {
  12539. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12540. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12541. if (t0 > t1) {
  12542. var temp = t1;
  12543. t1 = t0;
  12544. t0 = temp;
  12545. }
  12546. if (t0 > 1.0 || t1 < 0.0)
  12547. return;
  12548. if (t0 < 0)
  12549. t0 = 0;
  12550. if (t0 > 1.0)
  12551. t0 = 1.0;
  12552. }
  12553. this._collisionPoint.copyFromFloats(0, 0, 0);
  12554. var found = false;
  12555. var t = 1.0;
  12556. if (!embeddedInPlane) {
  12557. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12558. this.velocity.scaleToRef(t0, this._tempVector);
  12559. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12560. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12561. found = true;
  12562. t = t0;
  12563. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12564. }
  12565. }
  12566. if (!found) {
  12567. var velocitySquaredLength = this.velocity.lengthSquared();
  12568. var a = velocitySquaredLength;
  12569. this.basePoint.subtractToRef(p1, this._tempVector);
  12570. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12571. var c = this._tempVector.lengthSquared() - 1.0;
  12572. var lowestRoot = getLowestRoot(a, b, c, t);
  12573. if (lowestRoot.found) {
  12574. t = lowestRoot.root;
  12575. found = true;
  12576. this._collisionPoint.copyFrom(p1);
  12577. }
  12578. this.basePoint.subtractToRef(p2, this._tempVector);
  12579. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12580. c = this._tempVector.lengthSquared() - 1.0;
  12581. lowestRoot = getLowestRoot(a, b, c, t);
  12582. if (lowestRoot.found) {
  12583. t = lowestRoot.root;
  12584. found = true;
  12585. this._collisionPoint.copyFrom(p2);
  12586. }
  12587. this.basePoint.subtractToRef(p3, this._tempVector);
  12588. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12589. c = this._tempVector.lengthSquared() - 1.0;
  12590. lowestRoot = getLowestRoot(a, b, c, t);
  12591. if (lowestRoot.found) {
  12592. t = lowestRoot.root;
  12593. found = true;
  12594. this._collisionPoint.copyFrom(p3);
  12595. }
  12596. p2.subtractToRef(p1, this._edge);
  12597. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12598. var edgeSquaredLength = this._edge.lengthSquared();
  12599. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12600. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12601. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12602. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12603. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12604. lowestRoot = getLowestRoot(a, b, c, t);
  12605. if (lowestRoot.found) {
  12606. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12607. if (f >= 0.0 && f <= 1.0) {
  12608. t = lowestRoot.root;
  12609. found = true;
  12610. this._edge.scaleInPlace(f);
  12611. p1.addToRef(this._edge, this._collisionPoint);
  12612. }
  12613. }
  12614. p3.subtractToRef(p2, this._edge);
  12615. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12616. edgeSquaredLength = this._edge.lengthSquared();
  12617. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12618. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12619. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12620. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12621. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12622. lowestRoot = getLowestRoot(a, b, c, t);
  12623. if (lowestRoot.found) {
  12624. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12625. if (f >= 0.0 && f <= 1.0) {
  12626. t = lowestRoot.root;
  12627. found = true;
  12628. this._edge.scaleInPlace(f);
  12629. p2.addToRef(this._edge, this._collisionPoint);
  12630. }
  12631. }
  12632. p1.subtractToRef(p3, this._edge);
  12633. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12634. edgeSquaredLength = this._edge.lengthSquared();
  12635. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12636. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12637. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12638. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12639. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12640. lowestRoot = getLowestRoot(a, b, c, t);
  12641. if (lowestRoot.found) {
  12642. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12643. if (f >= 0.0 && f <= 1.0) {
  12644. t = lowestRoot.root;
  12645. found = true;
  12646. this._edge.scaleInPlace(f);
  12647. p3.addToRef(this._edge, this._collisionPoint);
  12648. }
  12649. }
  12650. }
  12651. if (found) {
  12652. var distToCollision = t * this.velocity.length();
  12653. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12654. if (!this.intersectionPoint) {
  12655. this.intersectionPoint = this._collisionPoint.clone();
  12656. }
  12657. else {
  12658. this.intersectionPoint.copyFrom(this._collisionPoint);
  12659. }
  12660. this.nearestDistance = distToCollision;
  12661. this.collisionFound = true;
  12662. }
  12663. }
  12664. };
  12665. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12666. for (var i = indexStart; i < indexEnd; i += 3) {
  12667. var p1 = pts[indices[i] - decal];
  12668. var p2 = pts[indices[i + 1] - decal];
  12669. var p3 = pts[indices[i + 2] - decal];
  12670. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12671. }
  12672. };
  12673. Collider.prototype._getResponse = function (pos, vel) {
  12674. pos.addToRef(vel, this._destinationPoint);
  12675. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12676. this.basePoint.addToRef(vel, pos);
  12677. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12678. this._slidePlaneNormal.normalize();
  12679. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12680. pos.addInPlace(this._displacementVector);
  12681. this.intersectionPoint.addInPlace(this._displacementVector);
  12682. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12683. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12684. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12685. };
  12686. return Collider;
  12687. }());
  12688. BABYLON.Collider = Collider;
  12689. })(BABYLON || (BABYLON = {}));
  12690. //# sourceMappingURL=babylon.collider.js.map
  12691. var BABYLON;
  12692. (function (BABYLON) {
  12693. //WebWorker code will be inserted to this variable.
  12694. BABYLON.CollisionWorker = "";
  12695. (function (WorkerTaskType) {
  12696. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12697. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12698. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12699. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12700. var WorkerTaskType = BABYLON.WorkerTaskType;
  12701. (function (WorkerReplyType) {
  12702. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12703. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12704. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12705. var WorkerReplyType = BABYLON.WorkerReplyType;
  12706. var CollisionCoordinatorWorker = (function () {
  12707. function CollisionCoordinatorWorker() {
  12708. var _this = this;
  12709. this._scaledPosition = BABYLON.Vector3.Zero();
  12710. this._scaledVelocity = BABYLON.Vector3.Zero();
  12711. this.onMeshUpdated = function (mesh) {
  12712. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12713. };
  12714. this.onGeometryUpdated = function (geometry) {
  12715. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12716. };
  12717. this._afterRender = function () {
  12718. if (!_this._init)
  12719. return;
  12720. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12721. return;
  12722. }
  12723. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12724. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12725. if (_this._runningUpdated > 4) {
  12726. return;
  12727. }
  12728. ++_this._runningUpdated;
  12729. var payload = {
  12730. updatedMeshes: _this._addUpdateMeshesList,
  12731. updatedGeometries: _this._addUpdateGeometriesList,
  12732. removedGeometries: _this._toRemoveGeometryArray,
  12733. removedMeshes: _this._toRemoveMeshesArray
  12734. };
  12735. var message = {
  12736. payload: payload,
  12737. taskType: WorkerTaskType.UPDATE
  12738. };
  12739. var serializable = [];
  12740. for (var id in payload.updatedGeometries) {
  12741. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12742. //prepare transferables
  12743. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12744. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12745. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12746. }
  12747. }
  12748. _this._worker.postMessage(message, serializable);
  12749. _this._addUpdateMeshesList = {};
  12750. _this._addUpdateGeometriesList = {};
  12751. _this._toRemoveGeometryArray = [];
  12752. _this._toRemoveMeshesArray = [];
  12753. };
  12754. this._onMessageFromWorker = function (e) {
  12755. var returnData = e.data;
  12756. if (returnData.error != WorkerReplyType.SUCCESS) {
  12757. //TODO what errors can be returned from the worker?
  12758. BABYLON.Tools.Warn("error returned from worker!");
  12759. return;
  12760. }
  12761. switch (returnData.taskType) {
  12762. case WorkerTaskType.INIT:
  12763. _this._init = true;
  12764. //Update the worked with ALL of the scene's current state
  12765. _this._scene.meshes.forEach(function (mesh) {
  12766. _this.onMeshAdded(mesh);
  12767. });
  12768. _this._scene.getGeometries().forEach(function (geometry) {
  12769. _this.onGeometryAdded(geometry);
  12770. });
  12771. break;
  12772. case WorkerTaskType.UPDATE:
  12773. _this._runningUpdated--;
  12774. break;
  12775. case WorkerTaskType.COLLIDE:
  12776. _this._runningCollisionTask = false;
  12777. var returnPayload = returnData.payload;
  12778. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12779. return;
  12780. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12781. //cleanup
  12782. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12783. break;
  12784. }
  12785. };
  12786. this._collisionsCallbackArray = [];
  12787. this._init = false;
  12788. this._runningUpdated = 0;
  12789. this._runningCollisionTask = false;
  12790. this._addUpdateMeshesList = {};
  12791. this._addUpdateGeometriesList = {};
  12792. this._toRemoveGeometryArray = [];
  12793. this._toRemoveMeshesArray = [];
  12794. }
  12795. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12796. if (!this._init)
  12797. return;
  12798. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12799. return;
  12800. position.divideToRef(collider.radius, this._scaledPosition);
  12801. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12802. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12803. var payload = {
  12804. collider: {
  12805. position: this._scaledPosition.asArray(),
  12806. velocity: this._scaledVelocity.asArray(),
  12807. radius: collider.radius.asArray()
  12808. },
  12809. collisionId: collisionIndex,
  12810. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12811. maximumRetry: maximumRetry
  12812. };
  12813. var message = {
  12814. payload: payload,
  12815. taskType: WorkerTaskType.COLLIDE
  12816. };
  12817. this._worker.postMessage(message);
  12818. };
  12819. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12820. this._scene = scene;
  12821. this._scene.registerAfterRender(this._afterRender);
  12822. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12823. this._worker = new Worker(workerUrl);
  12824. this._worker.onmessage = this._onMessageFromWorker;
  12825. var message = {
  12826. payload: {},
  12827. taskType: WorkerTaskType.INIT
  12828. };
  12829. this._worker.postMessage(message);
  12830. };
  12831. CollisionCoordinatorWorker.prototype.destroy = function () {
  12832. this._scene.unregisterAfterRender(this._afterRender);
  12833. this._worker.terminate();
  12834. };
  12835. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12836. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12837. this.onMeshUpdated(mesh);
  12838. };
  12839. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12840. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12841. };
  12842. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12843. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12844. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12845. this.onGeometryUpdated(geometry);
  12846. };
  12847. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12848. this._toRemoveGeometryArray.push(geometry.id);
  12849. };
  12850. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12851. var submeshes = [];
  12852. if (mesh.subMeshes) {
  12853. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12854. return {
  12855. position: idx,
  12856. verticesStart: sm.verticesStart,
  12857. verticesCount: sm.verticesCount,
  12858. indexStart: sm.indexStart,
  12859. indexCount: sm.indexCount,
  12860. hasMaterial: !!sm.getMaterial(),
  12861. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12862. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12863. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12864. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12865. };
  12866. });
  12867. }
  12868. var geometryId = null;
  12869. if (mesh instanceof BABYLON.Mesh) {
  12870. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12871. }
  12872. else if (mesh instanceof BABYLON.InstancedMesh) {
  12873. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12874. }
  12875. return {
  12876. uniqueId: mesh.uniqueId,
  12877. id: mesh.id,
  12878. name: mesh.name,
  12879. geometryId: geometryId,
  12880. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12881. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12882. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12883. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12884. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12885. subMeshes: submeshes,
  12886. checkCollisions: mesh.checkCollisions
  12887. };
  12888. };
  12889. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12890. return {
  12891. id: geometry.id,
  12892. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12893. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12894. indices: new Int32Array(geometry.getIndices() || []),
  12895. };
  12896. };
  12897. return CollisionCoordinatorWorker;
  12898. }());
  12899. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12900. var CollisionCoordinatorLegacy = (function () {
  12901. function CollisionCoordinatorLegacy() {
  12902. this._scaledPosition = BABYLON.Vector3.Zero();
  12903. this._scaledVelocity = BABYLON.Vector3.Zero();
  12904. this._finalPosition = BABYLON.Vector3.Zero();
  12905. }
  12906. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12907. position.divideToRef(collider.radius, this._scaledPosition);
  12908. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12909. collider.collidedMesh = null;
  12910. collider.retry = 0;
  12911. collider.initialVelocity = this._scaledVelocity;
  12912. collider.initialPosition = this._scaledPosition;
  12913. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12914. this._finalPosition.multiplyInPlace(collider.radius);
  12915. //run the callback
  12916. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12917. };
  12918. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12919. this._scene = scene;
  12920. };
  12921. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12922. //Legacy need no destruction method.
  12923. };
  12924. //No update in legacy mode
  12925. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12926. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12927. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12928. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12929. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12930. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12931. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12932. if (excludedMesh === void 0) { excludedMesh = null; }
  12933. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12934. if (collider.retry >= maximumRetry) {
  12935. finalPosition.copyFrom(position);
  12936. return;
  12937. }
  12938. collider._initialize(position, velocity, closeDistance);
  12939. // Check all meshes
  12940. for (var index = 0; index < this._scene.meshes.length; index++) {
  12941. var mesh = this._scene.meshes[index];
  12942. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12943. mesh._checkCollision(collider);
  12944. }
  12945. }
  12946. if (!collider.collisionFound) {
  12947. position.addToRef(velocity, finalPosition);
  12948. return;
  12949. }
  12950. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12951. collider._getResponse(position, velocity);
  12952. }
  12953. if (velocity.length() <= closeDistance) {
  12954. finalPosition.copyFrom(position);
  12955. return;
  12956. }
  12957. collider.retry++;
  12958. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12959. };
  12960. return CollisionCoordinatorLegacy;
  12961. }());
  12962. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12963. })(BABYLON || (BABYLON = {}));
  12964. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12965. var BABYLON;
  12966. (function (BABYLON) {
  12967. var Camera = (function (_super) {
  12968. __extends(Camera, _super);
  12969. function Camera(name, position, scene) {
  12970. _super.call(this, name, scene);
  12971. this.upVector = BABYLON.Vector3.Up();
  12972. this.orthoLeft = null;
  12973. this.orthoRight = null;
  12974. this.orthoBottom = null;
  12975. this.orthoTop = null;
  12976. this.fov = 0.8;
  12977. this.minZ = 1.0;
  12978. this.maxZ = 10000.0;
  12979. this.inertia = 0.9;
  12980. this.mode = Camera.PERSPECTIVE_CAMERA;
  12981. this.isIntermediate = false;
  12982. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12983. this.layerMask = 0x0FFFFFFF;
  12984. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12985. // Camera rig members
  12986. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12987. this._rigCameras = new Array();
  12988. // Cache
  12989. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12990. this._projectionMatrix = new BABYLON.Matrix();
  12991. this._doNotComputeProjectionMatrix = false;
  12992. this._postProcesses = new Array();
  12993. this._transformMatrix = BABYLON.Matrix.Zero();
  12994. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12995. this._activeMeshes = new BABYLON.SmartArray(256);
  12996. this._globalPosition = BABYLON.Vector3.Zero();
  12997. this._refreshFrustumPlanes = true;
  12998. scene.addCamera(this);
  12999. if (!scene.activeCamera) {
  13000. scene.activeCamera = this;
  13001. }
  13002. this.position = position;
  13003. }
  13004. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13005. get: function () {
  13006. return Camera._PERSPECTIVE_CAMERA;
  13007. },
  13008. enumerable: true,
  13009. configurable: true
  13010. });
  13011. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13012. get: function () {
  13013. return Camera._ORTHOGRAPHIC_CAMERA;
  13014. },
  13015. enumerable: true,
  13016. configurable: true
  13017. });
  13018. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13019. get: function () {
  13020. return Camera._FOVMODE_VERTICAL_FIXED;
  13021. },
  13022. enumerable: true,
  13023. configurable: true
  13024. });
  13025. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13026. get: function () {
  13027. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13033. get: function () {
  13034. return Camera._RIG_MODE_NONE;
  13035. },
  13036. enumerable: true,
  13037. configurable: true
  13038. });
  13039. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13040. get: function () {
  13041. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13042. },
  13043. enumerable: true,
  13044. configurable: true
  13045. });
  13046. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13047. get: function () {
  13048. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13054. get: function () {
  13055. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13056. },
  13057. enumerable: true,
  13058. configurable: true
  13059. });
  13060. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13061. get: function () {
  13062. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13063. },
  13064. enumerable: true,
  13065. configurable: true
  13066. });
  13067. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13068. get: function () {
  13069. return Camera._RIG_MODE_VR;
  13070. },
  13071. enumerable: true,
  13072. configurable: true
  13073. });
  13074. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13075. get: function () {
  13076. return Camera._RIG_MODE_WEBVR;
  13077. },
  13078. enumerable: true,
  13079. configurable: true
  13080. });
  13081. Camera.prototype.getClassName = function () {
  13082. return "Camera";
  13083. };
  13084. /**
  13085. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13086. */
  13087. Camera.prototype.toString = function (fullDetails) {
  13088. var ret = "Name: " + this.name;
  13089. ret += ", type: " + this.getClassName();
  13090. if (this.animations) {
  13091. for (var i = 0; i < this.animations.length; i++) {
  13092. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13093. }
  13094. }
  13095. if (fullDetails) {
  13096. }
  13097. return ret;
  13098. };
  13099. Object.defineProperty(Camera.prototype, "globalPosition", {
  13100. get: function () {
  13101. return this._globalPosition;
  13102. },
  13103. enumerable: true,
  13104. configurable: true
  13105. });
  13106. Camera.prototype.getActiveMeshes = function () {
  13107. return this._activeMeshes;
  13108. };
  13109. Camera.prototype.isActiveMesh = function (mesh) {
  13110. return (this._activeMeshes.indexOf(mesh) !== -1);
  13111. };
  13112. //Cache
  13113. Camera.prototype._initCache = function () {
  13114. _super.prototype._initCache.call(this);
  13115. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13116. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13117. this._cache.mode = undefined;
  13118. this._cache.minZ = undefined;
  13119. this._cache.maxZ = undefined;
  13120. this._cache.fov = undefined;
  13121. this._cache.fovMode = undefined;
  13122. this._cache.aspectRatio = undefined;
  13123. this._cache.orthoLeft = undefined;
  13124. this._cache.orthoRight = undefined;
  13125. this._cache.orthoBottom = undefined;
  13126. this._cache.orthoTop = undefined;
  13127. this._cache.renderWidth = undefined;
  13128. this._cache.renderHeight = undefined;
  13129. };
  13130. Camera.prototype._updateCache = function (ignoreParentClass) {
  13131. if (!ignoreParentClass) {
  13132. _super.prototype._updateCache.call(this);
  13133. }
  13134. var engine = this.getEngine();
  13135. this._cache.position.copyFrom(this.position);
  13136. this._cache.upVector.copyFrom(this.upVector);
  13137. this._cache.mode = this.mode;
  13138. this._cache.minZ = this.minZ;
  13139. this._cache.maxZ = this.maxZ;
  13140. this._cache.fov = this.fov;
  13141. this._cache.fovMode = this.fovMode;
  13142. this._cache.aspectRatio = engine.getAspectRatio(this);
  13143. this._cache.orthoLeft = this.orthoLeft;
  13144. this._cache.orthoRight = this.orthoRight;
  13145. this._cache.orthoBottom = this.orthoBottom;
  13146. this._cache.orthoTop = this.orthoTop;
  13147. this._cache.renderWidth = engine.getRenderWidth();
  13148. this._cache.renderHeight = engine.getRenderHeight();
  13149. };
  13150. Camera.prototype._updateFromScene = function () {
  13151. this.updateCache();
  13152. this.update();
  13153. };
  13154. // Synchronized
  13155. Camera.prototype._isSynchronized = function () {
  13156. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13157. };
  13158. Camera.prototype._isSynchronizedViewMatrix = function () {
  13159. if (!_super.prototype._isSynchronized.call(this))
  13160. return false;
  13161. return this._cache.position.equals(this.position)
  13162. && this._cache.upVector.equals(this.upVector)
  13163. && this.isSynchronizedWithParent();
  13164. };
  13165. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13166. var check = this._cache.mode === this.mode
  13167. && this._cache.minZ === this.minZ
  13168. && this._cache.maxZ === this.maxZ;
  13169. if (!check) {
  13170. return false;
  13171. }
  13172. var engine = this.getEngine();
  13173. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13174. check = this._cache.fov === this.fov
  13175. && this._cache.fovMode === this.fovMode
  13176. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13177. }
  13178. else {
  13179. check = this._cache.orthoLeft === this.orthoLeft
  13180. && this._cache.orthoRight === this.orthoRight
  13181. && this._cache.orthoBottom === this.orthoBottom
  13182. && this._cache.orthoTop === this.orthoTop
  13183. && this._cache.renderWidth === engine.getRenderWidth()
  13184. && this._cache.renderHeight === engine.getRenderHeight();
  13185. }
  13186. return check;
  13187. };
  13188. // Controls
  13189. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13190. };
  13191. Camera.prototype.detachControl = function (element) {
  13192. };
  13193. Camera.prototype.update = function () {
  13194. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13195. this._updateRigCameras();
  13196. }
  13197. this._checkInputs();
  13198. };
  13199. Camera.prototype._checkInputs = function () {
  13200. };
  13201. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13202. // invalidate framebuffer
  13203. if (this._postProcesses.length > 0) {
  13204. this._postProcesses[0].markTextureDirty();
  13205. }
  13206. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13207. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13208. var cam = this._rigCameras[i];
  13209. var rigPostProcess = cam._rigPostProcess;
  13210. // for VR rig, there does not have to be a post process
  13211. if (rigPostProcess) {
  13212. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13213. if (isPass) {
  13214. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13215. cam.isIntermediate = this._postProcesses.length === 0;
  13216. }
  13217. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13218. rigPostProcess.markTextureDirty();
  13219. }
  13220. else {
  13221. cam._postProcesses = this._postProcesses.slice(0);
  13222. }
  13223. }
  13224. };
  13225. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13226. if (insertAt === void 0) { insertAt = null; }
  13227. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13228. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13229. return 0;
  13230. }
  13231. if (insertAt == null || insertAt < 0) {
  13232. this._postProcesses.push(postProcess);
  13233. }
  13234. else {
  13235. this._postProcesses.splice(insertAt, 0, postProcess);
  13236. }
  13237. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13238. return this._postProcesses.indexOf(postProcess);
  13239. };
  13240. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13241. if (atIndices === void 0) { atIndices = null; }
  13242. var result = [];
  13243. var i;
  13244. var index;
  13245. if (!atIndices) {
  13246. var idx = this._postProcesses.indexOf(postProcess);
  13247. if (idx !== -1) {
  13248. this._postProcesses.splice(idx, 1);
  13249. }
  13250. }
  13251. else {
  13252. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13253. // iterate descending, so can just splice as we go
  13254. for (i = atIndices.length - 1; i >= 0; i--) {
  13255. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13256. result.push(i);
  13257. continue;
  13258. }
  13259. this._postProcesses.splice(index, 1);
  13260. }
  13261. }
  13262. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13263. return result;
  13264. };
  13265. Camera.prototype.getWorldMatrix = function () {
  13266. if (!this._worldMatrix) {
  13267. this._worldMatrix = BABYLON.Matrix.Identity();
  13268. }
  13269. var viewMatrix = this.getViewMatrix();
  13270. viewMatrix.invertToRef(this._worldMatrix);
  13271. return this._worldMatrix;
  13272. };
  13273. Camera.prototype._getViewMatrix = function () {
  13274. return BABYLON.Matrix.Identity();
  13275. };
  13276. Camera.prototype.getViewMatrix = function (force) {
  13277. this._computedViewMatrix = this._computeViewMatrix(force);
  13278. if (!force && this._isSynchronizedViewMatrix()) {
  13279. return this._computedViewMatrix;
  13280. }
  13281. this._refreshFrustumPlanes = true;
  13282. if (!this.parent || !this.parent.getWorldMatrix) {
  13283. this._globalPosition.copyFrom(this.position);
  13284. }
  13285. else {
  13286. if (!this._worldMatrix) {
  13287. this._worldMatrix = BABYLON.Matrix.Identity();
  13288. }
  13289. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13290. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13291. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13292. this._computedViewMatrix.invert();
  13293. this._markSyncedWithParent();
  13294. }
  13295. this._currentRenderId = this.getScene().getRenderId();
  13296. return this._computedViewMatrix;
  13297. };
  13298. Camera.prototype._computeViewMatrix = function (force) {
  13299. if (!force && this._isSynchronizedViewMatrix()) {
  13300. return this._computedViewMatrix;
  13301. }
  13302. this._computedViewMatrix = this._getViewMatrix();
  13303. this._currentRenderId = this.getScene().getRenderId();
  13304. return this._computedViewMatrix;
  13305. };
  13306. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13307. this._doNotComputeProjectionMatrix = true;
  13308. if (projection !== undefined) {
  13309. this._projectionMatrix = projection;
  13310. }
  13311. };
  13312. ;
  13313. Camera.prototype.unfreezeProjectionMatrix = function () {
  13314. this._doNotComputeProjectionMatrix = false;
  13315. };
  13316. ;
  13317. Camera.prototype.getProjectionMatrix = function (force) {
  13318. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13319. return this._projectionMatrix;
  13320. }
  13321. this._refreshFrustumPlanes = true;
  13322. var engine = this.getEngine();
  13323. var scene = this.getScene();
  13324. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13325. if (this.minZ <= 0) {
  13326. this.minZ = 0.1;
  13327. }
  13328. if (scene.useRightHandedSystem) {
  13329. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13330. }
  13331. else {
  13332. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13333. }
  13334. return this._projectionMatrix;
  13335. }
  13336. var halfWidth = engine.getRenderWidth() / 2.0;
  13337. var halfHeight = engine.getRenderHeight() / 2.0;
  13338. if (scene.useRightHandedSystem) {
  13339. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13340. }
  13341. else {
  13342. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13343. }
  13344. return this._projectionMatrix;
  13345. };
  13346. Camera.prototype.getTranformationMatrix = function () {
  13347. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13348. return this._transformMatrix;
  13349. };
  13350. Camera.prototype.updateFrustumPlanes = function () {
  13351. if (!this._refreshFrustumPlanes) {
  13352. return;
  13353. }
  13354. this.getTranformationMatrix();
  13355. if (!this._frustumPlanes) {
  13356. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13357. }
  13358. else {
  13359. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13360. }
  13361. this._refreshFrustumPlanes = false;
  13362. };
  13363. Camera.prototype.isInFrustum = function (target) {
  13364. this.updateFrustumPlanes();
  13365. return target.isInFrustum(this._frustumPlanes);
  13366. };
  13367. Camera.prototype.isCompletelyInFrustum = function (target) {
  13368. this.updateFrustumPlanes();
  13369. return target.isCompletelyInFrustum(this._frustumPlanes);
  13370. };
  13371. Camera.prototype.dispose = function () {
  13372. // Animations
  13373. this.getScene().stopAnimation(this);
  13374. // Remove from scene
  13375. this.getScene().removeCamera(this);
  13376. while (this._rigCameras.length > 0) {
  13377. this._rigCameras.pop().dispose();
  13378. }
  13379. // Postprocesses
  13380. for (var i = 0; i < this._postProcesses.length; ++i) {
  13381. this._postProcesses[i].dispose(this);
  13382. }
  13383. _super.prototype.dispose.call(this);
  13384. };
  13385. // ---- Camera rigs section ----
  13386. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13387. while (this._rigCameras.length > 0) {
  13388. this._rigCameras.pop().dispose();
  13389. }
  13390. this.cameraRigMode = mode;
  13391. this._cameraRigParams = {};
  13392. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13393. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13394. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13395. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13396. // create the rig cameras, unless none
  13397. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13398. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13399. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13400. }
  13401. switch (this.cameraRigMode) {
  13402. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13403. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13404. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13405. break;
  13406. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13407. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13408. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13409. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13410. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13411. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13412. break;
  13413. case Camera.RIG_MODE_VR:
  13414. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13415. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13416. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13417. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13418. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13419. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13420. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13421. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13422. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13423. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13424. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13425. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13426. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13427. if (metrics.compensateDistortion) {
  13428. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13429. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13430. }
  13431. break;
  13432. case Camera.RIG_MODE_WEBVR:
  13433. if (rigParams.vrDisplay) {
  13434. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13435. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13436. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13437. this._rigCameras[0].setCameraRigParameter("left", true);
  13438. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13439. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13440. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13441. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13442. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13443. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13444. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13445. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13446. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13447. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13448. }
  13449. break;
  13450. }
  13451. this._cascadePostProcessesToRigCams();
  13452. this.
  13453. update();
  13454. };
  13455. Camera.prototype._getVRProjectionMatrix = function () {
  13456. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13457. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13458. return this._projectionMatrix;
  13459. };
  13460. Camera.prototype._getWebVRProjectionMatrix = function () {
  13461. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13462. //babylon compatible matrix
  13463. [8, 9, 10, 11].forEach(function (num) {
  13464. projectionArray[num] *= -1;
  13465. });
  13466. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13467. return this._projectionMatrix;
  13468. };
  13469. //Can be used, but we'll use the free camera's view matrix calculation
  13470. Camera.prototype._getWebVRViewMatrix = function () {
  13471. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13472. //babylon compatible matrix
  13473. [8, 9, 10, 11].forEach(function (num) {
  13474. projectionArray[num] *= -1;
  13475. });
  13476. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13477. return this._webvrViewMatrix;
  13478. };
  13479. Camera.prototype.setCameraRigParameter = function (name, value) {
  13480. if (!this._cameraRigParams) {
  13481. this._cameraRigParams = {};
  13482. }
  13483. this._cameraRigParams[name] = value;
  13484. //provisionnally:
  13485. if (name === "interaxialDistance") {
  13486. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13487. }
  13488. };
  13489. /**
  13490. * needs to be overridden by children so sub has required properties to be copied
  13491. */
  13492. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13493. return null;
  13494. };
  13495. /**
  13496. * May need to be overridden by children
  13497. */
  13498. Camera.prototype._updateRigCameras = function () {
  13499. for (var i = 0; i < this._rigCameras.length; i++) {
  13500. this._rigCameras[i].minZ = this.minZ;
  13501. this._rigCameras[i].maxZ = this.maxZ;
  13502. this._rigCameras[i].fov = this.fov;
  13503. }
  13504. // only update viewport when ANAGLYPH
  13505. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13506. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13507. }
  13508. };
  13509. Camera.prototype._setupInputs = function () {
  13510. };
  13511. Camera.prototype.serialize = function () {
  13512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13513. // Type
  13514. serializationObject.type = this.getClassName();
  13515. // Parent
  13516. if (this.parent) {
  13517. serializationObject.parentId = this.parent.id;
  13518. }
  13519. if (this.inputs) {
  13520. this.inputs.serialize(serializationObject);
  13521. }
  13522. // Animations
  13523. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13524. serializationObject.ranges = this.serializeAnimationRanges();
  13525. return serializationObject;
  13526. };
  13527. Camera.prototype.clone = function (name) {
  13528. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13529. };
  13530. Camera.prototype.getDirection = function (localAxis) {
  13531. var result = BABYLON.Vector3.Zero();
  13532. this.getDirectionToRef(localAxis, result);
  13533. return result;
  13534. };
  13535. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13536. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13537. };
  13538. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13539. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13540. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13541. switch (type) {
  13542. case "ArcRotateCamera":
  13543. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13544. case "DeviceOrientationCamera":
  13545. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13546. case "FollowCamera":
  13547. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13548. case "ArcFollowCamera":
  13549. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13550. case "GamepadCamera":
  13551. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13552. case "TouchCamera":
  13553. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13554. case "VirtualJoysticksCamera":
  13555. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13556. case "WebVRFreeCamera":
  13557. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13558. case "VRDeviceOrientationFreeCamera":
  13559. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13560. case "AnaglyphArcRotateCamera":
  13561. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13562. case "AnaglyphFreeCamera":
  13563. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13564. case "AnaglyphGamepadCamera":
  13565. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13566. case "AnaglyphUniversalCamera":
  13567. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13568. case "StereoscopicArcRotateCamera":
  13569. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13570. case "StereoscopicFreeCamera":
  13571. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13572. case "StereoscopicGamepadCamera":
  13573. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13574. case "StereoscopicUniversalCamera":
  13575. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13576. case "FreeCamera":
  13577. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13578. default:
  13579. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13580. }
  13581. };
  13582. Camera.Parse = function (parsedCamera, scene) {
  13583. var type = parsedCamera.type;
  13584. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13585. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13586. // Parent
  13587. if (parsedCamera.parentId) {
  13588. camera._waitingParentId = parsedCamera.parentId;
  13589. }
  13590. //If camera has an input manager, let it parse inputs settings
  13591. if (camera.inputs) {
  13592. camera.inputs.parse(parsedCamera);
  13593. camera._setupInputs();
  13594. }
  13595. // Target
  13596. if (parsedCamera.target) {
  13597. if (camera.setTarget) {
  13598. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13599. }
  13600. }
  13601. // Apply 3d rig, when found
  13602. if (parsedCamera.cameraRigMode) {
  13603. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13604. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13605. }
  13606. // Animations
  13607. if (parsedCamera.animations) {
  13608. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13609. var parsedAnimation = parsedCamera.animations[animationIndex];
  13610. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13611. }
  13612. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13613. }
  13614. if (parsedCamera.autoAnimate) {
  13615. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13616. }
  13617. return camera;
  13618. };
  13619. // Statics
  13620. Camera._PERSPECTIVE_CAMERA = 0;
  13621. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13622. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13623. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13624. Camera._RIG_MODE_NONE = 0;
  13625. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13626. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13627. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13628. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13629. Camera._RIG_MODE_VR = 20;
  13630. Camera._RIG_MODE_WEBVR = 21;
  13631. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13632. __decorate([
  13633. BABYLON.serializeAsVector3()
  13634. ], Camera.prototype, "position", void 0);
  13635. __decorate([
  13636. BABYLON.serializeAsVector3()
  13637. ], Camera.prototype, "upVector", void 0);
  13638. __decorate([
  13639. BABYLON.serialize()
  13640. ], Camera.prototype, "orthoLeft", void 0);
  13641. __decorate([
  13642. BABYLON.serialize()
  13643. ], Camera.prototype, "orthoRight", void 0);
  13644. __decorate([
  13645. BABYLON.serialize()
  13646. ], Camera.prototype, "orthoBottom", void 0);
  13647. __decorate([
  13648. BABYLON.serialize()
  13649. ], Camera.prototype, "orthoTop", void 0);
  13650. __decorate([
  13651. BABYLON.serialize()
  13652. ], Camera.prototype, "fov", void 0);
  13653. __decorate([
  13654. BABYLON.serialize()
  13655. ], Camera.prototype, "minZ", void 0);
  13656. __decorate([
  13657. BABYLON.serialize()
  13658. ], Camera.prototype, "maxZ", void 0);
  13659. __decorate([
  13660. BABYLON.serialize()
  13661. ], Camera.prototype, "inertia", void 0);
  13662. __decorate([
  13663. BABYLON.serialize()
  13664. ], Camera.prototype, "mode", void 0);
  13665. __decorate([
  13666. BABYLON.serialize()
  13667. ], Camera.prototype, "layerMask", void 0);
  13668. __decorate([
  13669. BABYLON.serialize()
  13670. ], Camera.prototype, "fovMode", void 0);
  13671. __decorate([
  13672. BABYLON.serialize()
  13673. ], Camera.prototype, "cameraRigMode", void 0);
  13674. __decorate([
  13675. BABYLON.serialize()
  13676. ], Camera.prototype, "interaxialDistance", void 0);
  13677. __decorate([
  13678. BABYLON.serialize()
  13679. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13680. return Camera;
  13681. }(BABYLON.Node));
  13682. BABYLON.Camera = Camera;
  13683. })(BABYLON || (BABYLON = {}));
  13684. //# sourceMappingURL=babylon.camera.js.map
  13685. var BABYLON;
  13686. (function (BABYLON) {
  13687. BABYLON.CameraInputTypes = {};
  13688. var CameraInputsManager = (function () {
  13689. function CameraInputsManager(camera) {
  13690. this.attached = {};
  13691. this.camera = camera;
  13692. this.checkInputs = function () { };
  13693. }
  13694. CameraInputsManager.prototype.add = function (input) {
  13695. var type = input.getSimpleName();
  13696. if (this.attached[type]) {
  13697. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13698. return;
  13699. }
  13700. this.attached[type] = input;
  13701. input.camera = this.camera;
  13702. //for checkInputs, we are dynamically creating a function
  13703. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13704. if (input.checkInputs) {
  13705. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13706. }
  13707. if (this.attachedElement) {
  13708. input.attachControl(this.attachedElement);
  13709. }
  13710. };
  13711. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13712. for (var cam in this.attached) {
  13713. var input = this.attached[cam];
  13714. if (input === inputToRemove) {
  13715. input.detachControl(this.attachedElement);
  13716. delete this.attached[cam];
  13717. this.rebuildInputCheck();
  13718. }
  13719. }
  13720. };
  13721. CameraInputsManager.prototype.removeByType = function (inputType) {
  13722. for (var cam in this.attached) {
  13723. var input = this.attached[cam];
  13724. if (input.getTypeName() === inputType) {
  13725. input.detachControl(this.attachedElement);
  13726. delete this.attached[cam];
  13727. this.rebuildInputCheck();
  13728. }
  13729. }
  13730. };
  13731. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13732. var current = this.checkInputs;
  13733. return function () {
  13734. current();
  13735. fn();
  13736. };
  13737. };
  13738. CameraInputsManager.prototype.attachInput = function (input) {
  13739. input.attachControl(this.attachedElement, this.noPreventDefault);
  13740. };
  13741. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13742. if (this.attachedElement) {
  13743. return;
  13744. }
  13745. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13746. this.attachedElement = element;
  13747. this.noPreventDefault = noPreventDefault;
  13748. for (var cam in this.attached) {
  13749. var input = this.attached[cam];
  13750. this.attached[cam].attachControl(element, noPreventDefault);
  13751. }
  13752. };
  13753. CameraInputsManager.prototype.detachElement = function (element) {
  13754. if (this.attachedElement !== element) {
  13755. return;
  13756. }
  13757. for (var cam in this.attached) {
  13758. var input = this.attached[cam];
  13759. this.attached[cam].detachControl(element);
  13760. }
  13761. this.attachedElement = null;
  13762. };
  13763. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13764. this.checkInputs = function () { };
  13765. for (var cam in this.attached) {
  13766. var input = this.attached[cam];
  13767. if (input.checkInputs) {
  13768. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13769. }
  13770. }
  13771. };
  13772. CameraInputsManager.prototype.clear = function () {
  13773. if (this.attachedElement) {
  13774. this.detachElement(this.attachedElement);
  13775. }
  13776. this.attached = {};
  13777. this.attachedElement = null;
  13778. this.checkInputs = function () { };
  13779. };
  13780. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13781. var inputs = {};
  13782. for (var cam in this.attached) {
  13783. var input = this.attached[cam];
  13784. var res = BABYLON.SerializationHelper.Serialize(input);
  13785. inputs[input.getTypeName()] = res;
  13786. }
  13787. serializedCamera.inputsmgr = inputs;
  13788. };
  13789. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13790. var parsedInputs = parsedCamera.inputsmgr;
  13791. if (parsedInputs) {
  13792. this.clear();
  13793. for (var n in parsedInputs) {
  13794. var construct = BABYLON.CameraInputTypes[n];
  13795. if (construct) {
  13796. var parsedinput = parsedInputs[n];
  13797. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13798. this.add(input);
  13799. }
  13800. }
  13801. }
  13802. else {
  13803. //2016-03-08 this part is for managing backward compatibility
  13804. for (var n in this.attached) {
  13805. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13806. if (construct) {
  13807. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13808. this.remove(this.attached[n]);
  13809. this.add(input);
  13810. }
  13811. }
  13812. }
  13813. };
  13814. return CameraInputsManager;
  13815. }());
  13816. BABYLON.CameraInputsManager = CameraInputsManager;
  13817. })(BABYLON || (BABYLON = {}));
  13818. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13819. var BABYLON;
  13820. (function (BABYLON) {
  13821. var FreeCameraMouseInput = (function () {
  13822. function FreeCameraMouseInput(touchEnabled) {
  13823. if (touchEnabled === void 0) { touchEnabled = true; }
  13824. this.touchEnabled = touchEnabled;
  13825. this.buttons = [0, 1, 2];
  13826. this.angularSensibility = 2000.0;
  13827. }
  13828. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13829. var _this = this;
  13830. var engine = this.camera.getEngine();
  13831. if (!this._pointerInput) {
  13832. this._pointerInput = function (p, s) {
  13833. var evt = p.event;
  13834. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13835. return;
  13836. }
  13837. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13838. return;
  13839. }
  13840. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13841. try {
  13842. evt.srcElement.setPointerCapture(evt.pointerId);
  13843. }
  13844. catch (e) {
  13845. }
  13846. _this.previousPosition = {
  13847. x: evt.clientX,
  13848. y: evt.clientY
  13849. };
  13850. if (!noPreventDefault) {
  13851. evt.preventDefault();
  13852. element.focus();
  13853. }
  13854. }
  13855. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13856. try {
  13857. evt.srcElement.releasePointerCapture(evt.pointerId);
  13858. }
  13859. catch (e) {
  13860. }
  13861. _this.previousPosition = null;
  13862. if (!noPreventDefault) {
  13863. evt.preventDefault();
  13864. }
  13865. }
  13866. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13867. if (!_this.previousPosition || engine.isPointerLock) {
  13868. return;
  13869. }
  13870. var offsetX = evt.clientX - _this.previousPosition.x;
  13871. var offsetY = evt.clientY - _this.previousPosition.y;
  13872. if (_this.camera.getScene().useRightHandedSystem) {
  13873. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13874. }
  13875. else {
  13876. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13877. }
  13878. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13879. _this.previousPosition = {
  13880. x: evt.clientX,
  13881. y: evt.clientY
  13882. };
  13883. if (!noPreventDefault) {
  13884. evt.preventDefault();
  13885. }
  13886. }
  13887. };
  13888. }
  13889. this._onMouseMove = function (evt) {
  13890. if (!engine.isPointerLock) {
  13891. return;
  13892. }
  13893. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13894. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13895. if (_this.camera.getScene().useRightHandedSystem) {
  13896. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13897. }
  13898. else {
  13899. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13900. }
  13901. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13902. _this.previousPosition = null;
  13903. if (!noPreventDefault) {
  13904. evt.preventDefault();
  13905. }
  13906. };
  13907. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13908. element.addEventListener("mousemove", this._onMouseMove, false);
  13909. };
  13910. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13911. if (this._observer && element) {
  13912. this.camera.getScene().onPointerObservable.remove(this._observer);
  13913. element.removeEventListener("mousemove", this._onMouseMove);
  13914. this._observer = null;
  13915. this._onMouseMove = null;
  13916. this.previousPosition = null;
  13917. }
  13918. };
  13919. FreeCameraMouseInput.prototype.getTypeName = function () {
  13920. return "FreeCameraMouseInput";
  13921. };
  13922. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13923. return "mouse";
  13924. };
  13925. __decorate([
  13926. BABYLON.serialize()
  13927. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13928. __decorate([
  13929. BABYLON.serialize()
  13930. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13931. return FreeCameraMouseInput;
  13932. }());
  13933. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13934. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13935. })(BABYLON || (BABYLON = {}));
  13936. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13937. var BABYLON;
  13938. (function (BABYLON) {
  13939. var FreeCameraKeyboardMoveInput = (function () {
  13940. function FreeCameraKeyboardMoveInput() {
  13941. this._keys = [];
  13942. this.keysUp = [38];
  13943. this.keysDown = [40];
  13944. this.keysLeft = [37];
  13945. this.keysRight = [39];
  13946. }
  13947. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13948. var _this = this;
  13949. if (!this._onKeyDown) {
  13950. element.tabIndex = 1;
  13951. this._onKeyDown = function (evt) {
  13952. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13953. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13954. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13955. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13956. var index = _this._keys.indexOf(evt.keyCode);
  13957. if (index === -1) {
  13958. _this._keys.push(evt.keyCode);
  13959. }
  13960. if (!noPreventDefault) {
  13961. evt.preventDefault();
  13962. }
  13963. }
  13964. };
  13965. this._onKeyUp = function (evt) {
  13966. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13967. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13968. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13969. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13970. var index = _this._keys.indexOf(evt.keyCode);
  13971. if (index >= 0) {
  13972. _this._keys.splice(index, 1);
  13973. }
  13974. if (!noPreventDefault) {
  13975. evt.preventDefault();
  13976. }
  13977. }
  13978. };
  13979. element.addEventListener("keydown", this._onKeyDown, false);
  13980. element.addEventListener("keyup", this._onKeyUp, false);
  13981. BABYLON.Tools.RegisterTopRootEvents([
  13982. { name: "blur", handler: this._onLostFocus }
  13983. ]);
  13984. }
  13985. };
  13986. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13987. if (this._onKeyDown) {
  13988. element.removeEventListener("keydown", this._onKeyDown);
  13989. element.removeEventListener("keyup", this._onKeyUp);
  13990. BABYLON.Tools.UnregisterTopRootEvents([
  13991. { name: "blur", handler: this._onLostFocus }
  13992. ]);
  13993. this._keys = [];
  13994. this._onKeyDown = null;
  13995. this._onKeyUp = null;
  13996. }
  13997. };
  13998. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13999. if (this._onKeyDown) {
  14000. var camera = this.camera;
  14001. // Keyboard
  14002. for (var index = 0; index < this._keys.length; index++) {
  14003. var keyCode = this._keys[index];
  14004. var speed = camera._computeLocalCameraSpeed();
  14005. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14006. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14007. }
  14008. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14009. camera._localDirection.copyFromFloats(0, 0, speed);
  14010. }
  14011. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14012. camera._localDirection.copyFromFloats(speed, 0, 0);
  14013. }
  14014. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14015. camera._localDirection.copyFromFloats(0, 0, -speed);
  14016. }
  14017. if (camera.getScene().useRightHandedSystem) {
  14018. camera._localDirection.z *= -1;
  14019. }
  14020. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14021. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14022. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14023. }
  14024. }
  14025. };
  14026. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14027. return "FreeCameraKeyboardMoveInput";
  14028. };
  14029. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14030. this._keys = [];
  14031. };
  14032. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14033. return "keyboard";
  14034. };
  14035. __decorate([
  14036. BABYLON.serialize()
  14037. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14038. __decorate([
  14039. BABYLON.serialize()
  14040. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14041. __decorate([
  14042. BABYLON.serialize()
  14043. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14044. __decorate([
  14045. BABYLON.serialize()
  14046. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14047. return FreeCameraKeyboardMoveInput;
  14048. }());
  14049. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14050. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14051. })(BABYLON || (BABYLON = {}));
  14052. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14053. var BABYLON;
  14054. (function (BABYLON) {
  14055. var FreeCameraTouchInput = (function () {
  14056. function FreeCameraTouchInput() {
  14057. this._offsetX = null;
  14058. this._offsetY = null;
  14059. this._pointerCount = 0;
  14060. this._pointerPressed = [];
  14061. this.touchAngularSensibility = 200000.0;
  14062. this.touchMoveSensibility = 250.0;
  14063. }
  14064. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14065. var _this = this;
  14066. var previousPosition;
  14067. if (this._pointerInput === undefined) {
  14068. this._onLostFocus = function (evt) {
  14069. _this._offsetX = null;
  14070. _this._offsetY = null;
  14071. };
  14072. this._pointerInput = function (p, s) {
  14073. var evt = p.event;
  14074. if (evt.pointerType === "mouse") {
  14075. return;
  14076. }
  14077. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14078. if (!noPreventDefault) {
  14079. evt.preventDefault();
  14080. }
  14081. _this._pointerPressed.push(evt.pointerId);
  14082. if (_this._pointerPressed.length !== 1) {
  14083. return;
  14084. }
  14085. previousPosition = {
  14086. x: evt.clientX,
  14087. y: evt.clientY
  14088. };
  14089. }
  14090. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14091. if (!noPreventDefault) {
  14092. evt.preventDefault();
  14093. }
  14094. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14095. if (index === -1) {
  14096. return;
  14097. }
  14098. _this._pointerPressed.splice(index, 1);
  14099. if (index != 0) {
  14100. return;
  14101. }
  14102. previousPosition = null;
  14103. _this._offsetX = null;
  14104. _this._offsetY = null;
  14105. }
  14106. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14107. if (!noPreventDefault) {
  14108. evt.preventDefault();
  14109. }
  14110. if (!previousPosition) {
  14111. return;
  14112. }
  14113. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14114. if (index != 0) {
  14115. return;
  14116. }
  14117. _this._offsetX = evt.clientX - previousPosition.x;
  14118. _this._offsetY = -(evt.clientY - previousPosition.y);
  14119. }
  14120. };
  14121. }
  14122. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14123. element.addEventListener("blur", this._onLostFocus);
  14124. };
  14125. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14126. if (this._pointerInput && element) {
  14127. this.camera.getScene().onPointerObservable.remove(this._observer);
  14128. this._observer = null;
  14129. element.removeEventListener("blur", this._onLostFocus);
  14130. this._onLostFocus = null;
  14131. this._pointerPressed = [];
  14132. this._offsetX = null;
  14133. this._offsetY = null;
  14134. this._pointerCount = 0;
  14135. }
  14136. };
  14137. FreeCameraTouchInput.prototype.checkInputs = function () {
  14138. if (this._offsetX) {
  14139. var camera = this.camera;
  14140. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14141. if (this._pointerPressed.length > 1) {
  14142. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14143. }
  14144. else {
  14145. var speed = camera._computeLocalCameraSpeed();
  14146. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14147. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14148. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14149. }
  14150. }
  14151. };
  14152. FreeCameraTouchInput.prototype.getTypeName = function () {
  14153. return "FreeCameraTouchInput";
  14154. };
  14155. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14156. return "touch";
  14157. };
  14158. __decorate([
  14159. BABYLON.serialize()
  14160. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14161. __decorate([
  14162. BABYLON.serialize()
  14163. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14164. return FreeCameraTouchInput;
  14165. }());
  14166. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14167. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14168. })(BABYLON || (BABYLON = {}));
  14169. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14170. var BABYLON;
  14171. (function (BABYLON) {
  14172. var FreeCameraDeviceOrientationInput = (function () {
  14173. function FreeCameraDeviceOrientationInput() {
  14174. var _this = this;
  14175. this._screenOrientationAngle = 0;
  14176. this._screenQuaternion = new BABYLON.Quaternion();
  14177. this._alpha = 0;
  14178. this._beta = 0;
  14179. this._gamma = 0;
  14180. this._orientationChanged = function () {
  14181. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14182. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14183. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14184. };
  14185. this._deviceOrientation = function (evt) {
  14186. _this._alpha = evt.alpha;
  14187. _this._beta = evt.beta;
  14188. _this._gamma = evt.gamma;
  14189. };
  14190. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14191. this._orientationChanged();
  14192. }
  14193. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14194. get: function () {
  14195. return this._camera;
  14196. },
  14197. set: function (camera) {
  14198. this._camera = camera;
  14199. if (!this._camera.rotationQuaternion)
  14200. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14201. },
  14202. enumerable: true,
  14203. configurable: true
  14204. });
  14205. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14206. window.addEventListener("orientationchange", this._orientationChanged);
  14207. window.addEventListener("deviceorientation", this._deviceOrientation);
  14208. //In certain cases, the attach control is called AFTER orientation was changed,
  14209. //So this is needed.
  14210. this._orientationChanged();
  14211. };
  14212. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14213. window.removeEventListener("orientationchange", this._orientationChanged);
  14214. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14215. };
  14216. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14217. //if no device orientation provided, don't update the rotation.
  14218. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14219. if (!this._alpha)
  14220. return;
  14221. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14222. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14223. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14224. //Mirror on XY Plane
  14225. this._camera.rotationQuaternion.z *= -1;
  14226. this._camera.rotationQuaternion.w *= -1;
  14227. };
  14228. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14229. return "FreeCameraDeviceOrientationInput";
  14230. };
  14231. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14232. return "deviceOrientation";
  14233. };
  14234. return FreeCameraDeviceOrientationInput;
  14235. }());
  14236. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14237. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14238. })(BABYLON || (BABYLON = {}));
  14239. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14240. var BABYLON;
  14241. (function (BABYLON) {
  14242. var FreeCameraGamepadInput = (function () {
  14243. function FreeCameraGamepadInput() {
  14244. this.gamepadAngularSensibility = 200;
  14245. this.gamepadMoveSensibility = 40;
  14246. }
  14247. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14248. var _this = this;
  14249. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14250. };
  14251. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14252. if (this._gamepads) {
  14253. this._gamepads.dispose();
  14254. }
  14255. this.gamepad = null;
  14256. };
  14257. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14258. if (this.gamepad) {
  14259. var camera = this.camera;
  14260. var LSValues = this.gamepad.leftStick;
  14261. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14262. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14263. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14264. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14265. var RSValues = this.gamepad.rightStick;
  14266. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14267. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14268. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14269. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14270. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14271. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14272. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14273. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14274. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14275. }
  14276. };
  14277. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14278. // Only the first gamepad can control the camera
  14279. if (gamepad.index === 0) {
  14280. this.gamepad = gamepad;
  14281. }
  14282. };
  14283. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14284. return "FreeCameraGamepadInput";
  14285. };
  14286. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14287. return "gamepad";
  14288. };
  14289. __decorate([
  14290. BABYLON.serialize()
  14291. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14292. __decorate([
  14293. BABYLON.serialize()
  14294. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14295. return FreeCameraGamepadInput;
  14296. }());
  14297. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14298. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14299. })(BABYLON || (BABYLON = {}));
  14300. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14301. var BABYLON;
  14302. (function (BABYLON) {
  14303. var ArcRotateCameraKeyboardMoveInput = (function () {
  14304. function ArcRotateCameraKeyboardMoveInput() {
  14305. this._keys = [];
  14306. this.keysUp = [38];
  14307. this.keysDown = [40];
  14308. this.keysLeft = [37];
  14309. this.keysRight = [39];
  14310. }
  14311. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14312. var _this = this;
  14313. element.tabIndex = 1;
  14314. this._onKeyDown = function (evt) {
  14315. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14316. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14317. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14318. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14319. var index = _this._keys.indexOf(evt.keyCode);
  14320. if (index === -1) {
  14321. _this._keys.push(evt.keyCode);
  14322. }
  14323. if (evt.preventDefault) {
  14324. if (!noPreventDefault) {
  14325. evt.preventDefault();
  14326. }
  14327. }
  14328. }
  14329. };
  14330. this._onKeyUp = function (evt) {
  14331. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14332. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14333. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14334. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14335. var index = _this._keys.indexOf(evt.keyCode);
  14336. if (index >= 0) {
  14337. _this._keys.splice(index, 1);
  14338. }
  14339. if (evt.preventDefault) {
  14340. if (!noPreventDefault) {
  14341. evt.preventDefault();
  14342. }
  14343. }
  14344. }
  14345. };
  14346. this._onLostFocus = function () {
  14347. _this._keys = [];
  14348. };
  14349. element.addEventListener("keydown", this._onKeyDown, false);
  14350. element.addEventListener("keyup", this._onKeyUp, false);
  14351. BABYLON.Tools.RegisterTopRootEvents([
  14352. { name: "blur", handler: this._onLostFocus }
  14353. ]);
  14354. };
  14355. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14356. if (element) {
  14357. element.removeEventListener("keydown", this._onKeyDown);
  14358. element.removeEventListener("keyup", this._onKeyUp);
  14359. }
  14360. BABYLON.Tools.UnregisterTopRootEvents([
  14361. { name: "blur", handler: this._onLostFocus }
  14362. ]);
  14363. this._keys = [];
  14364. this._onKeyDown = null;
  14365. this._onKeyUp = null;
  14366. this._onLostFocus = null;
  14367. };
  14368. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14369. if (this._onKeyDown) {
  14370. var camera = this.camera;
  14371. for (var index = 0; index < this._keys.length; index++) {
  14372. var keyCode = this._keys[index];
  14373. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14374. camera.inertialAlphaOffset -= 0.01;
  14375. }
  14376. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14377. camera.inertialBetaOffset -= 0.01;
  14378. }
  14379. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14380. camera.inertialAlphaOffset += 0.01;
  14381. }
  14382. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14383. camera.inertialBetaOffset += 0.01;
  14384. }
  14385. }
  14386. }
  14387. };
  14388. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14389. return "ArcRotateCameraKeyboardMoveInput";
  14390. };
  14391. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14392. return "keyboard";
  14393. };
  14394. __decorate([
  14395. BABYLON.serialize()
  14396. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14397. __decorate([
  14398. BABYLON.serialize()
  14399. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14400. __decorate([
  14401. BABYLON.serialize()
  14402. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14403. __decorate([
  14404. BABYLON.serialize()
  14405. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14406. return ArcRotateCameraKeyboardMoveInput;
  14407. }());
  14408. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14409. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14410. })(BABYLON || (BABYLON = {}));
  14411. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14412. var BABYLON;
  14413. (function (BABYLON) {
  14414. var ArcRotateCameraMouseWheelInput = (function () {
  14415. function ArcRotateCameraMouseWheelInput() {
  14416. this.wheelPrecision = 3.0;
  14417. }
  14418. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14419. var _this = this;
  14420. this._wheel = function (p, s) {
  14421. //sanity check - this should be a PointerWheel event.
  14422. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14423. return;
  14424. var event = p.event;
  14425. var delta = 0;
  14426. if (event.wheelDelta) {
  14427. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14428. }
  14429. else if (event.detail) {
  14430. delta = -event.detail / _this.wheelPrecision;
  14431. }
  14432. if (delta)
  14433. _this.camera.inertialRadiusOffset += delta;
  14434. if (event.preventDefault) {
  14435. if (!noPreventDefault) {
  14436. event.preventDefault();
  14437. }
  14438. }
  14439. };
  14440. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14441. };
  14442. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14443. if (this._observer && element) {
  14444. this.camera.getScene().onPointerObservable.remove(this._observer);
  14445. this._observer = null;
  14446. this._wheel = null;
  14447. }
  14448. };
  14449. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14450. return "ArcRotateCameraMouseWheelInput";
  14451. };
  14452. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14453. return "mousewheel";
  14454. };
  14455. __decorate([
  14456. BABYLON.serialize()
  14457. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14458. return ArcRotateCameraMouseWheelInput;
  14459. }());
  14460. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14461. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14462. })(BABYLON || (BABYLON = {}));
  14463. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14464. var BABYLON;
  14465. (function (BABYLON) {
  14466. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14467. var ArcRotateCameraPointersInput = (function () {
  14468. function ArcRotateCameraPointersInput() {
  14469. this.buttons = [0, 1, 2];
  14470. this.angularSensibilityX = 1000.0;
  14471. this.angularSensibilityY = 1000.0;
  14472. this.pinchPrecision = 6.0;
  14473. this.panningSensibility = 50.0;
  14474. this._isPanClick = false;
  14475. this.pinchInwards = true;
  14476. }
  14477. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14478. var _this = this;
  14479. var engine = this.camera.getEngine();
  14480. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14481. var pointA, pointB;
  14482. var previousPinchDistance = 0;
  14483. this._pointerInput = function (p, s) {
  14484. var evt = p.event;
  14485. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14486. return;
  14487. }
  14488. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14489. try {
  14490. evt.srcElement.setPointerCapture(evt.pointerId);
  14491. }
  14492. catch (e) {
  14493. }
  14494. // Manage panning with pan button click
  14495. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14496. // manage pointers
  14497. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14498. if (pointA === undefined) {
  14499. pointA = cacheSoloPointer;
  14500. }
  14501. else if (pointB === undefined) {
  14502. pointB = cacheSoloPointer;
  14503. }
  14504. if (!noPreventDefault) {
  14505. evt.preventDefault();
  14506. element.focus();
  14507. }
  14508. }
  14509. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14510. try {
  14511. evt.srcElement.releasePointerCapture(evt.pointerId);
  14512. }
  14513. catch (e) {
  14514. }
  14515. cacheSoloPointer = null;
  14516. previousPinchDistance = 0;
  14517. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14518. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14519. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14520. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14521. pointA = pointB = undefined;
  14522. if (!noPreventDefault) {
  14523. evt.preventDefault();
  14524. }
  14525. }
  14526. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14527. if (!noPreventDefault) {
  14528. evt.preventDefault();
  14529. }
  14530. // One button down
  14531. if (pointA && pointB === undefined) {
  14532. if (_this.panningSensibility !== 0 &&
  14533. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14534. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14535. _this.camera
  14536. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14537. _this.camera
  14538. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14539. }
  14540. else {
  14541. var offsetX = evt.clientX - cacheSoloPointer.x;
  14542. var offsetY = evt.clientY - cacheSoloPointer.y;
  14543. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14544. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14545. }
  14546. cacheSoloPointer.x = evt.clientX;
  14547. cacheSoloPointer.y = evt.clientY;
  14548. }
  14549. else if (pointA && pointB) {
  14550. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14551. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14552. ed.x = evt.clientX;
  14553. ed.y = evt.clientY;
  14554. var direction = _this.pinchInwards ? 1 : -1;
  14555. var distX = pointA.x - pointB.x;
  14556. var distY = pointA.y - pointB.y;
  14557. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14558. if (previousPinchDistance === 0) {
  14559. previousPinchDistance = pinchSquaredDistance;
  14560. return;
  14561. }
  14562. if (pinchSquaredDistance !== previousPinchDistance) {
  14563. _this.camera
  14564. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14565. (_this.pinchPrecision *
  14566. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14567. direction);
  14568. previousPinchDistance = pinchSquaredDistance;
  14569. }
  14570. }
  14571. }
  14572. };
  14573. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14574. this._onContextMenu = function (evt) {
  14575. evt.preventDefault();
  14576. };
  14577. if (!this.camera._useCtrlForPanning) {
  14578. element.addEventListener("contextmenu", this._onContextMenu, false);
  14579. }
  14580. this._onLostFocus = function () {
  14581. //this._keys = [];
  14582. pointA = pointB = undefined;
  14583. previousPinchDistance = 0;
  14584. cacheSoloPointer = null;
  14585. };
  14586. this._onMouseMove = function (evt) {
  14587. if (!engine.isPointerLock) {
  14588. return;
  14589. }
  14590. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14591. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14592. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14593. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14594. if (!noPreventDefault) {
  14595. evt.preventDefault();
  14596. }
  14597. };
  14598. this._onGestureStart = function (e) {
  14599. if (window.MSGesture === undefined) {
  14600. return;
  14601. }
  14602. if (!_this._MSGestureHandler) {
  14603. _this._MSGestureHandler = new MSGesture();
  14604. _this._MSGestureHandler.target = element;
  14605. }
  14606. _this._MSGestureHandler.addPointer(e.pointerId);
  14607. };
  14608. this._onGesture = function (e) {
  14609. _this.camera.radius *= e.scale;
  14610. if (e.preventDefault) {
  14611. if (!noPreventDefault) {
  14612. e.stopPropagation();
  14613. e.preventDefault();
  14614. }
  14615. }
  14616. };
  14617. element.addEventListener("mousemove", this._onMouseMove, false);
  14618. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14619. element.addEventListener("MSGestureChange", this._onGesture, false);
  14620. element.addEventListener("keydown", this._onKeyDown, false);
  14621. element.addEventListener("keyup", this._onKeyUp, false);
  14622. BABYLON.Tools.RegisterTopRootEvents([
  14623. { name: "blur", handler: this._onLostFocus }
  14624. ]);
  14625. };
  14626. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14627. if (element && this._observer) {
  14628. this.camera.getScene().onPointerObservable.remove(this._observer);
  14629. this._observer = null;
  14630. element.removeEventListener("contextmenu", this._onContextMenu);
  14631. element.removeEventListener("mousemove", this._onMouseMove);
  14632. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14633. element.removeEventListener("MSGestureChange", this._onGesture);
  14634. element.removeEventListener("keydown", this._onKeyDown);
  14635. element.removeEventListener("keyup", this._onKeyUp);
  14636. this._isPanClick = false;
  14637. this.pinchInwards = true;
  14638. this._onKeyDown = null;
  14639. this._onKeyUp = null;
  14640. this._onMouseMove = null;
  14641. this._onGestureStart = null;
  14642. this._onGesture = null;
  14643. this._MSGestureHandler = null;
  14644. this._onLostFocus = null;
  14645. this._onContextMenu = null;
  14646. }
  14647. BABYLON.Tools.UnregisterTopRootEvents([
  14648. { name: "blur", handler: this._onLostFocus }
  14649. ]);
  14650. };
  14651. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14652. return "ArcRotateCameraPointersInput";
  14653. };
  14654. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14655. return "pointers";
  14656. };
  14657. __decorate([
  14658. BABYLON.serialize()
  14659. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14660. __decorate([
  14661. BABYLON.serialize()
  14662. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14663. __decorate([
  14664. BABYLON.serialize()
  14665. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14666. __decorate([
  14667. BABYLON.serialize()
  14668. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14672. return ArcRotateCameraPointersInput;
  14673. }());
  14674. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14675. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14676. })(BABYLON || (BABYLON = {}));
  14677. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14678. var BABYLON;
  14679. (function (BABYLON) {
  14680. var ArcRotateCameraGamepadInput = (function () {
  14681. function ArcRotateCameraGamepadInput() {
  14682. this.gamepadRotationSensibility = 80;
  14683. this.gamepadMoveSensibility = 40;
  14684. }
  14685. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14686. var _this = this;
  14687. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14688. };
  14689. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14690. if (this._gamepads) {
  14691. this._gamepads.dispose();
  14692. }
  14693. this.gamepad = null;
  14694. };
  14695. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14696. if (this.gamepad) {
  14697. var camera = this.camera;
  14698. var RSValues = this.gamepad.rightStick;
  14699. if (RSValues.x != 0) {
  14700. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14701. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14702. camera.inertialAlphaOffset += normalizedRX;
  14703. }
  14704. }
  14705. if (RSValues.y != 0) {
  14706. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14707. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14708. camera.inertialBetaOffset += normalizedRY;
  14709. }
  14710. }
  14711. var LSValues = this.gamepad.leftStick;
  14712. if (LSValues.y != 0) {
  14713. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14714. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14715. this.camera.inertialRadiusOffset -= normalizedLY;
  14716. }
  14717. }
  14718. }
  14719. };
  14720. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14721. // Only the first gamepad can control the camera
  14722. if (gamepad.index === 0) {
  14723. this.gamepad = gamepad;
  14724. }
  14725. };
  14726. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14727. return "ArcRotateCameraGamepadInput";
  14728. };
  14729. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14730. return "gamepad";
  14731. };
  14732. __decorate([
  14733. BABYLON.serialize()
  14734. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14735. __decorate([
  14736. BABYLON.serialize()
  14737. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14738. return ArcRotateCameraGamepadInput;
  14739. }());
  14740. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14741. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14742. })(BABYLON || (BABYLON = {}));
  14743. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14744. var BABYLON;
  14745. (function (BABYLON) {
  14746. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14747. function ArcRotateCameraVRDeviceOrientationInput() {
  14748. this.alphaCorrection = 1;
  14749. this.betaCorrection = 1;
  14750. this.gammaCorrection = 1;
  14751. this._alpha = 0;
  14752. this._beta = 0;
  14753. this._gamma = 0;
  14754. this._dirty = false;
  14755. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14756. }
  14757. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14758. this.camera.attachControl(element, noPreventDefault);
  14759. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14760. };
  14761. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14762. var camera = this.camera;
  14763. this._alpha = +evt.alpha | 0;
  14764. this._beta = +evt.beta | 0;
  14765. this._gamma = +evt.gamma | 0;
  14766. this._dirty = true;
  14767. };
  14768. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14769. if (this._dirty) {
  14770. this._dirty = false;
  14771. if (this._gamma < 0) {
  14772. this._gamma = 180 + this._gamma;
  14773. }
  14774. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14775. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14776. }
  14777. };
  14778. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14779. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14780. };
  14781. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14782. return "ArcRotateCameraVRDeviceOrientationInput";
  14783. };
  14784. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14785. return "VRDeviceOrientation";
  14786. };
  14787. return ArcRotateCameraVRDeviceOrientationInput;
  14788. }());
  14789. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14790. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14791. })(BABYLON || (BABYLON = {}));
  14792. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14793. var BABYLON;
  14794. (function (BABYLON) {
  14795. var TargetCamera = (function (_super) {
  14796. __extends(TargetCamera, _super);
  14797. function TargetCamera(name, position, scene) {
  14798. _super.call(this, name, position, scene);
  14799. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14800. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14801. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14802. this.speed = 2.0;
  14803. this.noRotationConstraint = false;
  14804. this.lockedTarget = null;
  14805. this._currentTarget = BABYLON.Vector3.Zero();
  14806. this._viewMatrix = BABYLON.Matrix.Zero();
  14807. this._camMatrix = BABYLON.Matrix.Zero();
  14808. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14809. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14810. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14811. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14812. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14813. this._lookAtTemp = BABYLON.Matrix.Zero();
  14814. this._tempMatrix = BABYLON.Matrix.Zero();
  14815. }
  14816. TargetCamera.prototype.getFrontPosition = function (distance) {
  14817. var direction = this.getTarget().subtract(this.position);
  14818. direction.normalize();
  14819. direction.scaleInPlace(distance);
  14820. return this.globalPosition.add(direction);
  14821. };
  14822. TargetCamera.prototype._getLockedTargetPosition = function () {
  14823. if (!this.lockedTarget) {
  14824. return null;
  14825. }
  14826. if (this.lockedTarget.absolutePosition) {
  14827. this.lockedTarget.computeWorldMatrix();
  14828. }
  14829. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14830. };
  14831. // Cache
  14832. TargetCamera.prototype._initCache = function () {
  14833. _super.prototype._initCache.call(this);
  14834. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14835. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14836. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14837. };
  14838. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14839. if (!ignoreParentClass) {
  14840. _super.prototype._updateCache.call(this);
  14841. }
  14842. var lockedTargetPosition = this._getLockedTargetPosition();
  14843. if (!lockedTargetPosition) {
  14844. this._cache.lockedTarget = null;
  14845. }
  14846. else {
  14847. if (!this._cache.lockedTarget) {
  14848. this._cache.lockedTarget = lockedTargetPosition.clone();
  14849. }
  14850. else {
  14851. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14852. }
  14853. }
  14854. this._cache.rotation.copyFrom(this.rotation);
  14855. if (this.rotationQuaternion)
  14856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14857. };
  14858. // Synchronized
  14859. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14860. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14861. return false;
  14862. }
  14863. var lockedTargetPosition = this._getLockedTargetPosition();
  14864. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14865. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14866. };
  14867. // Methods
  14868. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14869. var engine = this.getEngine();
  14870. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14871. };
  14872. // Target
  14873. TargetCamera.prototype.setTarget = function (target) {
  14874. this.upVector.normalize();
  14875. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14876. this._camMatrix.invert();
  14877. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14878. var vDir = target.subtract(this.position);
  14879. if (vDir.x >= 0.0) {
  14880. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14881. }
  14882. else {
  14883. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14884. }
  14885. this.rotation.z = 0;
  14886. if (isNaN(this.rotation.x)) {
  14887. this.rotation.x = 0;
  14888. }
  14889. if (isNaN(this.rotation.y)) {
  14890. this.rotation.y = 0;
  14891. }
  14892. if (isNaN(this.rotation.z)) {
  14893. this.rotation.z = 0;
  14894. }
  14895. if (this.rotationQuaternion) {
  14896. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14897. }
  14898. };
  14899. TargetCamera.prototype.getTarget = function () {
  14900. return this._currentTarget;
  14901. };
  14902. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14903. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14904. };
  14905. TargetCamera.prototype._updatePosition = function () {
  14906. this.position.addInPlace(this.cameraDirection);
  14907. };
  14908. TargetCamera.prototype._checkInputs = function () {
  14909. var needToMove = this._decideIfNeedsToMove();
  14910. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14911. // Move
  14912. if (needToMove) {
  14913. this._updatePosition();
  14914. }
  14915. // Rotate
  14916. if (needToRotate) {
  14917. this.rotation.x += this.cameraRotation.x;
  14918. this.rotation.y += this.cameraRotation.y;
  14919. if (!this.noRotationConstraint) {
  14920. var limit = (Math.PI / 2) * 0.95;
  14921. if (this.rotation.x > limit)
  14922. this.rotation.x = limit;
  14923. if (this.rotation.x < -limit)
  14924. this.rotation.x = -limit;
  14925. }
  14926. }
  14927. // Inertia
  14928. if (needToMove) {
  14929. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14930. this.cameraDirection.x = 0;
  14931. }
  14932. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14933. this.cameraDirection.y = 0;
  14934. }
  14935. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14936. this.cameraDirection.z = 0;
  14937. }
  14938. this.cameraDirection.scaleInPlace(this.inertia);
  14939. }
  14940. if (needToRotate) {
  14941. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14942. this.cameraRotation.x = 0;
  14943. }
  14944. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14945. this.cameraRotation.y = 0;
  14946. }
  14947. this.cameraRotation.scaleInPlace(this.inertia);
  14948. }
  14949. _super.prototype._checkInputs.call(this);
  14950. };
  14951. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14952. if (this.rotationQuaternion) {
  14953. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14954. //update the up vector!
  14955. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14956. }
  14957. else {
  14958. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14959. }
  14960. };
  14961. TargetCamera.prototype._getViewMatrix = function () {
  14962. if (!this.lockedTarget) {
  14963. // Compute
  14964. this._updateCameraRotationMatrix();
  14965. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14966. // Computing target and final matrix
  14967. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14968. }
  14969. else {
  14970. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14971. }
  14972. if (this.getScene().useRightHandedSystem) {
  14973. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14974. }
  14975. else {
  14976. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14977. }
  14978. return this._viewMatrix;
  14979. };
  14980. /**
  14981. * @override
  14982. * Override Camera.createRigCamera
  14983. */
  14984. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14985. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14986. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14987. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14988. if (!this.rotationQuaternion) {
  14989. this.rotationQuaternion = new BABYLON.Quaternion();
  14990. }
  14991. rigCamera._cameraRigParams = {};
  14992. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14993. }
  14994. return rigCamera;
  14995. }
  14996. return null;
  14997. };
  14998. /**
  14999. * @override
  15000. * Override Camera._updateRigCameras
  15001. */
  15002. TargetCamera.prototype._updateRigCameras = function () {
  15003. var camLeft = this._rigCameras[0];
  15004. var camRight = this._rigCameras[1];
  15005. switch (this.cameraRigMode) {
  15006. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15007. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15010. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15011. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15012. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15013. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15014. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15015. camLeft.setTarget(this.getTarget());
  15016. camRight.setTarget(this.getTarget());
  15017. break;
  15018. case BABYLON.Camera.RIG_MODE_VR:
  15019. case BABYLON.Camera.RIG_MODE_WEBVR:
  15020. if (camLeft.rotationQuaternion) {
  15021. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15022. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15023. }
  15024. else {
  15025. camLeft.rotation.copyFrom(this.rotation);
  15026. camRight.rotation.copyFrom(this.rotation);
  15027. }
  15028. camLeft.position.copyFrom(this.position);
  15029. camRight.position.copyFrom(this.position);
  15030. break;
  15031. }
  15032. _super.prototype._updateRigCameras.call(this);
  15033. };
  15034. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15035. if (!this._rigCamTransformMatrix) {
  15036. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15037. }
  15038. var target = this.getTarget();
  15039. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15040. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15041. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15042. };
  15043. TargetCamera.prototype.getClassName = function () {
  15044. return "TargetCamera";
  15045. };
  15046. __decorate([
  15047. BABYLON.serializeAsVector3()
  15048. ], TargetCamera.prototype, "rotation", void 0);
  15049. __decorate([
  15050. BABYLON.serialize()
  15051. ], TargetCamera.prototype, "speed", void 0);
  15052. __decorate([
  15053. BABYLON.serializeAsMeshReference("lockedTargetId")
  15054. ], TargetCamera.prototype, "lockedTarget", void 0);
  15055. return TargetCamera;
  15056. }(BABYLON.Camera));
  15057. BABYLON.TargetCamera = TargetCamera;
  15058. })(BABYLON || (BABYLON = {}));
  15059. //# sourceMappingURL=babylon.targetCamera.js.map
  15060. var BABYLON;
  15061. (function (BABYLON) {
  15062. var FreeCamera = (function (_super) {
  15063. __extends(FreeCamera, _super);
  15064. function FreeCamera(name, position, scene) {
  15065. var _this = this;
  15066. _super.call(this, name, position, scene);
  15067. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15068. this.checkCollisions = false;
  15069. this.applyGravity = false;
  15070. this._collider = new BABYLON.Collider();
  15071. this._needMoveForGravity = false;
  15072. this._oldPosition = BABYLON.Vector3.Zero();
  15073. this._diffPosition = BABYLON.Vector3.Zero();
  15074. this._newPosition = BABYLON.Vector3.Zero();
  15075. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15076. if (collidedMesh === void 0) { collidedMesh = null; }
  15077. //TODO move this to the collision coordinator!
  15078. if (_this.getScene().workerCollisions)
  15079. newPosition.multiplyInPlace(_this._collider.radius);
  15080. var updatePosition = function (newPos) {
  15081. _this._newPosition.copyFrom(newPos);
  15082. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15083. var oldPosition = _this.position.clone();
  15084. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15085. _this.position.addInPlace(_this._diffPosition);
  15086. if (_this.onCollide && collidedMesh) {
  15087. _this.onCollide(collidedMesh);
  15088. }
  15089. }
  15090. };
  15091. updatePosition(newPosition);
  15092. };
  15093. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  15094. this.inputs.addKeyboard().addMouse();
  15095. }
  15096. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15097. //-- begin properties for backward compatibility for inputs
  15098. get: function () {
  15099. var mouse = this.inputs.attached["mouse"];
  15100. if (mouse)
  15101. return mouse.angularSensibility;
  15102. },
  15103. set: function (value) {
  15104. var mouse = this.inputs.attached["mouse"];
  15105. if (mouse)
  15106. mouse.angularSensibility = value;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15112. get: function () {
  15113. var keyboard = this.inputs.attached["keyboard"];
  15114. if (keyboard)
  15115. return keyboard.keysUp;
  15116. },
  15117. set: function (value) {
  15118. var keyboard = this.inputs.attached["keyboard"];
  15119. if (keyboard)
  15120. keyboard.keysUp = value;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15126. get: function () {
  15127. var keyboard = this.inputs.attached["keyboard"];
  15128. if (keyboard)
  15129. return keyboard.keysDown;
  15130. },
  15131. set: function (value) {
  15132. var keyboard = this.inputs.attached["keyboard"];
  15133. if (keyboard)
  15134. keyboard.keysDown = value;
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15140. get: function () {
  15141. var keyboard = this.inputs.attached["keyboard"];
  15142. if (keyboard)
  15143. return keyboard.keysLeft;
  15144. },
  15145. set: function (value) {
  15146. var keyboard = this.inputs.attached["keyboard"];
  15147. if (keyboard)
  15148. keyboard.keysLeft = value;
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15154. get: function () {
  15155. var keyboard = this.inputs.attached["keyboard"];
  15156. if (keyboard)
  15157. return keyboard.keysRight;
  15158. },
  15159. set: function (value) {
  15160. var keyboard = this.inputs.attached["keyboard"];
  15161. if (keyboard)
  15162. keyboard.keysRight = value;
  15163. },
  15164. enumerable: true,
  15165. configurable: true
  15166. });
  15167. // Controls
  15168. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15169. this.inputs.attachElement(element, noPreventDefault);
  15170. };
  15171. FreeCamera.prototype.detachControl = function (element) {
  15172. this.inputs.detachElement(element);
  15173. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15174. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15175. };
  15176. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15177. var globalPosition;
  15178. if (this.parent) {
  15179. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15180. }
  15181. else {
  15182. globalPosition = this.position;
  15183. }
  15184. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15185. this._collider.radius = this.ellipsoid;
  15186. //no need for clone, as long as gravity is not on.
  15187. var actualVelocity = velocity;
  15188. //add gravity to the velocity to prevent the dual-collision checking
  15189. if (this.applyGravity) {
  15190. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15191. actualVelocity = velocity.add(this.getScene().gravity);
  15192. }
  15193. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15194. };
  15195. FreeCamera.prototype._checkInputs = function () {
  15196. if (!this._localDirection) {
  15197. this._localDirection = BABYLON.Vector3.Zero();
  15198. this._transformedDirection = BABYLON.Vector3.Zero();
  15199. }
  15200. this.inputs.checkInputs();
  15201. _super.prototype._checkInputs.call(this);
  15202. };
  15203. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15204. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15205. };
  15206. FreeCamera.prototype._updatePosition = function () {
  15207. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15208. this._collideWithWorld(this.cameraDirection);
  15209. }
  15210. else {
  15211. this.position.addInPlace(this.cameraDirection);
  15212. }
  15213. };
  15214. FreeCamera.prototype.dispose = function () {
  15215. this.inputs.clear();
  15216. _super.prototype.dispose.call(this);
  15217. };
  15218. FreeCamera.prototype.getClassName = function () {
  15219. return "FreeCamera";
  15220. };
  15221. __decorate([
  15222. BABYLON.serializeAsVector3()
  15223. ], FreeCamera.prototype, "ellipsoid", void 0);
  15224. __decorate([
  15225. BABYLON.serialize()
  15226. ], FreeCamera.prototype, "checkCollisions", void 0);
  15227. __decorate([
  15228. BABYLON.serialize()
  15229. ], FreeCamera.prototype, "applyGravity", void 0);
  15230. return FreeCamera;
  15231. }(BABYLON.TargetCamera));
  15232. BABYLON.FreeCamera = FreeCamera;
  15233. })(BABYLON || (BABYLON = {}));
  15234. //# sourceMappingURL=babylon.freeCamera.js.map
  15235. var BABYLON;
  15236. (function (BABYLON) {
  15237. var FreeCameraInputsManager = (function (_super) {
  15238. __extends(FreeCameraInputsManager, _super);
  15239. function FreeCameraInputsManager(camera) {
  15240. _super.call(this, camera);
  15241. }
  15242. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15243. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15244. return this;
  15245. };
  15246. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15247. if (touchEnabled === void 0) { touchEnabled = true; }
  15248. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15249. return this;
  15250. };
  15251. FreeCameraInputsManager.prototype.addGamepad = function () {
  15252. this.add(new BABYLON.FreeCameraGamepadInput());
  15253. return this;
  15254. };
  15255. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15256. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15257. return this;
  15258. };
  15259. FreeCameraInputsManager.prototype.addTouch = function () {
  15260. this.add(new BABYLON.FreeCameraTouchInput());
  15261. return this;
  15262. };
  15263. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15264. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15265. return this;
  15266. };
  15267. return FreeCameraInputsManager;
  15268. }(BABYLON.CameraInputsManager));
  15269. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15270. })(BABYLON || (BABYLON = {}));
  15271. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15272. var BABYLON;
  15273. (function (BABYLON) {
  15274. var FollowCamera = (function (_super) {
  15275. __extends(FollowCamera, _super);
  15276. function FollowCamera(name, position, scene, lockedTarget) {
  15277. _super.call(this, name, position, scene);
  15278. this.radius = 12;
  15279. this.rotationOffset = 0;
  15280. this.heightOffset = 4;
  15281. this.cameraAcceleration = 0.05;
  15282. this.maxCameraSpeed = 20;
  15283. this.lockedTarget = lockedTarget;
  15284. }
  15285. FollowCamera.prototype.getRadians = function (degrees) {
  15286. return degrees * Math.PI / 180;
  15287. };
  15288. FollowCamera.prototype.follow = function (cameraTarget) {
  15289. if (!cameraTarget)
  15290. return;
  15291. var yRotation;
  15292. if (cameraTarget.rotationQuaternion) {
  15293. var rotMatrix = new BABYLON.Matrix();
  15294. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15295. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15296. }
  15297. else {
  15298. yRotation = cameraTarget.rotation.y;
  15299. }
  15300. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15301. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15302. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15303. var dx = targetX - this.position.x;
  15304. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15305. var dz = (targetZ) - this.position.z;
  15306. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15307. var vy = dy * this.cameraAcceleration;
  15308. var vz = dz * this.cameraAcceleration * 2;
  15309. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15310. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15311. }
  15312. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15313. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15314. }
  15315. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15316. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15317. }
  15318. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15319. this.setTarget(cameraTarget.position);
  15320. };
  15321. FollowCamera.prototype._checkInputs = function () {
  15322. _super.prototype._checkInputs.call(this);
  15323. this.follow(this.lockedTarget);
  15324. };
  15325. FollowCamera.prototype.getClassName = function () {
  15326. return "FollowCamera";
  15327. };
  15328. __decorate([
  15329. BABYLON.serialize()
  15330. ], FollowCamera.prototype, "radius", void 0);
  15331. __decorate([
  15332. BABYLON.serialize()
  15333. ], FollowCamera.prototype, "rotationOffset", void 0);
  15334. __decorate([
  15335. BABYLON.serialize()
  15336. ], FollowCamera.prototype, "heightOffset", void 0);
  15337. __decorate([
  15338. BABYLON.serialize()
  15339. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15340. __decorate([
  15341. BABYLON.serialize()
  15342. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15343. __decorate([
  15344. BABYLON.serializeAsMeshReference("lockedTargetId")
  15345. ], FollowCamera.prototype, "lockedTarget", void 0);
  15346. return FollowCamera;
  15347. }(BABYLON.TargetCamera));
  15348. BABYLON.FollowCamera = FollowCamera;
  15349. var ArcFollowCamera = (function (_super) {
  15350. __extends(ArcFollowCamera, _super);
  15351. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15352. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15353. this.alpha = alpha;
  15354. this.beta = beta;
  15355. this.radius = radius;
  15356. this.target = target;
  15357. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15358. this.follow();
  15359. }
  15360. ArcFollowCamera.prototype.follow = function () {
  15361. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15362. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15363. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15364. this.position = this.target.position.add(this._cartesianCoordinates);
  15365. this.setTarget(this.target.position);
  15366. };
  15367. ArcFollowCamera.prototype._checkInputs = function () {
  15368. _super.prototype._checkInputs.call(this);
  15369. this.follow();
  15370. };
  15371. ArcFollowCamera.prototype.getClassName = function () {
  15372. return "ArcFollowCamera";
  15373. };
  15374. return ArcFollowCamera;
  15375. }(BABYLON.TargetCamera));
  15376. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15377. })(BABYLON || (BABYLON = {}));
  15378. //# sourceMappingURL=babylon.followCamera.js.map
  15379. var BABYLON;
  15380. (function (BABYLON) {
  15381. // We're mainly based on the logic defined into the FreeCamera code
  15382. var TouchCamera = (function (_super) {
  15383. __extends(TouchCamera, _super);
  15384. //-- end properties for backward compatibility for inputs
  15385. function TouchCamera(name, position, scene) {
  15386. _super.call(this, name, position, scene);
  15387. this.inputs.addTouch();
  15388. this._setupInputs();
  15389. }
  15390. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15391. //-- Begin properties for backward compatibility for inputs
  15392. get: function () {
  15393. var touch = this.inputs.attached["touch"];
  15394. if (touch)
  15395. return touch.touchAngularSensibility;
  15396. },
  15397. set: function (value) {
  15398. var touch = this.inputs.attached["touch"];
  15399. if (touch)
  15400. touch.touchAngularSensibility = value;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15406. get: function () {
  15407. var touch = this.inputs.attached["touch"];
  15408. if (touch)
  15409. return touch.touchMoveSensibility;
  15410. },
  15411. set: function (value) {
  15412. var touch = this.inputs.attached["touch"];
  15413. if (touch)
  15414. touch.touchMoveSensibility = value;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. TouchCamera.prototype.getClassName = function () {
  15420. return "TouchCamera";
  15421. };
  15422. TouchCamera.prototype._setupInputs = function () {
  15423. var mouse = this.inputs.attached["mouse"];
  15424. if (mouse) {
  15425. mouse.touchEnabled = false;
  15426. }
  15427. };
  15428. return TouchCamera;
  15429. }(BABYLON.FreeCamera));
  15430. BABYLON.TouchCamera = TouchCamera;
  15431. })(BABYLON || (BABYLON = {}));
  15432. //# sourceMappingURL=babylon.touchCamera.js.map
  15433. var BABYLON;
  15434. (function (BABYLON) {
  15435. var ArcRotateCamera = (function (_super) {
  15436. __extends(ArcRotateCamera, _super);
  15437. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15438. var _this = this;
  15439. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15440. this.inertialAlphaOffset = 0;
  15441. this.inertialBetaOffset = 0;
  15442. this.inertialRadiusOffset = 0;
  15443. this.lowerAlphaLimit = null;
  15444. this.upperAlphaLimit = null;
  15445. this.lowerBetaLimit = 0.01;
  15446. this.upperBetaLimit = Math.PI;
  15447. this.lowerRadiusLimit = null;
  15448. this.upperRadiusLimit = null;
  15449. this.inertialPanningX = 0;
  15450. this.inertialPanningY = 0;
  15451. //-- end properties for backward compatibility for inputs
  15452. this.zoomOnFactor = 1;
  15453. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15454. this.allowUpsideDown = true;
  15455. this._viewMatrix = new BABYLON.Matrix();
  15456. // Panning
  15457. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15458. this.checkCollisions = false;
  15459. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15460. this._collider = new BABYLON.Collider();
  15461. this._previousPosition = BABYLON.Vector3.Zero();
  15462. this._collisionVelocity = BABYLON.Vector3.Zero();
  15463. this._newPosition = BABYLON.Vector3.Zero();
  15464. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15465. if (collidedMesh === void 0) { collidedMesh = null; }
  15466. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15467. newPosition.multiplyInPlace(_this._collider.radius);
  15468. }
  15469. if (!collidedMesh) {
  15470. _this._previousPosition.copyFrom(_this.position);
  15471. }
  15472. else {
  15473. _this.setPosition(newPosition);
  15474. if (_this.onCollide) {
  15475. _this.onCollide(collidedMesh);
  15476. }
  15477. }
  15478. // Recompute because of constraints
  15479. var cosa = Math.cos(_this.alpha);
  15480. var sina = Math.sin(_this.alpha);
  15481. var cosb = Math.cos(_this.beta);
  15482. var sinb = Math.sin(_this.beta);
  15483. if (sinb === 0) {
  15484. sinb = 0.0001;
  15485. }
  15486. var target = _this._getTargetPosition();
  15487. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15488. _this.position.copyFrom(_this._newPosition);
  15489. var up = _this.upVector;
  15490. if (_this.allowUpsideDown && _this.beta < 0) {
  15491. up = up.clone();
  15492. up = up.negate();
  15493. }
  15494. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15495. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15496. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15497. _this._collisionTriggered = false;
  15498. };
  15499. if (!target) {
  15500. this.target = BABYLON.Vector3.Zero();
  15501. }
  15502. else {
  15503. this.target = target;
  15504. }
  15505. this.alpha = alpha;
  15506. this.beta = beta;
  15507. this.radius = radius;
  15508. this.getViewMatrix();
  15509. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15510. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15511. }
  15512. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15513. //-- begin properties for backward compatibility for inputs
  15514. get: function () {
  15515. var pointers = this.inputs.attached["pointers"];
  15516. if (pointers)
  15517. return pointers.angularSensibilityX;
  15518. },
  15519. set: function (value) {
  15520. var pointers = this.inputs.attached["pointers"];
  15521. if (pointers) {
  15522. pointers.angularSensibilityX = value;
  15523. }
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15529. get: function () {
  15530. var pointers = this.inputs.attached["pointers"];
  15531. if (pointers)
  15532. return pointers.angularSensibilityY;
  15533. },
  15534. set: function (value) {
  15535. var pointers = this.inputs.attached["pointers"];
  15536. if (pointers) {
  15537. pointers.angularSensibilityY = value;
  15538. }
  15539. },
  15540. enumerable: true,
  15541. configurable: true
  15542. });
  15543. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15544. get: function () {
  15545. var pointers = this.inputs.attached["pointers"];
  15546. if (pointers)
  15547. return pointers.pinchPrecision;
  15548. },
  15549. set: function (value) {
  15550. var pointers = this.inputs.attached["pointers"];
  15551. if (pointers) {
  15552. pointers.pinchPrecision = value;
  15553. }
  15554. },
  15555. enumerable: true,
  15556. configurable: true
  15557. });
  15558. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15559. get: function () {
  15560. var pointers = this.inputs.attached["pointers"];
  15561. if (pointers)
  15562. return pointers.panningSensibility;
  15563. },
  15564. set: function (value) {
  15565. var pointers = this.inputs.attached["pointers"];
  15566. if (pointers) {
  15567. pointers.panningSensibility = value;
  15568. }
  15569. },
  15570. enumerable: true,
  15571. configurable: true
  15572. });
  15573. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15574. get: function () {
  15575. var keyboard = this.inputs.attached["keyboard"];
  15576. if (keyboard)
  15577. return keyboard.keysUp;
  15578. },
  15579. set: function (value) {
  15580. var keyboard = this.inputs.attached["keyboard"];
  15581. if (keyboard)
  15582. keyboard.keysUp = value;
  15583. },
  15584. enumerable: true,
  15585. configurable: true
  15586. });
  15587. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15588. get: function () {
  15589. var keyboard = this.inputs.attached["keyboard"];
  15590. if (keyboard)
  15591. return keyboard.keysDown;
  15592. },
  15593. set: function (value) {
  15594. var keyboard = this.inputs.attached["keyboard"];
  15595. if (keyboard)
  15596. keyboard.keysDown = value;
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15602. get: function () {
  15603. var keyboard = this.inputs.attached["keyboard"];
  15604. if (keyboard)
  15605. return keyboard.keysLeft;
  15606. },
  15607. set: function (value) {
  15608. var keyboard = this.inputs.attached["keyboard"];
  15609. if (keyboard)
  15610. keyboard.keysLeft = value;
  15611. },
  15612. enumerable: true,
  15613. configurable: true
  15614. });
  15615. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15616. get: function () {
  15617. var keyboard = this.inputs.attached["keyboard"];
  15618. if (keyboard)
  15619. return keyboard.keysRight;
  15620. },
  15621. set: function (value) {
  15622. var keyboard = this.inputs.attached["keyboard"];
  15623. if (keyboard)
  15624. keyboard.keysRight = value;
  15625. },
  15626. enumerable: true,
  15627. configurable: true
  15628. });
  15629. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15630. get: function () {
  15631. var mousewheel = this.inputs.attached["mousewheel"];
  15632. if (mousewheel)
  15633. return mousewheel.wheelPrecision;
  15634. },
  15635. set: function (value) {
  15636. var mousewheel = this.inputs.attached["mousewheel"];
  15637. if (mousewheel)
  15638. mousewheel.wheelPrecision = value;
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. // Cache
  15644. ArcRotateCamera.prototype._initCache = function () {
  15645. _super.prototype._initCache.call(this);
  15646. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15647. this._cache.alpha = undefined;
  15648. this._cache.beta = undefined;
  15649. this._cache.radius = undefined;
  15650. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15651. };
  15652. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15653. if (!ignoreParentClass) {
  15654. _super.prototype._updateCache.call(this);
  15655. }
  15656. this._cache.target.copyFrom(this._getTargetPosition());
  15657. this._cache.alpha = this.alpha;
  15658. this._cache.beta = this.beta;
  15659. this._cache.radius = this.radius;
  15660. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15661. };
  15662. ArcRotateCamera.prototype._getTargetPosition = function () {
  15663. if (this.target.getAbsolutePosition) {
  15664. var pos = this.target.getAbsolutePosition();
  15665. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15666. }
  15667. return this.target;
  15668. };
  15669. // Synchronized
  15670. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15671. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15672. return false;
  15673. return this._cache.target.equals(this.target)
  15674. && this._cache.alpha === this.alpha
  15675. && this._cache.beta === this.beta
  15676. && this._cache.radius === this.radius
  15677. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15678. };
  15679. // Methods
  15680. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15681. var _this = this;
  15682. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15683. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15684. this._useCtrlForPanning = useCtrlForPanning;
  15685. this._panningMouseButton = panningMouseButton;
  15686. this.inputs.attachElement(element, noPreventDefault);
  15687. this._reset = function () {
  15688. _this.inertialAlphaOffset = 0;
  15689. _this.inertialBetaOffset = 0;
  15690. _this.inertialRadiusOffset = 0;
  15691. };
  15692. };
  15693. ArcRotateCamera.prototype.detachControl = function (element) {
  15694. this.inputs.detachElement(element);
  15695. if (this._reset) {
  15696. this._reset();
  15697. }
  15698. };
  15699. ArcRotateCamera.prototype._checkInputs = function () {
  15700. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15701. if (this._collisionTriggered) {
  15702. return;
  15703. }
  15704. this.inputs.checkInputs();
  15705. // Inertia
  15706. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15707. if (this.getScene().useRightHandedSystem) {
  15708. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15709. }
  15710. else {
  15711. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15712. }
  15713. this.beta += this.inertialBetaOffset;
  15714. this.radius -= this.inertialRadiusOffset;
  15715. this.inertialAlphaOffset *= this.inertia;
  15716. this.inertialBetaOffset *= this.inertia;
  15717. this.inertialRadiusOffset *= this.inertia;
  15718. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15719. this.inertialAlphaOffset = 0;
  15720. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15721. this.inertialBetaOffset = 0;
  15722. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15723. this.inertialRadiusOffset = 0;
  15724. }
  15725. // Panning inertia
  15726. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15727. if (!this._localDirection) {
  15728. this._localDirection = BABYLON.Vector3.Zero();
  15729. this._transformedDirection = BABYLON.Vector3.Zero();
  15730. }
  15731. this.inertialPanningX *= this.inertia;
  15732. this.inertialPanningY *= this.inertia;
  15733. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15734. this.inertialPanningX = 0;
  15735. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15736. this.inertialPanningY = 0;
  15737. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15738. this._localDirection.multiplyInPlace(this.panningAxis);
  15739. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15740. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15741. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15742. if (!this.panningAxis.y) {
  15743. this._transformedDirection.y = 0;
  15744. }
  15745. if (!this.target.getAbsolutePosition) {
  15746. this.target.addInPlace(this._transformedDirection);
  15747. }
  15748. }
  15749. // Limits
  15750. this._checkLimits();
  15751. _super.prototype._checkInputs.call(this);
  15752. };
  15753. ArcRotateCamera.prototype._checkLimits = function () {
  15754. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15755. if (this.allowUpsideDown && this.beta > Math.PI) {
  15756. this.beta = this.beta - (2 * Math.PI);
  15757. }
  15758. }
  15759. else {
  15760. if (this.beta < this.lowerBetaLimit) {
  15761. this.beta = this.lowerBetaLimit;
  15762. }
  15763. }
  15764. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15765. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15766. this.beta = this.beta + (2 * Math.PI);
  15767. }
  15768. }
  15769. else {
  15770. if (this.beta > this.upperBetaLimit) {
  15771. this.beta = this.upperBetaLimit;
  15772. }
  15773. }
  15774. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15775. this.alpha = this.lowerAlphaLimit;
  15776. }
  15777. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15778. this.alpha = this.upperAlphaLimit;
  15779. }
  15780. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15781. this.radius = this.lowerRadiusLimit;
  15782. }
  15783. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15784. this.radius = this.upperRadiusLimit;
  15785. }
  15786. };
  15787. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15788. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15789. this.radius = radiusv3.length();
  15790. // Alpha
  15791. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15792. if (radiusv3.z < 0) {
  15793. this.alpha = 2 * Math.PI - this.alpha;
  15794. }
  15795. // Beta
  15796. this.beta = Math.acos(radiusv3.y / this.radius);
  15797. this._checkLimits();
  15798. };
  15799. ArcRotateCamera.prototype.setPosition = function (position) {
  15800. if (this.position.equals(position)) {
  15801. return;
  15802. }
  15803. this.position.copyFrom(position);
  15804. this.rebuildAnglesAndRadius();
  15805. };
  15806. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15807. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15808. if (this._getTargetPosition().equals(target)) {
  15809. return;
  15810. }
  15811. if (toBoundingCenter && target.getBoundingInfo) {
  15812. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15813. }
  15814. else {
  15815. this._targetBoundingCenter = null;
  15816. }
  15817. this.target = target;
  15818. this.rebuildAnglesAndRadius();
  15819. };
  15820. ArcRotateCamera.prototype._getViewMatrix = function () {
  15821. // Compute
  15822. var cosa = Math.cos(this.alpha);
  15823. var sina = Math.sin(this.alpha);
  15824. var cosb = Math.cos(this.beta);
  15825. var sinb = Math.sin(this.beta);
  15826. if (sinb === 0) {
  15827. sinb = 0.0001;
  15828. }
  15829. var target = this._getTargetPosition();
  15830. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15831. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15832. this._collider.radius = this.collisionRadius;
  15833. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15834. this._collisionTriggered = true;
  15835. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15836. }
  15837. else {
  15838. this.position.copyFrom(this._newPosition);
  15839. var up = this.upVector;
  15840. if (this.allowUpsideDown && this.beta < 0) {
  15841. up = up.clone();
  15842. up = up.negate();
  15843. }
  15844. if (this.getScene().useRightHandedSystem) {
  15845. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15846. }
  15847. else {
  15848. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15849. }
  15850. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15851. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15852. }
  15853. this._currentTarget = target;
  15854. return this._viewMatrix;
  15855. };
  15856. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15857. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15858. meshes = meshes || this.getScene().meshes;
  15859. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15860. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15861. this.radius = distance * this.zoomOnFactor;
  15862. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15863. };
  15864. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15865. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15866. var meshesOrMinMaxVector;
  15867. var distance;
  15868. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15869. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15870. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15871. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15872. }
  15873. else {
  15874. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15875. distance = meshesOrMinMaxVectorAndDistance.distance;
  15876. }
  15877. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15878. if (!doNotUpdateMaxZ) {
  15879. this.maxZ = distance * 2;
  15880. }
  15881. };
  15882. /**
  15883. * @override
  15884. * Override Camera.createRigCamera
  15885. */
  15886. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15887. var alphaShift;
  15888. switch (this.cameraRigMode) {
  15889. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15892. case BABYLON.Camera.RIG_MODE_VR:
  15893. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15894. break;
  15895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15897. break;
  15898. }
  15899. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15900. rigCam._cameraRigParams = {};
  15901. return rigCam;
  15902. };
  15903. /**
  15904. * @override
  15905. * Override Camera._updateRigCameras
  15906. */
  15907. ArcRotateCamera.prototype._updateRigCameras = function () {
  15908. var camLeft = this._rigCameras[0];
  15909. var camRight = this._rigCameras[1];
  15910. camLeft.beta = camRight.beta = this.beta;
  15911. camLeft.radius = camRight.radius = this.radius;
  15912. switch (this.cameraRigMode) {
  15913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15916. case BABYLON.Camera.RIG_MODE_VR:
  15917. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15918. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15919. break;
  15920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15921. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15922. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15923. break;
  15924. }
  15925. _super.prototype._updateRigCameras.call(this);
  15926. };
  15927. ArcRotateCamera.prototype.dispose = function () {
  15928. this.inputs.clear();
  15929. _super.prototype.dispose.call(this);
  15930. };
  15931. ArcRotateCamera.prototype.getClassName = function () {
  15932. return "ArcRotateCamera";
  15933. };
  15934. __decorate([
  15935. BABYLON.serialize()
  15936. ], ArcRotateCamera.prototype, "alpha", void 0);
  15937. __decorate([
  15938. BABYLON.serialize()
  15939. ], ArcRotateCamera.prototype, "beta", void 0);
  15940. __decorate([
  15941. BABYLON.serialize()
  15942. ], ArcRotateCamera.prototype, "radius", void 0);
  15943. __decorate([
  15944. BABYLON.serializeAsVector3()
  15945. ], ArcRotateCamera.prototype, "target", void 0);
  15946. __decorate([
  15947. BABYLON.serialize()
  15948. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15949. __decorate([
  15950. BABYLON.serialize()
  15951. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15952. __decorate([
  15953. BABYLON.serialize()
  15954. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15955. __decorate([
  15956. BABYLON.serialize()
  15957. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15958. __decorate([
  15959. BABYLON.serialize()
  15960. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15961. __decorate([
  15962. BABYLON.serialize()
  15963. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15964. __decorate([
  15965. BABYLON.serialize()
  15966. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15967. __decorate([
  15968. BABYLON.serialize()
  15969. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15970. __decorate([
  15971. BABYLON.serialize()
  15972. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15973. __decorate([
  15974. BABYLON.serialize()
  15975. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15976. __decorate([
  15977. BABYLON.serialize()
  15978. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15979. __decorate([
  15980. BABYLON.serialize()
  15981. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15982. __decorate([
  15983. BABYLON.serialize()
  15984. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15985. return ArcRotateCamera;
  15986. }(BABYLON.TargetCamera));
  15987. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15988. })(BABYLON || (BABYLON = {}));
  15989. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  15990. var BABYLON;
  15991. (function (BABYLON) {
  15992. var ArcRotateCameraInputsManager = (function (_super) {
  15993. __extends(ArcRotateCameraInputsManager, _super);
  15994. function ArcRotateCameraInputsManager(camera) {
  15995. _super.call(this, camera);
  15996. }
  15997. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15998. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15999. return this;
  16000. };
  16001. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16002. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16003. return this;
  16004. };
  16005. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16006. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16007. return this;
  16008. };
  16009. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16010. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16011. return this;
  16012. };
  16013. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16014. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16015. return this;
  16016. };
  16017. return ArcRotateCameraInputsManager;
  16018. }(BABYLON.CameraInputsManager));
  16019. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16020. })(BABYLON || (BABYLON = {}));
  16021. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16022. var BABYLON;
  16023. (function (BABYLON) {
  16024. var RenderingManager = (function () {
  16025. function RenderingManager(scene) {
  16026. this._renderingGroups = new Array();
  16027. this._autoClearDepthStencil = {};
  16028. this._customOpaqueSortCompareFn = {};
  16029. this._customAlphaTestSortCompareFn = {};
  16030. this._customTransparentSortCompareFn = {};
  16031. this._renderinGroupInfo = null;
  16032. this._scene = scene;
  16033. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16034. this._autoClearDepthStencil[i] = true;
  16035. }
  16036. }
  16037. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  16038. if (this._scene._activeParticleSystems.length === 0) {
  16039. return;
  16040. }
  16041. // Particles
  16042. var activeCamera = this._scene.activeCamera;
  16043. this._scene._particlesDuration.beginMonitoring();
  16044. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16045. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16046. if (particleSystem.renderingGroupId !== index) {
  16047. continue;
  16048. }
  16049. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16050. continue;
  16051. }
  16052. this._clearDepthStencilBuffer();
  16053. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16054. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16055. }
  16056. }
  16057. this._scene._particlesDuration.endMonitoring(false);
  16058. };
  16059. RenderingManager.prototype._renderSprites = function (index) {
  16060. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  16061. return;
  16062. }
  16063. // Sprites
  16064. var activeCamera = this._scene.activeCamera;
  16065. this._scene._spritesDuration.beginMonitoring();
  16066. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  16067. var spriteManager = this._scene.spriteManagers[id];
  16068. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16069. this._clearDepthStencilBuffer();
  16070. spriteManager.render();
  16071. }
  16072. }
  16073. this._scene._spritesDuration.endMonitoring(false);
  16074. };
  16075. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  16076. if (this._depthStencilBufferAlreadyCleaned) {
  16077. return;
  16078. }
  16079. this._scene.getEngine().clear(0, false, true, true);
  16080. this._depthStencilBufferAlreadyCleaned = true;
  16081. };
  16082. RenderingManager.prototype._renderSpritesAndParticles = function () {
  16083. if (this._currentRenderSprites) {
  16084. this._renderSprites(this._currentIndex);
  16085. }
  16086. if (this._currentRenderParticles) {
  16087. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  16088. }
  16089. };
  16090. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16091. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16092. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16093. var info = null;
  16094. if (observable) {
  16095. if (!this._renderinGroupInfo) {
  16096. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16097. }
  16098. info = this._renderinGroupInfo;
  16099. info.scene = this._scene;
  16100. info.camera = this._scene.activeCamera;
  16101. }
  16102. this._currentActiveMeshes = activeMeshes;
  16103. this._currentRenderParticles = renderParticles;
  16104. this._currentRenderSprites = renderSprites;
  16105. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16106. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16107. var renderingGroup = this._renderingGroups[index];
  16108. var needToStepBack = false;
  16109. this._currentIndex = index;
  16110. if (renderingGroup) {
  16111. var renderingGroupMask = 0;
  16112. // Fire PRECLEAR stage
  16113. if (observable) {
  16114. renderingGroupMask = Math.pow(2, index);
  16115. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16116. info.renderingGroupId = index;
  16117. observable.notifyObservers(info, renderingGroupMask);
  16118. }
  16119. // Clear depth/stencil if needed
  16120. if (this._autoClearDepthStencil[index]) {
  16121. this._clearDepthStencilBuffer();
  16122. }
  16123. // Fire PREOPAQUE stage
  16124. if (observable) {
  16125. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16126. observable.notifyObservers(info, renderingGroupMask);
  16127. }
  16128. if (!renderingGroup.onBeforeTransparentRendering) {
  16129. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  16130. }
  16131. // Fire PRETRANSPARENT stage
  16132. if (observable) {
  16133. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16134. observable.notifyObservers(info, renderingGroupMask);
  16135. }
  16136. if (!renderingGroup.render(customRenderFunction)) {
  16137. this._renderingGroups.splice(index, 1);
  16138. needToStepBack = true;
  16139. this._renderSpritesAndParticles();
  16140. }
  16141. // Fire POSTTRANSPARENT stage
  16142. if (observable) {
  16143. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16144. observable.notifyObservers(info, renderingGroupMask);
  16145. }
  16146. }
  16147. else {
  16148. this._renderSpritesAndParticles();
  16149. if (observable) {
  16150. var renderingGroupMask = Math.pow(2, index);
  16151. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16152. info.renderingGroupId = index;
  16153. observable.notifyObservers(info, renderingGroupMask);
  16154. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16155. observable.notifyObservers(info, renderingGroupMask);
  16156. }
  16157. }
  16158. if (needToStepBack) {
  16159. index--;
  16160. }
  16161. }
  16162. };
  16163. RenderingManager.prototype.reset = function () {
  16164. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16165. var renderingGroup = this._renderingGroups[index];
  16166. if (renderingGroup) {
  16167. renderingGroup.prepare();
  16168. }
  16169. }
  16170. };
  16171. RenderingManager.prototype.dispatch = function (subMesh) {
  16172. var mesh = subMesh.getMesh();
  16173. var renderingGroupId = mesh.renderingGroupId || 0;
  16174. if (!this._renderingGroups[renderingGroupId]) {
  16175. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16176. }
  16177. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16178. };
  16179. /**
  16180. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16181. * This allowed control for front to back rendering or reversly depending of the special needs.
  16182. *
  16183. * @param renderingGroupId The rendering group id corresponding to its index
  16184. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16185. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16186. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16187. */
  16188. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16189. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16190. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16191. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16192. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16193. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16194. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16195. if (this._renderingGroups[renderingGroupId]) {
  16196. var group = this._renderingGroups[renderingGroupId];
  16197. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16198. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16199. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16200. }
  16201. };
  16202. /**
  16203. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16204. *
  16205. * @param renderingGroupId The rendering group id corresponding to its index
  16206. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16207. */
  16208. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  16209. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  16210. };
  16211. /**
  16212. * The max id used for rendering groups (not included)
  16213. */
  16214. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16215. /**
  16216. * The min id used for rendering groups (included)
  16217. */
  16218. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16219. return RenderingManager;
  16220. }());
  16221. BABYLON.RenderingManager = RenderingManager;
  16222. })(BABYLON || (BABYLON = {}));
  16223. //# sourceMappingURL=babylon.renderingManager.js.map
  16224. var BABYLON;
  16225. (function (BABYLON) {
  16226. var RenderingGroup = (function () {
  16227. /**
  16228. * Creates a new rendering group.
  16229. * @param index The rendering group index
  16230. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16231. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16232. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16233. */
  16234. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16235. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16236. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16237. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16238. this.index = index;
  16239. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16240. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16241. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16242. this._scene = scene;
  16243. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16244. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16245. this.transparentSortCompareFn = transparentSortCompareFn;
  16246. }
  16247. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16248. /**
  16249. * Set the opaque sort comparison function.
  16250. * If null the sub meshes will be render in the order they were created
  16251. */
  16252. set: function (value) {
  16253. this._opaqueSortCompareFn = value;
  16254. if (value) {
  16255. this._renderOpaque = this.renderOpaqueSorted;
  16256. }
  16257. else {
  16258. this._renderOpaque = RenderingGroup.renderUnsorted;
  16259. }
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16265. /**
  16266. * Set the alpha test sort comparison function.
  16267. * If null the sub meshes will be render in the order they were created
  16268. */
  16269. set: function (value) {
  16270. this._alphaTestSortCompareFn = value;
  16271. if (value) {
  16272. this._renderAlphaTest = this.renderAlphaTestSorted;
  16273. }
  16274. else {
  16275. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16276. }
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16282. /**
  16283. * Set the transparent sort comparison function.
  16284. * If null the sub meshes will be render in the order they were created
  16285. */
  16286. set: function (value) {
  16287. if (value) {
  16288. this._transparentSortCompareFn = value;
  16289. }
  16290. else {
  16291. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16292. }
  16293. this._renderTransparent = this.renderTransparentSorted;
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. /**
  16299. * Render all the sub meshes contained in the group.
  16300. * @param customRenderFunction Used to override the default render behaviour of the group.
  16301. * @returns true if rendered some submeshes.
  16302. */
  16303. RenderingGroup.prototype.render = function (customRenderFunction) {
  16304. if (customRenderFunction) {
  16305. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16306. return true;
  16307. }
  16308. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  16309. if (this.onBeforeTransparentRendering) {
  16310. this.onBeforeTransparentRendering();
  16311. }
  16312. return false;
  16313. }
  16314. var engine = this._scene.getEngine();
  16315. // Opaque
  16316. this._renderOpaque(this._opaqueSubMeshes);
  16317. // Alpha test
  16318. engine.setAlphaTesting(true);
  16319. this._renderAlphaTest(this._alphaTestSubMeshes);
  16320. engine.setAlphaTesting(false);
  16321. if (this.onBeforeTransparentRendering) {
  16322. this.onBeforeTransparentRendering();
  16323. }
  16324. // Transparent
  16325. this._renderTransparent(this._transparentSubMeshes);
  16326. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16327. return true;
  16328. };
  16329. /**
  16330. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16331. * @param subMeshes The submeshes to render
  16332. */
  16333. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16334. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16335. };
  16336. /**
  16337. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16338. * @param subMeshes The submeshes to render
  16339. */
  16340. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16341. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16342. };
  16343. /**
  16344. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16345. * @param subMeshes The submeshes to render
  16346. */
  16347. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16348. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16349. };
  16350. /**
  16351. * Renders the submeshes in a specified order.
  16352. * @param subMeshes The submeshes to sort before render
  16353. * @param sortCompareFn The comparison function use to sort
  16354. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16355. * @param transparent Specifies to activate blending if true
  16356. */
  16357. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16358. var subIndex = 0;
  16359. var subMesh;
  16360. for (; subIndex < subMeshes.length; subIndex++) {
  16361. subMesh = subMeshes.data[subIndex];
  16362. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16363. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16364. }
  16365. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16366. sortedArray.sort(sortCompareFn);
  16367. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16368. subMesh = sortedArray[subIndex];
  16369. subMesh.render(transparent);
  16370. }
  16371. };
  16372. /**
  16373. * Renders the submeshes in the order they were dispatched (no sort applied).
  16374. * @param subMeshes The submeshes to render
  16375. */
  16376. RenderingGroup.renderUnsorted = function (subMeshes) {
  16377. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16378. var submesh = subMeshes.data[subIndex];
  16379. submesh.render(false);
  16380. }
  16381. };
  16382. /**
  16383. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16384. * are rendered back to front if in the same alpha index.
  16385. *
  16386. * @param a The first submesh
  16387. * @param b The second submesh
  16388. * @returns The result of the comparison
  16389. */
  16390. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16391. // Alpha index first
  16392. if (a._alphaIndex > b._alphaIndex) {
  16393. return 1;
  16394. }
  16395. if (a._alphaIndex < b._alphaIndex) {
  16396. return -1;
  16397. }
  16398. // Then distance to camera
  16399. return RenderingGroup.backToFrontSortCompare(a, b);
  16400. };
  16401. /**
  16402. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16403. * are rendered back to front.
  16404. *
  16405. * @param a The first submesh
  16406. * @param b The second submesh
  16407. * @returns The result of the comparison
  16408. */
  16409. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16410. // Then distance to camera
  16411. if (a._distanceToCamera < b._distanceToCamera) {
  16412. return 1;
  16413. }
  16414. if (a._distanceToCamera > b._distanceToCamera) {
  16415. return -1;
  16416. }
  16417. return 0;
  16418. };
  16419. /**
  16420. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16421. * are rendered front to back (prevent overdraw).
  16422. *
  16423. * @param a The first submesh
  16424. * @param b The second submesh
  16425. * @returns The result of the comparison
  16426. */
  16427. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16428. // Then distance to camera
  16429. if (a._distanceToCamera < b._distanceToCamera) {
  16430. return -1;
  16431. }
  16432. if (a._distanceToCamera > b._distanceToCamera) {
  16433. return 1;
  16434. }
  16435. return 0;
  16436. };
  16437. /**
  16438. * Resets the different lists of submeshes to prepare a new frame.
  16439. */
  16440. RenderingGroup.prototype.prepare = function () {
  16441. this._opaqueSubMeshes.reset();
  16442. this._transparentSubMeshes.reset();
  16443. this._alphaTestSubMeshes.reset();
  16444. };
  16445. /**
  16446. * Inserts the submesh in its correct queue depending on its material.
  16447. * @param subMesh The submesh to dispatch
  16448. */
  16449. RenderingGroup.prototype.dispatch = function (subMesh) {
  16450. var material = subMesh.getMaterial();
  16451. var mesh = subMesh.getMesh();
  16452. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16453. this._transparentSubMeshes.push(subMesh);
  16454. }
  16455. else if (material.needAlphaTesting()) {
  16456. this._alphaTestSubMeshes.push(subMesh);
  16457. }
  16458. else {
  16459. this._opaqueSubMeshes.push(subMesh); // Opaque
  16460. }
  16461. };
  16462. return RenderingGroup;
  16463. }());
  16464. BABYLON.RenderingGroup = RenderingGroup;
  16465. })(BABYLON || (BABYLON = {}));
  16466. //# sourceMappingURL=babylon.renderingGroup.js.map
  16467. var BABYLON;
  16468. (function (BABYLON) {
  16469. var PointerEventTypes = (function () {
  16470. function PointerEventTypes() {
  16471. }
  16472. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16473. get: function () {
  16474. return PointerEventTypes._POINTERDOWN;
  16475. },
  16476. enumerable: true,
  16477. configurable: true
  16478. });
  16479. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16480. get: function () {
  16481. return PointerEventTypes._POINTERUP;
  16482. },
  16483. enumerable: true,
  16484. configurable: true
  16485. });
  16486. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16487. get: function () {
  16488. return PointerEventTypes._POINTERMOVE;
  16489. },
  16490. enumerable: true,
  16491. configurable: true
  16492. });
  16493. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16494. get: function () {
  16495. return PointerEventTypes._POINTERWHEEL;
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16501. get: function () {
  16502. return PointerEventTypes._POINTERPICK;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. PointerEventTypes._POINTERDOWN = 0x01;
  16508. PointerEventTypes._POINTERUP = 0x02;
  16509. PointerEventTypes._POINTERMOVE = 0x04;
  16510. PointerEventTypes._POINTERWHEEL = 0x08;
  16511. PointerEventTypes._POINTERPICK = 0x10;
  16512. return PointerEventTypes;
  16513. }());
  16514. BABYLON.PointerEventTypes = PointerEventTypes;
  16515. var PointerInfoBase = (function () {
  16516. function PointerInfoBase(type, event) {
  16517. this.type = type;
  16518. this.event = event;
  16519. }
  16520. return PointerInfoBase;
  16521. }());
  16522. BABYLON.PointerInfoBase = PointerInfoBase;
  16523. /**
  16524. * This class is used to store pointer related info for the onPrePointerObservable event.
  16525. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16526. */
  16527. var PointerInfoPre = (function (_super) {
  16528. __extends(PointerInfoPre, _super);
  16529. function PointerInfoPre(type, event, localX, localY) {
  16530. _super.call(this, type, event);
  16531. this.skipOnPointerObservable = false;
  16532. this.localPosition = new BABYLON.Vector2(localX, localY);
  16533. }
  16534. return PointerInfoPre;
  16535. }(PointerInfoBase));
  16536. BABYLON.PointerInfoPre = PointerInfoPre;
  16537. /**
  16538. * This type contains all the data related to a pointer event in Babylon.js.
  16539. * 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.
  16540. */
  16541. var PointerInfo = (function (_super) {
  16542. __extends(PointerInfo, _super);
  16543. function PointerInfo(type, event, pickInfo) {
  16544. _super.call(this, type, event);
  16545. this.pickInfo = pickInfo;
  16546. }
  16547. return PointerInfo;
  16548. }(PointerInfoBase));
  16549. BABYLON.PointerInfo = PointerInfo;
  16550. /**
  16551. * This class is used by the onRenderingGroupObservable
  16552. */
  16553. var RenderingGroupInfo = (function () {
  16554. function RenderingGroupInfo() {
  16555. }
  16556. /**
  16557. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16558. * This stage will be fired no matter what
  16559. */
  16560. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16561. /**
  16562. * Called before opaque object are rendered.
  16563. * This stage will be fired only if there's 3D Opaque content to render
  16564. */
  16565. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16566. /**
  16567. * Called after the opaque objects are rendered and before the transparent ones
  16568. * This stage will be fired only if there's 3D transparent content to render
  16569. */
  16570. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16571. /**
  16572. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16573. * This stage will be fired no matter what
  16574. */
  16575. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16576. return RenderingGroupInfo;
  16577. }());
  16578. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16579. /**
  16580. * Represents a scene to be rendered by the engine.
  16581. * @see http://doc.babylonjs.com/page.php?p=21911
  16582. */
  16583. var Scene = (function () {
  16584. /**
  16585. * @constructor
  16586. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16587. */
  16588. function Scene(engine) {
  16589. // Members
  16590. this.autoClear = true;
  16591. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16592. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16593. this.forceWireframe = false;
  16594. this.forcePointsCloud = false;
  16595. this.forceShowBoundingBoxes = false;
  16596. this.animationsEnabled = true;
  16597. this.constantlyUpdateMeshUnderPointer = false;
  16598. this.useRightHandedSystem = false;
  16599. this.hoverCursor = "pointer";
  16600. // Metadata
  16601. this.metadata = null;
  16602. // Events
  16603. /**
  16604. * An event triggered when the scene is disposed.
  16605. * @type {BABYLON.Observable}
  16606. */
  16607. this.onDisposeObservable = new BABYLON.Observable();
  16608. /**
  16609. * An event triggered before rendering the scene
  16610. * @type {BABYLON.Observable}
  16611. */
  16612. this.onBeforeRenderObservable = new BABYLON.Observable();
  16613. /**
  16614. * An event triggered after rendering the scene
  16615. * @type {BABYLON.Observable}
  16616. */
  16617. this.onAfterRenderObservable = new BABYLON.Observable();
  16618. /**
  16619. * An event triggered when the scene is ready
  16620. * @type {BABYLON.Observable}
  16621. */
  16622. this.onReadyObservable = new BABYLON.Observable();
  16623. /**
  16624. * An event triggered before rendering a camera
  16625. * @type {BABYLON.Observable}
  16626. */
  16627. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16628. /**
  16629. * An event triggered after rendering a camera
  16630. * @type {BABYLON.Observable}
  16631. */
  16632. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16633. /**
  16634. * An event triggered when a camera is created
  16635. * @type {BABYLON.Observable}
  16636. */
  16637. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16638. /**
  16639. * An event triggered when a camera is removed
  16640. * @type {BABYLON.Observable}
  16641. */
  16642. this.onCameraRemovedObservable = new BABYLON.Observable();
  16643. /**
  16644. * An event triggered when a light is created
  16645. * @type {BABYLON.Observable}
  16646. */
  16647. this.onNewLightAddedObservable = new BABYLON.Observable();
  16648. /**
  16649. * An event triggered when a light is removed
  16650. * @type {BABYLON.Observable}
  16651. */
  16652. this.onLightRemovedObservable = new BABYLON.Observable();
  16653. /**
  16654. * An event triggered when a geometry is created
  16655. * @type {BABYLON.Observable}
  16656. */
  16657. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16658. /**
  16659. * An event triggered when a geometry is removed
  16660. * @type {BABYLON.Observable}
  16661. */
  16662. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16663. /**
  16664. * An event triggered when a mesh is created
  16665. * @type {BABYLON.Observable}
  16666. */
  16667. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16668. /**
  16669. * An event triggered when a mesh is removed
  16670. * @type {BABYLON.Observable}
  16671. */
  16672. this.onMeshRemovedObservable = new BABYLON.Observable();
  16673. /**
  16674. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16675. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16676. * 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)
  16677. */
  16678. this.onRenderingGroupObservable = new BABYLON.Observable();
  16679. // Animations
  16680. this.animations = [];
  16681. /**
  16682. * 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).
  16683. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16684. */
  16685. this.onPrePointerObservable = new BABYLON.Observable();
  16686. /**
  16687. * Observable event triggered each time an input event is received from the rendering canvas
  16688. */
  16689. this.onPointerObservable = new BABYLON.Observable();
  16690. 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
  16691. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16692. this._startingPointerTime = 0;
  16693. // Fog
  16694. /**
  16695. * is fog enabled on this scene.
  16696. * @type {boolean}
  16697. */
  16698. this.fogEnabled = true;
  16699. this.fogMode = Scene.FOGMODE_NONE;
  16700. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16701. this.fogDensity = 0.1;
  16702. this.fogStart = 0;
  16703. this.fogEnd = 1000.0;
  16704. // Lights
  16705. /**
  16706. * is shadow enabled on this scene.
  16707. * @type {boolean}
  16708. */
  16709. this.shadowsEnabled = true;
  16710. /**
  16711. * is light enabled on this scene.
  16712. * @type {boolean}
  16713. */
  16714. this.lightsEnabled = true;
  16715. /**
  16716. * All of the lights added to this scene.
  16717. * @see BABYLON.Light
  16718. * @type {BABYLON.Light[]}
  16719. */
  16720. this.lights = new Array();
  16721. // Cameras
  16722. /**
  16723. * All of the cameras added to this scene.
  16724. * @see BABYLON.Camera
  16725. * @type {BABYLON.Camera[]}
  16726. */
  16727. this.cameras = new Array();
  16728. this.activeCameras = new Array();
  16729. // Meshes
  16730. /**
  16731. * All of the (abstract) meshes added to this scene.
  16732. * @see BABYLON.AbstractMesh
  16733. * @type {BABYLON.AbstractMesh[]}
  16734. */
  16735. this.meshes = new Array();
  16736. // Geometries
  16737. this._geometries = new Array();
  16738. this.materials = new Array();
  16739. this.multiMaterials = new Array();
  16740. // Textures
  16741. this.texturesEnabled = true;
  16742. this.textures = new Array();
  16743. // Particles
  16744. this.particlesEnabled = true;
  16745. this.particleSystems = new Array();
  16746. // Sprites
  16747. this.spritesEnabled = true;
  16748. this.spriteManagers = new Array();
  16749. // Layers
  16750. this.layers = new Array();
  16751. this.highlightLayers = new Array();
  16752. // Skeletons
  16753. this.skeletonsEnabled = true;
  16754. this.skeletons = new Array();
  16755. // Lens flares
  16756. this.lensFlaresEnabled = true;
  16757. this.lensFlareSystems = new Array();
  16758. // Collisions
  16759. this.collisionsEnabled = true;
  16760. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16761. // Postprocesses
  16762. this.postProcessesEnabled = true;
  16763. // Customs render targets
  16764. this.renderTargetsEnabled = true;
  16765. this.dumpNextRenderTargets = false;
  16766. this.customRenderTargets = new Array();
  16767. // Imported meshes
  16768. this.importedMeshesFiles = new Array();
  16769. // Probes
  16770. this.probesEnabled = true;
  16771. this.reflectionProbes = new Array();
  16772. this._actionManagers = new Array();
  16773. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16774. // Procedural textures
  16775. this.proceduralTexturesEnabled = true;
  16776. this._proceduralTextures = new Array();
  16777. this.soundTracks = new Array();
  16778. this._audioEnabled = true;
  16779. this._headphone = false;
  16780. // Performance counters
  16781. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16782. this._totalLightsCounter = new BABYLON.PerfCounter();
  16783. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16784. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16785. this._totalVertices = new BABYLON.PerfCounter();
  16786. this._activeIndices = new BABYLON.PerfCounter();
  16787. this._activeParticles = new BABYLON.PerfCounter();
  16788. this._lastFrameDuration = new BABYLON.PerfCounter();
  16789. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16790. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16791. this._particlesDuration = new BABYLON.PerfCounter();
  16792. this._renderDuration = new BABYLON.PerfCounter();
  16793. this._spritesDuration = new BABYLON.PerfCounter();
  16794. this._activeBones = new BABYLON.PerfCounter();
  16795. this._renderId = 0;
  16796. this._executeWhenReadyTimeoutId = -1;
  16797. this._intermediateRendering = false;
  16798. this._toBeDisposed = new BABYLON.SmartArray(256);
  16799. this._pendingData = []; //ANY
  16800. this._activeMeshes = new BABYLON.SmartArray(256);
  16801. this._processedMaterials = new BABYLON.SmartArray(256);
  16802. this._renderTargets = new BABYLON.SmartArray(256);
  16803. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16804. this._activeSkeletons = new BABYLON.SmartArray(32);
  16805. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16806. this._activeAnimatables = new Array();
  16807. this._transformMatrix = BABYLON.Matrix.Zero();
  16808. this._edgesRenderers = new BABYLON.SmartArray(16);
  16809. this._uniqueIdCounter = 0;
  16810. this._engine = engine;
  16811. engine.scenes.push(this);
  16812. this._externalData = new BABYLON.StringDictionary();
  16813. this._uid = null;
  16814. this._renderingManager = new BABYLON.RenderingManager(this);
  16815. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16816. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16817. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16818. if (BABYLON.OutlineRenderer) {
  16819. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16820. }
  16821. this.attachControl();
  16822. if (BABYLON.SoundTrack) {
  16823. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16824. }
  16825. //simplification queue
  16826. if (BABYLON.SimplificationQueue) {
  16827. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16828. }
  16829. //collision coordinator initialization. For now legacy per default.
  16830. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16831. }
  16832. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16833. get: function () {
  16834. return Scene._FOGMODE_NONE;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16840. get: function () {
  16841. return Scene._FOGMODE_EXP;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16847. get: function () {
  16848. return Scene._FOGMODE_EXP2;
  16849. },
  16850. enumerable: true,
  16851. configurable: true
  16852. });
  16853. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16854. get: function () {
  16855. return Scene._FOGMODE_LINEAR;
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(Scene.prototype, "onDispose", {
  16861. set: function (callback) {
  16862. if (this._onDisposeObserver) {
  16863. this.onDisposeObservable.remove(this._onDisposeObserver);
  16864. }
  16865. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. Object.defineProperty(Scene.prototype, "beforeRender", {
  16871. set: function (callback) {
  16872. if (this._onBeforeRenderObserver) {
  16873. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16874. }
  16875. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16876. },
  16877. enumerable: true,
  16878. configurable: true
  16879. });
  16880. Object.defineProperty(Scene.prototype, "afterRender", {
  16881. set: function (callback) {
  16882. if (this._onAfterRenderObserver) {
  16883. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16884. }
  16885. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16886. },
  16887. enumerable: true,
  16888. configurable: true
  16889. });
  16890. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16891. set: function (callback) {
  16892. if (this._onBeforeCameraRenderObserver) {
  16893. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16894. }
  16895. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16901. set: function (callback) {
  16902. if (this._onAfterCameraRenderObserver) {
  16903. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16904. }
  16905. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16911. get: function () {
  16912. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16918. get: function () {
  16919. if (!this._defaultMaterial) {
  16920. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16921. }
  16922. return this._defaultMaterial;
  16923. },
  16924. enumerable: true,
  16925. configurable: true
  16926. });
  16927. Object.defineProperty(Scene.prototype, "debugLayer", {
  16928. // Properties
  16929. get: function () {
  16930. if (!this._debugLayer) {
  16931. this._debugLayer = new BABYLON.DebugLayer(this);
  16932. }
  16933. return this._debugLayer;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16939. get: function () {
  16940. return this._workerCollisions;
  16941. },
  16942. set: function (enabled) {
  16943. enabled = (enabled && !!Worker);
  16944. this._workerCollisions = enabled;
  16945. if (this.collisionCoordinator) {
  16946. this.collisionCoordinator.destroy();
  16947. }
  16948. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16949. this.collisionCoordinator.init(this);
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16955. get: function () {
  16956. return this._selectionOctree;
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16962. /**
  16963. * The mesh that is currently under the pointer.
  16964. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16965. */
  16966. get: function () {
  16967. return this._pointerOverMesh;
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(Scene.prototype, "pointerX", {
  16973. /**
  16974. * Current on-screen X position of the pointer
  16975. * @return {number} X position of the pointer
  16976. */
  16977. get: function () {
  16978. return this._pointerX;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Object.defineProperty(Scene.prototype, "pointerY", {
  16984. /**
  16985. * Current on-screen Y position of the pointer
  16986. * @return {number} Y position of the pointer
  16987. */
  16988. get: function () {
  16989. return this._pointerY;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Scene.prototype.getCachedMaterial = function () {
  16995. return this._cachedMaterial;
  16996. };
  16997. Scene.prototype.getBoundingBoxRenderer = function () {
  16998. return this._boundingBoxRenderer;
  16999. };
  17000. Scene.prototype.getOutlineRenderer = function () {
  17001. return this._outlineRenderer;
  17002. };
  17003. Scene.prototype.getEngine = function () {
  17004. return this._engine;
  17005. };
  17006. Scene.prototype.getTotalVertices = function () {
  17007. return this._totalVertices.current;
  17008. };
  17009. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17010. get: function () {
  17011. return this._totalVertices;
  17012. },
  17013. enumerable: true,
  17014. configurable: true
  17015. });
  17016. Scene.prototype.getActiveIndices = function () {
  17017. return this._activeIndices.current;
  17018. };
  17019. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17020. get: function () {
  17021. return this._activeIndices;
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. Scene.prototype.getActiveParticles = function () {
  17027. return this._activeParticles.current;
  17028. };
  17029. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17030. get: function () {
  17031. return this._activeParticles;
  17032. },
  17033. enumerable: true,
  17034. configurable: true
  17035. });
  17036. Scene.prototype.getActiveBones = function () {
  17037. return this._activeBones.current;
  17038. };
  17039. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17040. get: function () {
  17041. return this._activeBones;
  17042. },
  17043. enumerable: true,
  17044. configurable: true
  17045. });
  17046. // Stats
  17047. Scene.prototype.getLastFrameDuration = function () {
  17048. return this._lastFrameDuration.current;
  17049. };
  17050. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17051. get: function () {
  17052. return this._lastFrameDuration;
  17053. },
  17054. enumerable: true,
  17055. configurable: true
  17056. });
  17057. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17058. return this._evaluateActiveMeshesDuration.current;
  17059. };
  17060. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17061. get: function () {
  17062. return this._evaluateActiveMeshesDuration;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Scene.prototype.getActiveMeshes = function () {
  17068. return this._activeMeshes;
  17069. };
  17070. Scene.prototype.getRenderTargetsDuration = function () {
  17071. return this._renderTargetsDuration.current;
  17072. };
  17073. Scene.prototype.getRenderDuration = function () {
  17074. return this._renderDuration.current;
  17075. };
  17076. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17077. get: function () {
  17078. return this._renderDuration;
  17079. },
  17080. enumerable: true,
  17081. configurable: true
  17082. });
  17083. Scene.prototype.getParticlesDuration = function () {
  17084. return this._particlesDuration.current;
  17085. };
  17086. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17087. get: function () {
  17088. return this._particlesDuration;
  17089. },
  17090. enumerable: true,
  17091. configurable: true
  17092. });
  17093. Scene.prototype.getSpritesDuration = function () {
  17094. return this._spritesDuration.current;
  17095. };
  17096. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17097. get: function () {
  17098. return this._spritesDuration;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Scene.prototype.getAnimationRatio = function () {
  17104. return this._animationRatio;
  17105. };
  17106. Scene.prototype.getRenderId = function () {
  17107. return this._renderId;
  17108. };
  17109. Scene.prototype.incrementRenderId = function () {
  17110. this._renderId++;
  17111. };
  17112. Scene.prototype._updatePointerPosition = function (evt) {
  17113. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17114. this._pointerX = evt.clientX - canvasRect.left;
  17115. this._pointerY = evt.clientY - canvasRect.top;
  17116. this._unTranslatedPointerX = this._pointerX;
  17117. this._unTranslatedPointerY = this._pointerY;
  17118. if (this.cameraToUseForPointers) {
  17119. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17120. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17121. }
  17122. };
  17123. // Pointers handling
  17124. /**
  17125. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17126. * @param attachUp defines if you want to attach events to pointerup
  17127. * @param attachDown defines if you want to attach events to pointerdown
  17128. * @param attachMove defines if you want to attach events to pointermove
  17129. */
  17130. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17131. var _this = this;
  17132. if (attachUp === void 0) { attachUp = true; }
  17133. if (attachDown === void 0) { attachDown = true; }
  17134. if (attachMove === void 0) { attachMove = true; }
  17135. var spritePredicate = function (sprite) {
  17136. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17137. };
  17138. this._onPointerMove = function (evt) {
  17139. _this._updatePointerPosition(evt);
  17140. // PreObservable support
  17141. if (_this.onPrePointerObservable.hasObservers()) {
  17142. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17143. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17144. _this.onPrePointerObservable.notifyObservers(pi, type);
  17145. if (pi.skipOnPointerObservable) {
  17146. return;
  17147. }
  17148. }
  17149. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17150. return;
  17151. }
  17152. var canvas = _this._engine.getRenderingCanvas();
  17153. if (!_this.pointerMovePredicate) {
  17154. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17155. }
  17156. // Meshes
  17157. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17158. if (pickResult.hit && pickResult.pickedMesh) {
  17159. _this.setPointerOverSprite(null);
  17160. _this.setPointerOverMesh(pickResult.pickedMesh);
  17161. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17162. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17163. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17164. }
  17165. else {
  17166. canvas.style.cursor = _this.hoverCursor;
  17167. }
  17168. }
  17169. else {
  17170. canvas.style.cursor = "";
  17171. }
  17172. }
  17173. else {
  17174. _this.setPointerOverMesh(null);
  17175. // Sprites
  17176. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17177. if (pickResult.hit && pickResult.pickedSprite) {
  17178. _this.setPointerOverSprite(pickResult.pickedSprite);
  17179. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17180. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17181. }
  17182. else {
  17183. canvas.style.cursor = _this.hoverCursor;
  17184. }
  17185. }
  17186. else {
  17187. _this.setPointerOverSprite(null);
  17188. // Restore pointer
  17189. canvas.style.cursor = "";
  17190. }
  17191. }
  17192. if (_this.onPointerMove) {
  17193. _this.onPointerMove(evt, pickResult);
  17194. }
  17195. if (_this.onPointerObservable.hasObservers()) {
  17196. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17197. var pi = new PointerInfo(type, evt, pickResult);
  17198. _this.onPointerObservable.notifyObservers(pi, type);
  17199. }
  17200. };
  17201. this._onPointerDown = function (evt) {
  17202. _this._updatePointerPosition(evt);
  17203. // PreObservable support
  17204. if (_this.onPrePointerObservable.hasObservers()) {
  17205. var type = PointerEventTypes.POINTERDOWN;
  17206. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17207. _this.onPrePointerObservable.notifyObservers(pi, type);
  17208. if (pi.skipOnPointerObservable) {
  17209. return;
  17210. }
  17211. }
  17212. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17213. return;
  17214. }
  17215. _this._startingPointerPosition.x = _this._pointerX;
  17216. _this._startingPointerPosition.y = _this._pointerY;
  17217. _this._startingPointerTime = new Date().getTime();
  17218. if (!_this.pointerDownPredicate) {
  17219. _this.pointerDownPredicate = function (mesh) {
  17220. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17221. };
  17222. }
  17223. // Meshes
  17224. _this._pickedDownMesh = null;
  17225. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17226. if (pickResult.hit && pickResult.pickedMesh) {
  17227. if (pickResult.pickedMesh.actionManager) {
  17228. _this._pickedDownMesh = pickResult.pickedMesh;
  17229. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17230. switch (evt.button) {
  17231. case 0:
  17232. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17233. break;
  17234. case 1:
  17235. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17236. break;
  17237. case 2:
  17238. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17239. break;
  17240. }
  17241. if (pickResult.pickedMesh.actionManager) {
  17242. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17243. }
  17244. }
  17245. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17246. var that = _this;
  17247. window.setTimeout(function () {
  17248. 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);
  17249. if (pickResult.hit && pickResult.pickedMesh) {
  17250. if (pickResult.pickedMesh.actionManager) {
  17251. 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)) {
  17252. that._startingPointerTime = 0;
  17253. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17254. }
  17255. }
  17256. }
  17257. }, BABYLON.ActionManager.LongPressDelay);
  17258. }
  17259. }
  17260. }
  17261. if (_this.onPointerDown) {
  17262. _this.onPointerDown(evt, pickResult);
  17263. }
  17264. if (_this.onPointerObservable.hasObservers()) {
  17265. var type = PointerEventTypes.POINTERDOWN;
  17266. var pi = new PointerInfo(type, evt, pickResult);
  17267. _this.onPointerObservable.notifyObservers(pi, type);
  17268. }
  17269. // Sprites
  17270. _this._pickedDownSprite = null;
  17271. if (_this.spriteManagers.length > 0) {
  17272. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17273. if (pickResult.hit && pickResult.pickedSprite) {
  17274. if (pickResult.pickedSprite.actionManager) {
  17275. _this._pickedDownSprite = pickResult.pickedSprite;
  17276. switch (evt.button) {
  17277. case 0:
  17278. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17279. break;
  17280. case 1:
  17281. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17282. break;
  17283. case 2:
  17284. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17285. break;
  17286. }
  17287. if (pickResult.pickedSprite.actionManager) {
  17288. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17289. }
  17290. }
  17291. }
  17292. }
  17293. };
  17294. this._onPointerUp = function (evt) {
  17295. _this._updatePointerPosition(evt);
  17296. // PreObservable support
  17297. if (_this.onPrePointerObservable.hasObservers()) {
  17298. var type = PointerEventTypes.POINTERUP;
  17299. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17300. _this.onPrePointerObservable.notifyObservers(pi, type);
  17301. if (pi.skipOnPointerObservable) {
  17302. return;
  17303. }
  17304. }
  17305. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17306. return;
  17307. }
  17308. if (!_this.pointerUpPredicate) {
  17309. _this.pointerUpPredicate = function (mesh) {
  17310. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17311. };
  17312. }
  17313. // Meshes
  17314. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17315. if (pickResult.hit && pickResult.pickedMesh) {
  17316. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17317. if (_this.onPointerPick) {
  17318. _this.onPointerPick(evt, pickResult);
  17319. }
  17320. if (_this.onPointerObservable.hasObservers()) {
  17321. var type = PointerEventTypes.POINTERPICK;
  17322. var pi = new PointerInfo(type, evt, pickResult);
  17323. _this.onPointerObservable.notifyObservers(pi, type);
  17324. }
  17325. }
  17326. if (pickResult.pickedMesh.actionManager) {
  17327. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17328. if (pickResult.pickedMesh.actionManager) {
  17329. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17330. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17331. }
  17332. }
  17333. }
  17334. }
  17335. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17336. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17337. }
  17338. if (_this.onPointerUp) {
  17339. _this.onPointerUp(evt, pickResult);
  17340. }
  17341. if (_this.onPointerObservable.hasObservers()) {
  17342. var type = PointerEventTypes.POINTERUP;
  17343. var pi = new PointerInfo(type, evt, pickResult);
  17344. _this.onPointerObservable.notifyObservers(pi, type);
  17345. }
  17346. _this._startingPointerTime = 0;
  17347. // Sprites
  17348. if (_this.spriteManagers.length > 0) {
  17349. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17350. if (pickResult.hit && pickResult.pickedSprite) {
  17351. if (pickResult.pickedSprite.actionManager) {
  17352. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17353. if (pickResult.pickedSprite.actionManager) {
  17354. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17355. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17356. }
  17357. }
  17358. }
  17359. }
  17360. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17361. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17362. }
  17363. }
  17364. };
  17365. this._onKeyDown = function (evt) {
  17366. if (_this.actionManager) {
  17367. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17368. }
  17369. };
  17370. this._onKeyUp = function (evt) {
  17371. if (_this.actionManager) {
  17372. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17373. }
  17374. };
  17375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17376. var canvas = this._engine.getRenderingCanvas();
  17377. if (attachMove) {
  17378. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17379. // Wheel
  17380. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17381. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17382. }
  17383. if (attachDown) {
  17384. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17385. }
  17386. if (attachUp) {
  17387. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17388. }
  17389. canvas.tabIndex = 1;
  17390. canvas.addEventListener("keydown", this._onKeyDown, false);
  17391. canvas.addEventListener("keyup", this._onKeyUp, false);
  17392. };
  17393. Scene.prototype.detachControl = function () {
  17394. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17395. var canvas = this._engine.getRenderingCanvas();
  17396. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17397. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17398. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17399. // Wheel
  17400. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17401. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17402. canvas.removeEventListener("keydown", this._onKeyDown);
  17403. canvas.removeEventListener("keyup", this._onKeyUp);
  17404. };
  17405. // Ready
  17406. Scene.prototype.isReady = function () {
  17407. if (this._pendingData.length > 0) {
  17408. return false;
  17409. }
  17410. var index;
  17411. for (index = 0; index < this._geometries.length; index++) {
  17412. var geometry = this._geometries[index];
  17413. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17414. return false;
  17415. }
  17416. }
  17417. for (index = 0; index < this.meshes.length; index++) {
  17418. var mesh = this.meshes[index];
  17419. if (!mesh.isReady()) {
  17420. return false;
  17421. }
  17422. var mat = mesh.material;
  17423. if (mat) {
  17424. if (!mat.isReady(mesh)) {
  17425. return false;
  17426. }
  17427. }
  17428. }
  17429. return true;
  17430. };
  17431. Scene.prototype.resetCachedMaterial = function () {
  17432. this._cachedMaterial = null;
  17433. };
  17434. Scene.prototype.registerBeforeRender = function (func) {
  17435. this.onBeforeRenderObservable.add(func);
  17436. };
  17437. Scene.prototype.unregisterBeforeRender = function (func) {
  17438. this.onBeforeRenderObservable.removeCallback(func);
  17439. };
  17440. Scene.prototype.registerAfterRender = function (func) {
  17441. this.onAfterRenderObservable.add(func);
  17442. };
  17443. Scene.prototype.unregisterAfterRender = function (func) {
  17444. this.onAfterRenderObservable.removeCallback(func);
  17445. };
  17446. Scene.prototype._addPendingData = function (data) {
  17447. this._pendingData.push(data);
  17448. };
  17449. Scene.prototype._removePendingData = function (data) {
  17450. var index = this._pendingData.indexOf(data);
  17451. if (index !== -1) {
  17452. this._pendingData.splice(index, 1);
  17453. }
  17454. };
  17455. Scene.prototype.getWaitingItemsCount = function () {
  17456. return this._pendingData.length;
  17457. };
  17458. /**
  17459. * Registers a function to be executed when the scene is ready.
  17460. * @param {Function} func - the function to be executed.
  17461. */
  17462. Scene.prototype.executeWhenReady = function (func) {
  17463. var _this = this;
  17464. this.onReadyObservable.add(func);
  17465. if (this._executeWhenReadyTimeoutId !== -1) {
  17466. return;
  17467. }
  17468. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17469. _this._checkIsReady();
  17470. }, 150);
  17471. };
  17472. Scene.prototype._checkIsReady = function () {
  17473. var _this = this;
  17474. if (this.isReady()) {
  17475. this.onReadyObservable.notifyObservers(this);
  17476. this.onReadyObservable.clear();
  17477. this._executeWhenReadyTimeoutId = -1;
  17478. return;
  17479. }
  17480. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17481. _this._checkIsReady();
  17482. }, 150);
  17483. };
  17484. // Animations
  17485. /**
  17486. * Will start the animation sequence of a given target
  17487. * @param target - the target
  17488. * @param {number} from - from which frame should animation start
  17489. * @param {number} to - till which frame should animation run.
  17490. * @param {boolean} [loop] - should the animation loop
  17491. * @param {number} [speedRatio] - the speed in which to run the animation
  17492. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17493. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17494. * @return {BABYLON.Animatable} the animatable object created for this animation
  17495. * @see BABYLON.Animatable
  17496. * @see http://doc.babylonjs.com/page.php?p=22081
  17497. */
  17498. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17499. if (speedRatio === void 0) { speedRatio = 1.0; }
  17500. this.stopAnimation(target);
  17501. if (!animatable) {
  17502. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17503. }
  17504. // Local animations
  17505. if (target.animations) {
  17506. animatable.appendAnimations(target, target.animations);
  17507. }
  17508. // Children animations
  17509. if (target.getAnimatables) {
  17510. var animatables = target.getAnimatables();
  17511. for (var index = 0; index < animatables.length; index++) {
  17512. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17513. }
  17514. }
  17515. animatable.reset();
  17516. return animatable;
  17517. };
  17518. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17519. if (speedRatio === undefined) {
  17520. speedRatio = 1.0;
  17521. }
  17522. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17523. return animatable;
  17524. };
  17525. Scene.prototype.getAnimatableByTarget = function (target) {
  17526. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17527. if (this._activeAnimatables[index].target === target) {
  17528. return this._activeAnimatables[index];
  17529. }
  17530. }
  17531. return null;
  17532. };
  17533. Object.defineProperty(Scene.prototype, "Animatables", {
  17534. get: function () {
  17535. return this._activeAnimatables;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. /**
  17541. * Will stop the animation of the given target
  17542. * @param target - the target
  17543. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17544. * @see beginAnimation
  17545. */
  17546. Scene.prototype.stopAnimation = function (target, animationName) {
  17547. var animatable = this.getAnimatableByTarget(target);
  17548. if (animatable) {
  17549. animatable.stop(animationName);
  17550. }
  17551. };
  17552. Scene.prototype._animate = function () {
  17553. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17554. return;
  17555. }
  17556. if (!this._animationStartDate) {
  17557. if (this._pendingData.length > 0) {
  17558. return;
  17559. }
  17560. this._animationStartDate = BABYLON.Tools.Now;
  17561. }
  17562. // Getting time
  17563. var now = BABYLON.Tools.Now;
  17564. var delay = now - this._animationStartDate;
  17565. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17566. this._activeAnimatables[index]._animate(delay);
  17567. }
  17568. };
  17569. // Matrix
  17570. Scene.prototype.getViewMatrix = function () {
  17571. return this._viewMatrix;
  17572. };
  17573. Scene.prototype.getProjectionMatrix = function () {
  17574. return this._projectionMatrix;
  17575. };
  17576. Scene.prototype.getTransformMatrix = function () {
  17577. return this._transformMatrix;
  17578. };
  17579. Scene.prototype.setTransformMatrix = function (view, projection) {
  17580. this._viewMatrix = view;
  17581. this._projectionMatrix = projection;
  17582. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17583. // Update frustum
  17584. if (!this._frustumPlanes) {
  17585. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17586. }
  17587. else {
  17588. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17589. }
  17590. };
  17591. // Methods
  17592. Scene.prototype.addMesh = function (newMesh) {
  17593. newMesh.uniqueId = this._uniqueIdCounter++;
  17594. var position = this.meshes.push(newMesh);
  17595. //notify the collision coordinator
  17596. this.collisionCoordinator.onMeshAdded(newMesh);
  17597. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17598. };
  17599. Scene.prototype.removeMesh = function (toRemove) {
  17600. var index = this.meshes.indexOf(toRemove);
  17601. if (index !== -1) {
  17602. // Remove from the scene if mesh found
  17603. this.meshes.splice(index, 1);
  17604. }
  17605. //notify the collision coordinator
  17606. this.collisionCoordinator.onMeshRemoved(toRemove);
  17607. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17608. return index;
  17609. };
  17610. Scene.prototype.removeSkeleton = function (toRemove) {
  17611. var index = this.skeletons.indexOf(toRemove);
  17612. if (index !== -1) {
  17613. // Remove from the scene if mesh found
  17614. this.skeletons.splice(index, 1);
  17615. }
  17616. return index;
  17617. };
  17618. Scene.prototype.removeLight = function (toRemove) {
  17619. var index = this.lights.indexOf(toRemove);
  17620. if (index !== -1) {
  17621. // Remove from the scene if mesh found
  17622. this.lights.splice(index, 1);
  17623. }
  17624. this.onLightRemovedObservable.notifyObservers(toRemove);
  17625. return index;
  17626. };
  17627. Scene.prototype.removeCamera = function (toRemove) {
  17628. var index = this.cameras.indexOf(toRemove);
  17629. if (index !== -1) {
  17630. // Remove from the scene if mesh found
  17631. this.cameras.splice(index, 1);
  17632. }
  17633. // Remove from activeCameras
  17634. var index2 = this.activeCameras.indexOf(toRemove);
  17635. if (index2 !== -1) {
  17636. // Remove from the scene if mesh found
  17637. this.activeCameras.splice(index2, 1);
  17638. }
  17639. // Reset the activeCamera
  17640. if (this.activeCamera === toRemove) {
  17641. if (this.cameras.length > 0) {
  17642. this.activeCamera = this.cameras[0];
  17643. }
  17644. else {
  17645. this.activeCamera = null;
  17646. }
  17647. }
  17648. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17649. return index;
  17650. };
  17651. Scene.prototype.addLight = function (newLight) {
  17652. newLight.uniqueId = this._uniqueIdCounter++;
  17653. var position = this.lights.push(newLight);
  17654. this.onNewLightAddedObservable.notifyObservers(newLight);
  17655. };
  17656. Scene.prototype.addCamera = function (newCamera) {
  17657. newCamera.uniqueId = this._uniqueIdCounter++;
  17658. var position = this.cameras.push(newCamera);
  17659. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17660. };
  17661. /**
  17662. * Switch active camera
  17663. * @param {Camera} newCamera - new active camera
  17664. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17665. */
  17666. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17667. if (attachControl === void 0) { attachControl = true; }
  17668. var canvas = this._engine.getRenderingCanvas();
  17669. this.activeCamera.detachControl(canvas);
  17670. this.activeCamera = newCamera;
  17671. if (attachControl) {
  17672. newCamera.attachControl(canvas);
  17673. }
  17674. };
  17675. /**
  17676. * sets the active camera of the scene using its ID
  17677. * @param {string} id - the camera's ID
  17678. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17679. * @see activeCamera
  17680. */
  17681. Scene.prototype.setActiveCameraByID = function (id) {
  17682. var camera = this.getCameraByID(id);
  17683. if (camera) {
  17684. this.activeCamera = camera;
  17685. return camera;
  17686. }
  17687. return null;
  17688. };
  17689. /**
  17690. * sets the active camera of the scene using its name
  17691. * @param {string} name - the camera's name
  17692. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17693. * @see activeCamera
  17694. */
  17695. Scene.prototype.setActiveCameraByName = function (name) {
  17696. var camera = this.getCameraByName(name);
  17697. if (camera) {
  17698. this.activeCamera = camera;
  17699. return camera;
  17700. }
  17701. return null;
  17702. };
  17703. /**
  17704. * get a material using its id
  17705. * @param {string} the material's ID
  17706. * @return {BABYLON.Material|null} the material or null if none found.
  17707. */
  17708. Scene.prototype.getMaterialByID = function (id) {
  17709. for (var index = 0; index < this.materials.length; index++) {
  17710. if (this.materials[index].id === id) {
  17711. return this.materials[index];
  17712. }
  17713. }
  17714. return null;
  17715. };
  17716. /**
  17717. * get a material using its name
  17718. * @param {string} the material's name
  17719. * @return {BABYLON.Material|null} the material or null if none found.
  17720. */
  17721. Scene.prototype.getMaterialByName = function (name) {
  17722. for (var index = 0; index < this.materials.length; index++) {
  17723. if (this.materials[index].name === name) {
  17724. return this.materials[index];
  17725. }
  17726. }
  17727. return null;
  17728. };
  17729. Scene.prototype.getLensFlareSystemByName = function (name) {
  17730. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17731. if (this.lensFlareSystems[index].name === name) {
  17732. return this.lensFlareSystems[index];
  17733. }
  17734. }
  17735. return null;
  17736. };
  17737. Scene.prototype.getLensFlareSystemByID = function (id) {
  17738. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17739. if (this.lensFlareSystems[index].id === id) {
  17740. return this.lensFlareSystems[index];
  17741. }
  17742. }
  17743. return null;
  17744. };
  17745. Scene.prototype.getCameraByID = function (id) {
  17746. for (var index = 0; index < this.cameras.length; index++) {
  17747. if (this.cameras[index].id === id) {
  17748. return this.cameras[index];
  17749. }
  17750. }
  17751. return null;
  17752. };
  17753. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17754. for (var index = 0; index < this.cameras.length; index++) {
  17755. if (this.cameras[index].uniqueId === uniqueId) {
  17756. return this.cameras[index];
  17757. }
  17758. }
  17759. return null;
  17760. };
  17761. /**
  17762. * get a camera using its name
  17763. * @param {string} the camera's name
  17764. * @return {BABYLON.Camera|null} the camera or null if none found.
  17765. */
  17766. Scene.prototype.getCameraByName = function (name) {
  17767. for (var index = 0; index < this.cameras.length; index++) {
  17768. if (this.cameras[index].name === name) {
  17769. return this.cameras[index];
  17770. }
  17771. }
  17772. return null;
  17773. };
  17774. /**
  17775. * get a bone using its id
  17776. * @param {string} the bone's id
  17777. * @return {BABYLON.Bone|null} the bone or null if not found
  17778. */
  17779. Scene.prototype.getBoneByID = function (id) {
  17780. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17781. var skeleton = this.skeletons[skeletonIndex];
  17782. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17783. if (skeleton.bones[boneIndex].id === id) {
  17784. return skeleton.bones[boneIndex];
  17785. }
  17786. }
  17787. }
  17788. return null;
  17789. };
  17790. /**
  17791. * get a bone using its id
  17792. * @param {string} the bone's name
  17793. * @return {BABYLON.Bone|null} the bone or null if not found
  17794. */
  17795. Scene.prototype.getBoneByName = function (name) {
  17796. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17797. var skeleton = this.skeletons[skeletonIndex];
  17798. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17799. if (skeleton.bones[boneIndex].name === name) {
  17800. return skeleton.bones[boneIndex];
  17801. }
  17802. }
  17803. }
  17804. return null;
  17805. };
  17806. /**
  17807. * get a light node using its name
  17808. * @param {string} the light's name
  17809. * @return {BABYLON.Light|null} the light or null if none found.
  17810. */
  17811. Scene.prototype.getLightByName = function (name) {
  17812. for (var index = 0; index < this.lights.length; index++) {
  17813. if (this.lights[index].name === name) {
  17814. return this.lights[index];
  17815. }
  17816. }
  17817. return null;
  17818. };
  17819. /**
  17820. * get a light node using its ID
  17821. * @param {string} the light's id
  17822. * @return {BABYLON.Light|null} the light or null if none found.
  17823. */
  17824. Scene.prototype.getLightByID = function (id) {
  17825. for (var index = 0; index < this.lights.length; index++) {
  17826. if (this.lights[index].id === id) {
  17827. return this.lights[index];
  17828. }
  17829. }
  17830. return null;
  17831. };
  17832. /**
  17833. * get a light node using its scene-generated unique ID
  17834. * @param {number} the light's unique id
  17835. * @return {BABYLON.Light|null} the light or null if none found.
  17836. */
  17837. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17838. for (var index = 0; index < this.lights.length; index++) {
  17839. if (this.lights[index].uniqueId === uniqueId) {
  17840. return this.lights[index];
  17841. }
  17842. }
  17843. return null;
  17844. };
  17845. /**
  17846. * get a particle system by id
  17847. * @param id {number} the particle system id
  17848. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17849. */
  17850. Scene.prototype.getParticleSystemByID = function (id) {
  17851. for (var index = 0; index < this.particleSystems.length; index++) {
  17852. if (this.particleSystems[index].id === id) {
  17853. return this.particleSystems[index];
  17854. }
  17855. }
  17856. return null;
  17857. };
  17858. /**
  17859. * get a geometry using its ID
  17860. * @param {string} the geometry's id
  17861. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17862. */
  17863. Scene.prototype.getGeometryByID = function (id) {
  17864. for (var index = 0; index < this._geometries.length; index++) {
  17865. if (this._geometries[index].id === id) {
  17866. return this._geometries[index];
  17867. }
  17868. }
  17869. return null;
  17870. };
  17871. /**
  17872. * add a new geometry to this scene.
  17873. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17874. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17875. * @return {boolean} was the geometry added or not
  17876. */
  17877. Scene.prototype.pushGeometry = function (geometry, force) {
  17878. if (!force && this.getGeometryByID(geometry.id)) {
  17879. return false;
  17880. }
  17881. this._geometries.push(geometry);
  17882. //notify the collision coordinator
  17883. this.collisionCoordinator.onGeometryAdded(geometry);
  17884. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17885. return true;
  17886. };
  17887. /**
  17888. * Removes an existing geometry
  17889. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17890. * @return {boolean} was the geometry removed or not
  17891. */
  17892. Scene.prototype.removeGeometry = function (geometry) {
  17893. var index = this._geometries.indexOf(geometry);
  17894. if (index > -1) {
  17895. this._geometries.splice(index, 1);
  17896. //notify the collision coordinator
  17897. this.collisionCoordinator.onGeometryDeleted(geometry);
  17898. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17899. return true;
  17900. }
  17901. return false;
  17902. };
  17903. Scene.prototype.getGeometries = function () {
  17904. return this._geometries;
  17905. };
  17906. /**
  17907. * Get the first added mesh found of a given ID
  17908. * @param {string} id - the id to search for
  17909. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17910. */
  17911. Scene.prototype.getMeshByID = function (id) {
  17912. for (var index = 0; index < this.meshes.length; index++) {
  17913. if (this.meshes[index].id === id) {
  17914. return this.meshes[index];
  17915. }
  17916. }
  17917. return null;
  17918. };
  17919. Scene.prototype.getMeshesByID = function (id) {
  17920. return this.meshes.filter(function (m) {
  17921. return m.id === id;
  17922. });
  17923. };
  17924. /**
  17925. * Get a mesh with its auto-generated unique id
  17926. * @param {number} uniqueId - the unique id to search for
  17927. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17928. */
  17929. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17930. for (var index = 0; index < this.meshes.length; index++) {
  17931. if (this.meshes[index].uniqueId === uniqueId) {
  17932. return this.meshes[index];
  17933. }
  17934. }
  17935. return null;
  17936. };
  17937. /**
  17938. * Get a the last added mesh found of a given ID
  17939. * @param {string} id - the id to search for
  17940. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17941. */
  17942. Scene.prototype.getLastMeshByID = function (id) {
  17943. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17944. if (this.meshes[index].id === id) {
  17945. return this.meshes[index];
  17946. }
  17947. }
  17948. return null;
  17949. };
  17950. /**
  17951. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17952. * @param {string} id - the id to search for
  17953. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17954. */
  17955. Scene.prototype.getLastEntryByID = function (id) {
  17956. var index;
  17957. for (index = this.meshes.length - 1; index >= 0; index--) {
  17958. if (this.meshes[index].id === id) {
  17959. return this.meshes[index];
  17960. }
  17961. }
  17962. for (index = this.cameras.length - 1; index >= 0; index--) {
  17963. if (this.cameras[index].id === id) {
  17964. return this.cameras[index];
  17965. }
  17966. }
  17967. for (index = this.lights.length - 1; index >= 0; index--) {
  17968. if (this.lights[index].id === id) {
  17969. return this.lights[index];
  17970. }
  17971. }
  17972. return null;
  17973. };
  17974. Scene.prototype.getNodeByID = function (id) {
  17975. var mesh = this.getMeshByID(id);
  17976. if (mesh) {
  17977. return mesh;
  17978. }
  17979. var light = this.getLightByID(id);
  17980. if (light) {
  17981. return light;
  17982. }
  17983. var camera = this.getCameraByID(id);
  17984. if (camera) {
  17985. return camera;
  17986. }
  17987. var bone = this.getBoneByID(id);
  17988. return bone;
  17989. };
  17990. Scene.prototype.getNodeByName = function (name) {
  17991. var mesh = this.getMeshByName(name);
  17992. if (mesh) {
  17993. return mesh;
  17994. }
  17995. var light = this.getLightByName(name);
  17996. if (light) {
  17997. return light;
  17998. }
  17999. var camera = this.getCameraByName(name);
  18000. if (camera) {
  18001. return camera;
  18002. }
  18003. var bone = this.getBoneByName(name);
  18004. return bone;
  18005. };
  18006. Scene.prototype.getMeshByName = function (name) {
  18007. for (var index = 0; index < this.meshes.length; index++) {
  18008. if (this.meshes[index].name === name) {
  18009. return this.meshes[index];
  18010. }
  18011. }
  18012. return null;
  18013. };
  18014. Scene.prototype.getSoundByName = function (name) {
  18015. var index;
  18016. if (BABYLON.AudioEngine) {
  18017. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18018. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18019. return this.mainSoundTrack.soundCollection[index];
  18020. }
  18021. }
  18022. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18023. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18024. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18025. return this.soundTracks[sdIndex].soundCollection[index];
  18026. }
  18027. }
  18028. }
  18029. }
  18030. return null;
  18031. };
  18032. Scene.prototype.getLastSkeletonByID = function (id) {
  18033. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18034. if (this.skeletons[index].id === id) {
  18035. return this.skeletons[index];
  18036. }
  18037. }
  18038. return null;
  18039. };
  18040. Scene.prototype.getSkeletonById = function (id) {
  18041. for (var index = 0; index < this.skeletons.length; index++) {
  18042. if (this.skeletons[index].id === id) {
  18043. return this.skeletons[index];
  18044. }
  18045. }
  18046. return null;
  18047. };
  18048. Scene.prototype.getSkeletonByName = function (name) {
  18049. for (var index = 0; index < this.skeletons.length; index++) {
  18050. if (this.skeletons[index].name === name) {
  18051. return this.skeletons[index];
  18052. }
  18053. }
  18054. return null;
  18055. };
  18056. Scene.prototype.isActiveMesh = function (mesh) {
  18057. return (this._activeMeshes.indexOf(mesh) !== -1);
  18058. };
  18059. Object.defineProperty(Scene.prototype, "uid", {
  18060. /**
  18061. * Return a unique id as a string which can serve as an identifier for the scene
  18062. */
  18063. get: function () {
  18064. if (!this._uid) {
  18065. this._uid = BABYLON.Tools.RandomId();
  18066. }
  18067. return this._uid;
  18068. },
  18069. enumerable: true,
  18070. configurable: true
  18071. });
  18072. /**
  18073. * Add an externaly attached data from its key.
  18074. * This method call will fail and return false, if such key already exists.
  18075. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18076. * @param key the unique key that identifies the data
  18077. * @param data the data object to associate to the key for this Engine instance
  18078. * @return true if no such key were already present and the data was added successfully, false otherwise
  18079. */
  18080. Scene.prototype.addExternalData = function (key, data) {
  18081. return this._externalData.add(key, data);
  18082. };
  18083. /**
  18084. * Get an externaly attached data from its key
  18085. * @param key the unique key that identifies the data
  18086. * @return the associated data, if present (can be null), or undefined if not present
  18087. */
  18088. Scene.prototype.getExternalData = function (key) {
  18089. return this._externalData.get(key);
  18090. };
  18091. /**
  18092. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18093. * @param key the unique key that identifies the data
  18094. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18095. * @return the associated data, can be null if the factory returned null.
  18096. */
  18097. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18098. return this._externalData.getOrAddWithFactory(key, factory);
  18099. };
  18100. /**
  18101. * Remove an externaly attached data from the Engine instance
  18102. * @param key the unique key that identifies the data
  18103. * @return true if the data was successfully removed, false if it doesn't exist
  18104. */
  18105. Scene.prototype.removeExternalData = function (key) {
  18106. return this._externalData.remove(key);
  18107. };
  18108. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18109. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18110. var material = subMesh.getMaterial();
  18111. if (mesh.showSubMeshesBoundingBox) {
  18112. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18113. }
  18114. if (material) {
  18115. // Render targets
  18116. if (material.getRenderTargetTextures) {
  18117. if (this._processedMaterials.indexOf(material) === -1) {
  18118. this._processedMaterials.push(material);
  18119. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18120. }
  18121. }
  18122. // Dispatch
  18123. this._activeIndices.addCount(subMesh.indexCount, false);
  18124. this._renderingManager.dispatch(subMesh);
  18125. }
  18126. }
  18127. };
  18128. Scene.prototype._isInIntermediateRendering = function () {
  18129. return this._intermediateRendering;
  18130. };
  18131. Scene.prototype._evaluateActiveMeshes = function () {
  18132. this.activeCamera._activeMeshes.reset();
  18133. this._activeMeshes.reset();
  18134. this._renderingManager.reset();
  18135. this._processedMaterials.reset();
  18136. this._activeParticleSystems.reset();
  18137. this._activeSkeletons.reset();
  18138. this._softwareSkinnedMeshes.reset();
  18139. this._boundingBoxRenderer.reset();
  18140. this._edgesRenderers.reset();
  18141. // Meshes
  18142. var meshes;
  18143. var len;
  18144. if (this._selectionOctree) {
  18145. var selection = this._selectionOctree.select(this._frustumPlanes);
  18146. meshes = selection.data;
  18147. len = selection.length;
  18148. }
  18149. else {
  18150. len = this.meshes.length;
  18151. meshes = this.meshes;
  18152. }
  18153. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18154. var mesh = meshes[meshIndex];
  18155. if (mesh.isBlocked) {
  18156. continue;
  18157. }
  18158. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18159. if (!mesh.isReady() || !mesh.isEnabled()) {
  18160. continue;
  18161. }
  18162. mesh.computeWorldMatrix();
  18163. // Intersections
  18164. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18165. this._meshesForIntersections.pushNoDuplicate(mesh);
  18166. }
  18167. // Switch to current LOD
  18168. var meshLOD = mesh.getLOD(this.activeCamera);
  18169. if (!meshLOD) {
  18170. continue;
  18171. }
  18172. mesh._preActivate();
  18173. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18174. this._activeMeshes.push(mesh);
  18175. this.activeCamera._activeMeshes.push(mesh);
  18176. mesh._activate(this._renderId);
  18177. this._activeMesh(mesh, meshLOD);
  18178. }
  18179. }
  18180. // Particle systems
  18181. this._particlesDuration.beginMonitoring();
  18182. var beforeParticlesDate = BABYLON.Tools.Now;
  18183. if (this.particlesEnabled) {
  18184. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18185. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18186. var particleSystem = this.particleSystems[particleIndex];
  18187. if (!particleSystem.isStarted()) {
  18188. continue;
  18189. }
  18190. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18191. this._activeParticleSystems.push(particleSystem);
  18192. particleSystem.animate();
  18193. }
  18194. }
  18195. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18196. }
  18197. this._particlesDuration.endMonitoring(false);
  18198. };
  18199. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18200. if (mesh.skeleton && this.skeletonsEnabled) {
  18201. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18202. mesh.skeleton.prepare();
  18203. }
  18204. if (!mesh.computeBonesUsingShaders) {
  18205. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18206. }
  18207. }
  18208. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18209. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18210. }
  18211. if (sourceMesh._edgesRenderer) {
  18212. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18213. }
  18214. if (mesh && mesh.subMeshes) {
  18215. // Submeshes Octrees
  18216. var len;
  18217. var subMeshes;
  18218. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18219. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18220. len = intersections.length;
  18221. subMeshes = intersections.data;
  18222. }
  18223. else {
  18224. subMeshes = mesh.subMeshes;
  18225. len = subMeshes.length;
  18226. }
  18227. for (var subIndex = 0; subIndex < len; subIndex++) {
  18228. var subMesh = subMeshes[subIndex];
  18229. this._evaluateSubMesh(subMesh, mesh);
  18230. }
  18231. }
  18232. };
  18233. Scene.prototype.updateTransformMatrix = function (force) {
  18234. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18235. };
  18236. Scene.prototype._renderForCamera = function (camera) {
  18237. var engine = this._engine;
  18238. var startTime = BABYLON.Tools.Now;
  18239. this.activeCamera = camera;
  18240. if (!this.activeCamera)
  18241. throw new Error("Active camera not set");
  18242. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18243. // Viewport
  18244. engine.setViewport(this.activeCamera.viewport);
  18245. // Camera
  18246. this.resetCachedMaterial();
  18247. this._renderId++;
  18248. this.updateTransformMatrix();
  18249. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18250. // Meshes
  18251. this._evaluateActiveMeshesDuration.beginMonitoring();
  18252. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18253. this._evaluateActiveMeshes();
  18254. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18255. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18256. // Software skinning
  18257. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18258. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18259. mesh.applySkeleton(mesh.skeleton);
  18260. }
  18261. // Render targets
  18262. this._renderTargetsDuration.beginMonitoring();
  18263. var needsRestoreFrameBuffer = false;
  18264. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18265. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18266. this._intermediateRendering = true;
  18267. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18268. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18269. var renderTarget = this._renderTargets.data[renderIndex];
  18270. if (renderTarget._shouldRender()) {
  18271. this._renderId++;
  18272. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18273. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18274. }
  18275. }
  18276. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18277. this._intermediateRendering = false;
  18278. this._renderId++;
  18279. needsRestoreFrameBuffer = true; // Restore back buffer
  18280. }
  18281. // Render HighlightLayer Texture
  18282. var stencilState = this._engine.getStencilBuffer();
  18283. var renderhighlights = false;
  18284. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18285. this._intermediateRendering = true;
  18286. for (var i = 0; i < this.highlightLayers.length; i++) {
  18287. var highlightLayer = this.highlightLayers[i];
  18288. if (highlightLayer.shouldRender() &&
  18289. (!highlightLayer.camera ||
  18290. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18291. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18292. renderhighlights = true;
  18293. var renderTarget = highlightLayer._mainTexture;
  18294. if (renderTarget._shouldRender()) {
  18295. this._renderId++;
  18296. renderTarget.render(false, false);
  18297. needsRestoreFrameBuffer = true;
  18298. }
  18299. }
  18300. }
  18301. this._intermediateRendering = false;
  18302. this._renderId++;
  18303. }
  18304. if (needsRestoreFrameBuffer) {
  18305. engine.restoreDefaultFramebuffer();
  18306. }
  18307. this._renderTargetsDuration.endMonitoring(false);
  18308. // Prepare Frame
  18309. this.postProcessManager._prepareFrame();
  18310. this._renderDuration.beginMonitoring();
  18311. // Backgrounds
  18312. var layerIndex;
  18313. var layer;
  18314. if (this.layers.length) {
  18315. engine.setDepthBuffer(false);
  18316. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18317. layer = this.layers[layerIndex];
  18318. if (layer.isBackground) {
  18319. layer.render();
  18320. }
  18321. }
  18322. engine.setDepthBuffer(true);
  18323. }
  18324. // Render
  18325. BABYLON.Tools.StartPerformanceCounter("Main render");
  18326. // Activate HighlightLayer stencil
  18327. if (renderhighlights) {
  18328. this._engine.setStencilBuffer(true);
  18329. }
  18330. this._renderingManager.render(null, null, true, true);
  18331. // Restore HighlightLayer stencil
  18332. if (renderhighlights) {
  18333. this._engine.setStencilBuffer(stencilState);
  18334. }
  18335. BABYLON.Tools.EndPerformanceCounter("Main render");
  18336. // Bounding boxes
  18337. this._boundingBoxRenderer.render();
  18338. // Edges
  18339. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18340. this._edgesRenderers.data[edgesRendererIndex].render();
  18341. }
  18342. // Lens flares
  18343. if (this.lensFlaresEnabled) {
  18344. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18345. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18346. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18347. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18348. lensFlareSystem.render();
  18349. }
  18350. }
  18351. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18352. }
  18353. // Foregrounds
  18354. if (this.layers.length) {
  18355. engine.setDepthBuffer(false);
  18356. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18357. layer = this.layers[layerIndex];
  18358. if (!layer.isBackground) {
  18359. layer.render();
  18360. }
  18361. }
  18362. engine.setDepthBuffer(true);
  18363. }
  18364. // Highlight Layer
  18365. if (renderhighlights) {
  18366. engine.setDepthBuffer(false);
  18367. for (var i = 0; i < this.highlightLayers.length; i++) {
  18368. if (this.highlightLayers[i].shouldRender()) {
  18369. this.highlightLayers[i].render();
  18370. }
  18371. }
  18372. engine.setDepthBuffer(true);
  18373. }
  18374. this._renderDuration.endMonitoring(false);
  18375. // Finalize frame
  18376. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18377. // Update camera
  18378. this.activeCamera._updateFromScene();
  18379. // Reset some special arrays
  18380. this._renderTargets.reset();
  18381. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18382. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18383. };
  18384. Scene.prototype._processSubCameras = function (camera) {
  18385. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18386. this._renderForCamera(camera);
  18387. return;
  18388. }
  18389. // rig cameras
  18390. for (var index = 0; index < camera._rigCameras.length; index++) {
  18391. this._renderForCamera(camera._rigCameras[index]);
  18392. }
  18393. this.activeCamera = camera;
  18394. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18395. // Update camera
  18396. this.activeCamera._updateFromScene();
  18397. };
  18398. Scene.prototype._checkIntersections = function () {
  18399. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18400. var sourceMesh = this._meshesForIntersections.data[index];
  18401. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18402. var action = sourceMesh.actionManager.actions[actionIndex];
  18403. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18404. var parameters = action.getTriggerParameter();
  18405. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18406. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18407. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18408. if (areIntersecting && currentIntersectionInProgress === -1) {
  18409. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18410. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18411. sourceMesh._intersectionsInProgress.push(otherMesh);
  18412. }
  18413. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18414. sourceMesh._intersectionsInProgress.push(otherMesh);
  18415. }
  18416. }
  18417. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18418. //They intersected, and now they don't.
  18419. //is this trigger an exit trigger? execute an event.
  18420. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18421. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18422. }
  18423. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18424. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18425. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18426. }
  18427. }
  18428. }
  18429. }
  18430. }
  18431. };
  18432. Scene.prototype.render = function () {
  18433. this._lastFrameDuration.beginMonitoring();
  18434. this._particlesDuration.fetchNewFrame();
  18435. this._spritesDuration.fetchNewFrame();
  18436. this._activeParticles.fetchNewFrame();
  18437. this._renderDuration.fetchNewFrame();
  18438. this._renderTargetsDuration.fetchNewFrame();
  18439. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18440. this._totalVertices.fetchNewFrame();
  18441. this._activeIndices.fetchNewFrame();
  18442. this._activeBones.fetchNewFrame();
  18443. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18444. this._meshesForIntersections.reset();
  18445. this.resetCachedMaterial();
  18446. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18447. // Actions
  18448. if (this.actionManager) {
  18449. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18450. }
  18451. //Simplification Queue
  18452. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18453. this.simplificationQueue.executeNext();
  18454. }
  18455. // Animations
  18456. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18457. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18458. this._animate();
  18459. // Physics
  18460. if (this._physicsEngine) {
  18461. BABYLON.Tools.StartPerformanceCounter("Physics");
  18462. this._physicsEngine._step(deltaTime / 1000.0);
  18463. BABYLON.Tools.EndPerformanceCounter("Physics");
  18464. }
  18465. // Before render
  18466. this.onBeforeRenderObservable.notifyObservers(this);
  18467. // Customs render targets
  18468. this._renderTargetsDuration.beginMonitoring();
  18469. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18470. var engine = this.getEngine();
  18471. var currentActiveCamera = this.activeCamera;
  18472. if (this.renderTargetsEnabled) {
  18473. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18474. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18475. var renderTarget = this.customRenderTargets[customIndex];
  18476. if (renderTarget._shouldRender()) {
  18477. this._renderId++;
  18478. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18479. if (!this.activeCamera)
  18480. throw new Error("Active camera not set");
  18481. // Viewport
  18482. engine.setViewport(this.activeCamera.viewport);
  18483. // Camera
  18484. this.updateTransformMatrix();
  18485. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18486. }
  18487. }
  18488. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18489. this._renderId++;
  18490. }
  18491. if (this.customRenderTargets.length > 0) {
  18492. engine.restoreDefaultFramebuffer();
  18493. }
  18494. this._renderTargetsDuration.endMonitoring();
  18495. this.activeCamera = currentActiveCamera;
  18496. // Procedural textures
  18497. if (this.proceduralTexturesEnabled) {
  18498. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18499. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18500. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18501. if (proceduralTexture._shouldRender()) {
  18502. proceduralTexture.render();
  18503. }
  18504. }
  18505. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18506. }
  18507. // Clear
  18508. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18509. // Shadows
  18510. if (this.shadowsEnabled) {
  18511. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18512. var light = this.lights[lightIndex];
  18513. var shadowGenerator = light.getShadowGenerator();
  18514. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18515. this._renderTargets.push(shadowGenerator.getShadowMap());
  18516. }
  18517. }
  18518. }
  18519. // Depth renderer
  18520. if (this._depthRenderer) {
  18521. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18522. }
  18523. // RenderPipeline
  18524. this.postProcessRenderPipelineManager.update();
  18525. // Multi-cameras?
  18526. if (this.activeCameras.length > 0) {
  18527. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18528. if (cameraIndex > 0) {
  18529. this._engine.clear(0, false, true, true);
  18530. }
  18531. this._processSubCameras(this.activeCameras[cameraIndex]);
  18532. }
  18533. }
  18534. else {
  18535. if (!this.activeCamera) {
  18536. throw new Error("No camera defined");
  18537. }
  18538. this._processSubCameras(this.activeCamera);
  18539. }
  18540. // Intersection checks
  18541. this._checkIntersections();
  18542. // Update the audio listener attached to the camera
  18543. if (BABYLON.AudioEngine) {
  18544. this._updateAudioParameters();
  18545. }
  18546. // After render
  18547. if (this.afterRender) {
  18548. this.afterRender();
  18549. }
  18550. this.onAfterRenderObservable.notifyObservers(this);
  18551. // Cleaning
  18552. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18553. this._toBeDisposed.data[index].dispose();
  18554. this._toBeDisposed[index] = null;
  18555. }
  18556. this._toBeDisposed.reset();
  18557. if (this.dumpNextRenderTargets) {
  18558. this.dumpNextRenderTargets = false;
  18559. }
  18560. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18561. this._lastFrameDuration.endMonitoring();
  18562. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18563. this._totalLightsCounter.addCount(this.lights.length, true);
  18564. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18565. this._totalTexturesCounter.addCount(this.textures.length, true);
  18566. this._activeBones.addCount(0, true);
  18567. this._activeIndices.addCount(0, true);
  18568. this._activeParticles.addCount(0, true);
  18569. };
  18570. Scene.prototype._updateAudioParameters = function () {
  18571. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18572. return;
  18573. }
  18574. var listeningCamera;
  18575. var audioEngine = BABYLON.Engine.audioEngine;
  18576. if (this.activeCameras.length > 0) {
  18577. listeningCamera = this.activeCameras[0];
  18578. }
  18579. else {
  18580. listeningCamera = this.activeCamera;
  18581. }
  18582. if (listeningCamera && audioEngine.canUseWebAudio) {
  18583. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18584. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18585. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18586. cameraDirection.normalize();
  18587. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18588. var i;
  18589. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18590. var sound = this.mainSoundTrack.soundCollection[i];
  18591. if (sound.useCustomAttenuation) {
  18592. sound.updateDistanceFromListener();
  18593. }
  18594. }
  18595. for (i = 0; i < this.soundTracks.length; i++) {
  18596. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18597. sound = this.soundTracks[i].soundCollection[j];
  18598. if (sound.useCustomAttenuation) {
  18599. sound.updateDistanceFromListener();
  18600. }
  18601. }
  18602. }
  18603. }
  18604. };
  18605. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18606. // Audio
  18607. get: function () {
  18608. return this._audioEnabled;
  18609. },
  18610. set: function (value) {
  18611. this._audioEnabled = value;
  18612. if (BABYLON.AudioEngine) {
  18613. if (this._audioEnabled) {
  18614. this._enableAudio();
  18615. }
  18616. else {
  18617. this._disableAudio();
  18618. }
  18619. }
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Scene.prototype._disableAudio = function () {
  18625. var i;
  18626. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18627. this.mainSoundTrack.soundCollection[i].pause();
  18628. }
  18629. for (i = 0; i < this.soundTracks.length; i++) {
  18630. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18631. this.soundTracks[i].soundCollection[j].pause();
  18632. }
  18633. }
  18634. };
  18635. Scene.prototype._enableAudio = function () {
  18636. var i;
  18637. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18638. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18639. this.mainSoundTrack.soundCollection[i].play();
  18640. }
  18641. }
  18642. for (i = 0; i < this.soundTracks.length; i++) {
  18643. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18644. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18645. this.soundTracks[i].soundCollection[j].play();
  18646. }
  18647. }
  18648. }
  18649. };
  18650. Object.defineProperty(Scene.prototype, "headphone", {
  18651. get: function () {
  18652. return this._headphone;
  18653. },
  18654. set: function (value) {
  18655. this._headphone = value;
  18656. if (BABYLON.AudioEngine) {
  18657. if (this._headphone) {
  18658. this._switchAudioModeForHeadphones();
  18659. }
  18660. else {
  18661. this._switchAudioModeForNormalSpeakers();
  18662. }
  18663. }
  18664. },
  18665. enumerable: true,
  18666. configurable: true
  18667. });
  18668. Scene.prototype._switchAudioModeForHeadphones = function () {
  18669. this.mainSoundTrack.switchPanningModelToHRTF();
  18670. for (var i = 0; i < this.soundTracks.length; i++) {
  18671. this.soundTracks[i].switchPanningModelToHRTF();
  18672. }
  18673. };
  18674. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18675. this.mainSoundTrack.switchPanningModelToEqualPower();
  18676. for (var i = 0; i < this.soundTracks.length; i++) {
  18677. this.soundTracks[i].switchPanningModelToEqualPower();
  18678. }
  18679. };
  18680. Scene.prototype.enableDepthRenderer = function () {
  18681. if (this._depthRenderer) {
  18682. return this._depthRenderer;
  18683. }
  18684. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18685. return this._depthRenderer;
  18686. };
  18687. Scene.prototype.disableDepthRenderer = function () {
  18688. if (!this._depthRenderer) {
  18689. return;
  18690. }
  18691. this._depthRenderer.dispose();
  18692. this._depthRenderer = null;
  18693. };
  18694. Scene.prototype.freezeMaterials = function () {
  18695. for (var i = 0; i < this.materials.length; i++) {
  18696. this.materials[i].freeze();
  18697. }
  18698. };
  18699. Scene.prototype.unfreezeMaterials = function () {
  18700. for (var i = 0; i < this.materials.length; i++) {
  18701. this.materials[i].unfreeze();
  18702. }
  18703. };
  18704. Scene.prototype.dispose = function () {
  18705. this.beforeRender = null;
  18706. this.afterRender = null;
  18707. this.skeletons = [];
  18708. this._boundingBoxRenderer.dispose();
  18709. if (this._depthRenderer) {
  18710. this._depthRenderer.dispose();
  18711. }
  18712. // Debug layer
  18713. if (this._debugLayer) {
  18714. this._debugLayer.hide();
  18715. }
  18716. // Events
  18717. this.onDisposeObservable.notifyObservers(this);
  18718. this.onDisposeObservable.clear();
  18719. this.onBeforeRenderObservable.clear();
  18720. this.onAfterRenderObservable.clear();
  18721. this.detachControl();
  18722. // Release sounds & sounds tracks
  18723. if (BABYLON.AudioEngine) {
  18724. this.disposeSounds();
  18725. }
  18726. // Detach cameras
  18727. var canvas = this._engine.getRenderingCanvas();
  18728. var index;
  18729. for (index = 0; index < this.cameras.length; index++) {
  18730. this.cameras[index].detachControl(canvas);
  18731. }
  18732. // Release lights
  18733. while (this.lights.length) {
  18734. this.lights[0].dispose();
  18735. }
  18736. // Release meshes
  18737. while (this.meshes.length) {
  18738. this.meshes[0].dispose(true);
  18739. }
  18740. // Release cameras
  18741. while (this.cameras.length) {
  18742. this.cameras[0].dispose();
  18743. }
  18744. // Release materials
  18745. while (this.materials.length) {
  18746. this.materials[0].dispose();
  18747. }
  18748. // Release particles
  18749. while (this.particleSystems.length) {
  18750. this.particleSystems[0].dispose();
  18751. }
  18752. // Release sprites
  18753. while (this.spriteManagers.length) {
  18754. this.spriteManagers[0].dispose();
  18755. }
  18756. // Release layers
  18757. while (this.layers.length) {
  18758. this.layers[0].dispose();
  18759. }
  18760. while (this.highlightLayers.length) {
  18761. this.highlightLayers[0].dispose();
  18762. }
  18763. // Release textures
  18764. while (this.textures.length) {
  18765. this.textures[0].dispose();
  18766. }
  18767. // Post-processes
  18768. this.postProcessManager.dispose();
  18769. // Physics
  18770. if (this._physicsEngine) {
  18771. this.disablePhysicsEngine();
  18772. }
  18773. // Remove from engine
  18774. index = this._engine.scenes.indexOf(this);
  18775. if (index > -1) {
  18776. this._engine.scenes.splice(index, 1);
  18777. }
  18778. this._engine.wipeCaches();
  18779. };
  18780. // Release sounds & sounds tracks
  18781. Scene.prototype.disposeSounds = function () {
  18782. this.mainSoundTrack.dispose();
  18783. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18784. this.soundTracks[scIndex].dispose();
  18785. }
  18786. };
  18787. // Octrees
  18788. Scene.prototype.getWorldExtends = function () {
  18789. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18790. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18791. for (var index = 0; index < this.meshes.length; index++) {
  18792. var mesh = this.meshes[index];
  18793. mesh.computeWorldMatrix(true);
  18794. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18795. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18796. BABYLON.Tools.CheckExtends(minBox, min, max);
  18797. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18798. }
  18799. return {
  18800. min: min,
  18801. max: max
  18802. };
  18803. };
  18804. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18805. if (maxCapacity === void 0) { maxCapacity = 64; }
  18806. if (maxDepth === void 0) { maxDepth = 2; }
  18807. if (!this._selectionOctree) {
  18808. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18809. }
  18810. var worldExtends = this.getWorldExtends();
  18811. // Update octree
  18812. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18813. return this._selectionOctree;
  18814. };
  18815. // Picking
  18816. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18817. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18818. var engine = this._engine;
  18819. if (!camera) {
  18820. if (!this.activeCamera)
  18821. throw new Error("Active camera not set");
  18822. camera = this.activeCamera;
  18823. }
  18824. var cameraViewport = camera.viewport;
  18825. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18826. // Moving coordinates to local viewport world
  18827. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18828. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18829. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18830. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18831. };
  18832. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18833. var engine = this._engine;
  18834. if (!camera) {
  18835. if (!this.activeCamera)
  18836. throw new Error("Active camera not set");
  18837. camera = this.activeCamera;
  18838. }
  18839. var cameraViewport = camera.viewport;
  18840. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18841. var identity = BABYLON.Matrix.Identity();
  18842. // Moving coordinates to local viewport world
  18843. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18844. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18845. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18846. };
  18847. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18848. var pickingInfo = null;
  18849. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18850. var mesh = this.meshes[meshIndex];
  18851. if (predicate) {
  18852. if (!predicate(mesh)) {
  18853. continue;
  18854. }
  18855. }
  18856. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18857. continue;
  18858. }
  18859. var world = mesh.getWorldMatrix();
  18860. var ray = rayFunction(world);
  18861. var result = mesh.intersects(ray, fastCheck);
  18862. if (!result || !result.hit)
  18863. continue;
  18864. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18865. continue;
  18866. pickingInfo = result;
  18867. if (fastCheck) {
  18868. break;
  18869. }
  18870. }
  18871. return pickingInfo || new BABYLON.PickingInfo();
  18872. };
  18873. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18874. var pickingInfos = new Array();
  18875. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18876. var mesh = this.meshes[meshIndex];
  18877. if (predicate) {
  18878. if (!predicate(mesh)) {
  18879. continue;
  18880. }
  18881. }
  18882. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18883. continue;
  18884. }
  18885. var world = mesh.getWorldMatrix();
  18886. var ray = rayFunction(world);
  18887. var result = mesh.intersects(ray, false);
  18888. if (!result || !result.hit)
  18889. continue;
  18890. pickingInfos.push(result);
  18891. }
  18892. return pickingInfos;
  18893. };
  18894. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18895. var pickingInfo = null;
  18896. camera = camera || this.activeCamera;
  18897. if (this.spriteManagers.length > 0) {
  18898. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18899. var spriteManager = this.spriteManagers[spriteIndex];
  18900. if (!spriteManager.isPickable) {
  18901. continue;
  18902. }
  18903. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18904. if (!result || !result.hit)
  18905. continue;
  18906. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18907. continue;
  18908. pickingInfo = result;
  18909. if (fastCheck) {
  18910. break;
  18911. }
  18912. }
  18913. }
  18914. return pickingInfo || new BABYLON.PickingInfo();
  18915. };
  18916. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18917. /// <param name="x">X position on screen</param>
  18918. /// <param name="y">Y position on screen</param>
  18919. /// <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>
  18920. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18921. /// <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>
  18922. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18923. var _this = this;
  18924. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18925. };
  18926. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18927. /// <param name="x">X position on screen</param>
  18928. /// <param name="y">Y position on screen</param>
  18929. /// <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>
  18930. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18931. /// <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>
  18932. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18933. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18934. };
  18935. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18936. var _this = this;
  18937. return this._internalPick(function (world) {
  18938. if (!_this._pickWithRayInverseMatrix) {
  18939. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18940. }
  18941. world.invertToRef(_this._pickWithRayInverseMatrix);
  18942. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18943. }, predicate, fastCheck);
  18944. };
  18945. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18946. /// <param name="x">X position on screen</param>
  18947. /// <param name="y">Y position on screen</param>
  18948. /// <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>
  18949. /// <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>
  18950. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18951. var _this = this;
  18952. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18953. };
  18954. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18955. /// <param name="ray">Ray to use</param>
  18956. /// <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>
  18957. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18958. var _this = this;
  18959. return this._internalMultiPick(function (world) {
  18960. if (!_this._pickWithRayInverseMatrix) {
  18961. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18962. }
  18963. world.invertToRef(_this._pickWithRayInverseMatrix);
  18964. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18965. }, predicate);
  18966. };
  18967. Scene.prototype.setPointerOverMesh = function (mesh) {
  18968. if (this._pointerOverMesh === mesh) {
  18969. return;
  18970. }
  18971. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18972. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18973. }
  18974. this._pointerOverMesh = mesh;
  18975. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18976. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18977. }
  18978. };
  18979. Scene.prototype.getPointerOverMesh = function () {
  18980. return this._pointerOverMesh;
  18981. };
  18982. Scene.prototype.setPointerOverSprite = function (sprite) {
  18983. if (this._pointerOverSprite === sprite) {
  18984. return;
  18985. }
  18986. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18987. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18988. }
  18989. this._pointerOverSprite = sprite;
  18990. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18991. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18992. }
  18993. };
  18994. Scene.prototype.getPointerOverSprite = function () {
  18995. return this._pointerOverSprite;
  18996. };
  18997. // Physics
  18998. Scene.prototype.getPhysicsEngine = function () {
  18999. return this._physicsEngine;
  19000. };
  19001. /**
  19002. * Enables physics to the current scene
  19003. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19004. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19005. * @return {boolean} was the physics engine initialized
  19006. */
  19007. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19008. if (this._physicsEngine) {
  19009. return true;
  19010. }
  19011. try {
  19012. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19013. return true;
  19014. }
  19015. catch (e) {
  19016. BABYLON.Tools.Error(e.message);
  19017. return false;
  19018. }
  19019. };
  19020. Scene.prototype.disablePhysicsEngine = function () {
  19021. if (!this._physicsEngine) {
  19022. return;
  19023. }
  19024. this._physicsEngine.dispose();
  19025. this._physicsEngine = undefined;
  19026. };
  19027. Scene.prototype.isPhysicsEnabled = function () {
  19028. return this._physicsEngine !== undefined;
  19029. };
  19030. /**
  19031. *
  19032. * Sets the gravity of the physics engine (and NOT of the scene)
  19033. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19034. */
  19035. Scene.prototype.setGravity = function (gravity) {
  19036. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19037. if (!this._physicsEngine) {
  19038. return;
  19039. }
  19040. this._physicsEngine.setGravity(gravity);
  19041. };
  19042. /**
  19043. * Legacy support, using the new API
  19044. * @Deprecated
  19045. */
  19046. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19047. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19048. if (parts.parts) {
  19049. options = parts;
  19050. parts = parts.parts;
  19051. }
  19052. var mainMesh = parts[0].mesh;
  19053. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19054. for (var index = 1; index < parts.length; index++) {
  19055. var mesh = parts[index].mesh;
  19056. if (mesh.parent !== mainMesh) {
  19057. mesh.position = mesh.position.subtract(mainMesh.position);
  19058. mesh.parent = mainMesh;
  19059. }
  19060. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19061. }
  19062. mainMesh.physicsImpostor.forceUpdate();
  19063. };
  19064. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19065. var mesh = compound.parts[0].mesh;
  19066. mesh.physicsImpostor.dispose();
  19067. mesh.physicsImpostor = null;
  19068. };
  19069. // Misc.
  19070. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19071. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19072. // Light
  19073. if (this.lights.length === 0) {
  19074. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19075. }
  19076. // Camera
  19077. if (!this.activeCamera) {
  19078. // Compute position
  19079. var worldExtends = this.getWorldExtends();
  19080. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19081. var camera;
  19082. if (createArcRotateCamera) {
  19083. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19084. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19085. camera.setTarget(worldCenter);
  19086. }
  19087. else {
  19088. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19089. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19090. camera.setTarget(worldCenter);
  19091. }
  19092. this.activeCamera = camera;
  19093. }
  19094. };
  19095. // Tags
  19096. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19097. if (tagsQuery === undefined) {
  19098. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19099. return list;
  19100. }
  19101. var listByTags = [];
  19102. forEach = forEach || (function (item) { return; });
  19103. for (var i in list) {
  19104. var item = list[i];
  19105. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19106. listByTags.push(item);
  19107. forEach(item);
  19108. }
  19109. }
  19110. return listByTags;
  19111. };
  19112. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19113. return this._getByTags(this.meshes, tagsQuery, forEach);
  19114. };
  19115. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19116. return this._getByTags(this.cameras, tagsQuery, forEach);
  19117. };
  19118. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19119. return this._getByTags(this.lights, tagsQuery, forEach);
  19120. };
  19121. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19122. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19123. };
  19124. /**
  19125. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19126. * This allowed control for front to back rendering or reversly depending of the special needs.
  19127. *
  19128. * @param renderingGroupId The rendering group id corresponding to its index
  19129. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19130. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19131. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19132. */
  19133. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19134. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19135. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19136. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19137. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19138. };
  19139. /**
  19140. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19141. *
  19142. * @param renderingGroupId The rendering group id corresponding to its index
  19143. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19144. */
  19145. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  19146. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  19147. };
  19148. // Statics
  19149. Scene._FOGMODE_NONE = 0;
  19150. Scene._FOGMODE_EXP = 1;
  19151. Scene._FOGMODE_EXP2 = 2;
  19152. Scene._FOGMODE_LINEAR = 3;
  19153. Scene.MinDeltaTime = 1.0;
  19154. Scene.MaxDeltaTime = 1000.0;
  19155. return Scene;
  19156. }());
  19157. BABYLON.Scene = Scene;
  19158. })(BABYLON || (BABYLON = {}));
  19159. //# sourceMappingURL=babylon.scene.js.map
  19160. var BABYLON;
  19161. (function (BABYLON) {
  19162. var Buffer = (function () {
  19163. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19164. if (engine instanceof BABYLON.Mesh) {
  19165. this._engine = engine.getScene().getEngine();
  19166. }
  19167. else {
  19168. this._engine = engine;
  19169. }
  19170. this._updatable = updatable;
  19171. this._data = data;
  19172. this._strideSize = stride;
  19173. if (!postponeInternalCreation) {
  19174. this.create();
  19175. }
  19176. this._instanced = instanced;
  19177. }
  19178. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19179. // a lot of these parameters are ignored as they are overriden by the buffer
  19180. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19181. };
  19182. // Properties
  19183. Buffer.prototype.isUpdatable = function () {
  19184. return this._updatable;
  19185. };
  19186. Buffer.prototype.getData = function () {
  19187. return this._data;
  19188. };
  19189. Buffer.prototype.getBuffer = function () {
  19190. return this._buffer;
  19191. };
  19192. Buffer.prototype.getStrideSize = function () {
  19193. return this._strideSize;
  19194. };
  19195. Buffer.prototype.getIsInstanced = function () {
  19196. return this._instanced;
  19197. };
  19198. // Methods
  19199. Buffer.prototype.create = function (data) {
  19200. if (!data && this._buffer) {
  19201. return; // nothing to do
  19202. }
  19203. data = data || this._data;
  19204. if (!this._buffer) {
  19205. if (this._updatable) {
  19206. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19207. this._data = data;
  19208. }
  19209. else {
  19210. this._buffer = this._engine.createVertexBuffer(data);
  19211. }
  19212. }
  19213. else if (this._updatable) {
  19214. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19215. this._data = data;
  19216. }
  19217. };
  19218. Buffer.prototype.update = function (data) {
  19219. this.create(data);
  19220. };
  19221. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19222. if (!this._buffer) {
  19223. return;
  19224. }
  19225. if (this._updatable) {
  19226. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19227. this._data = null;
  19228. }
  19229. };
  19230. Buffer.prototype.dispose = function () {
  19231. if (!this._buffer) {
  19232. return;
  19233. }
  19234. if (this._engine._releaseBuffer(this._buffer)) {
  19235. this._buffer = null;
  19236. }
  19237. };
  19238. return Buffer;
  19239. }());
  19240. BABYLON.Buffer = Buffer;
  19241. })(BABYLON || (BABYLON = {}));
  19242. //# sourceMappingURL=babylon.buffer.js.map
  19243. var BABYLON;
  19244. (function (BABYLON) {
  19245. var VertexBuffer = (function () {
  19246. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19247. if (!stride) {
  19248. // Deduce stride from kind
  19249. switch (kind) {
  19250. case VertexBuffer.PositionKind:
  19251. stride = 3;
  19252. break;
  19253. case VertexBuffer.NormalKind:
  19254. stride = 3;
  19255. break;
  19256. case VertexBuffer.UVKind:
  19257. case VertexBuffer.UV2Kind:
  19258. case VertexBuffer.UV3Kind:
  19259. case VertexBuffer.UV4Kind:
  19260. case VertexBuffer.UV5Kind:
  19261. case VertexBuffer.UV6Kind:
  19262. stride = 2;
  19263. break;
  19264. case VertexBuffer.ColorKind:
  19265. stride = 4;
  19266. break;
  19267. case VertexBuffer.MatricesIndicesKind:
  19268. case VertexBuffer.MatricesIndicesExtraKind:
  19269. stride = 4;
  19270. break;
  19271. case VertexBuffer.MatricesWeightsKind:
  19272. case VertexBuffer.MatricesWeightsExtraKind:
  19273. stride = 4;
  19274. break;
  19275. }
  19276. }
  19277. if (data instanceof BABYLON.Buffer) {
  19278. if (!stride) {
  19279. stride = data.getStrideSize();
  19280. }
  19281. this._buffer = data;
  19282. this._ownsBuffer = false;
  19283. }
  19284. else {
  19285. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19286. this._ownsBuffer = true;
  19287. }
  19288. this._stride = stride;
  19289. this._offset = offset ? offset : 0;
  19290. this._size = size ? size : stride;
  19291. this._kind = kind;
  19292. }
  19293. VertexBuffer.prototype.getKind = function () {
  19294. return this._kind;
  19295. };
  19296. // Properties
  19297. VertexBuffer.prototype.isUpdatable = function () {
  19298. return this._buffer.isUpdatable();
  19299. };
  19300. VertexBuffer.prototype.getData = function () {
  19301. return this._buffer.getData();
  19302. };
  19303. VertexBuffer.prototype.getBuffer = function () {
  19304. return this._buffer.getBuffer();
  19305. };
  19306. VertexBuffer.prototype.getStrideSize = function () {
  19307. return this._stride;
  19308. };
  19309. VertexBuffer.prototype.getOffset = function () {
  19310. return this._offset;
  19311. };
  19312. VertexBuffer.prototype.getSize = function () {
  19313. return this._size;
  19314. };
  19315. VertexBuffer.prototype.getIsInstanced = function () {
  19316. return this._buffer.getIsInstanced();
  19317. };
  19318. // Methods
  19319. VertexBuffer.prototype.create = function (data) {
  19320. return this._buffer.create(data);
  19321. };
  19322. VertexBuffer.prototype.update = function (data) {
  19323. return this._buffer.update(data);
  19324. };
  19325. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19326. return this._buffer.updateDirectly(data, offset);
  19327. };
  19328. VertexBuffer.prototype.dispose = function () {
  19329. if (this._ownsBuffer) {
  19330. this._buffer.dispose();
  19331. }
  19332. };
  19333. Object.defineProperty(VertexBuffer, "PositionKind", {
  19334. get: function () {
  19335. return VertexBuffer._PositionKind;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(VertexBuffer, "NormalKind", {
  19341. get: function () {
  19342. return VertexBuffer._NormalKind;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(VertexBuffer, "UVKind", {
  19348. get: function () {
  19349. return VertexBuffer._UVKind;
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19355. get: function () {
  19356. return VertexBuffer._UV2Kind;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19362. get: function () {
  19363. return VertexBuffer._UV3Kind;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19369. get: function () {
  19370. return VertexBuffer._UV4Kind;
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19376. get: function () {
  19377. return VertexBuffer._UV5Kind;
  19378. },
  19379. enumerable: true,
  19380. configurable: true
  19381. });
  19382. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19383. get: function () {
  19384. return VertexBuffer._UV6Kind;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(VertexBuffer, "ColorKind", {
  19390. get: function () {
  19391. return VertexBuffer._ColorKind;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19397. get: function () {
  19398. return VertexBuffer._MatricesIndicesKind;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19404. get: function () {
  19405. return VertexBuffer._MatricesWeightsKind;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19411. get: function () {
  19412. return VertexBuffer._MatricesIndicesExtraKind;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19418. get: function () {
  19419. return VertexBuffer._MatricesWeightsExtraKind;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. // Enums
  19425. VertexBuffer._PositionKind = "position";
  19426. VertexBuffer._NormalKind = "normal";
  19427. VertexBuffer._UVKind = "uv";
  19428. VertexBuffer._UV2Kind = "uv2";
  19429. VertexBuffer._UV3Kind = "uv3";
  19430. VertexBuffer._UV4Kind = "uv4";
  19431. VertexBuffer._UV5Kind = "uv5";
  19432. VertexBuffer._UV6Kind = "uv6";
  19433. VertexBuffer._ColorKind = "color";
  19434. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19435. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19436. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19437. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19438. return VertexBuffer;
  19439. }());
  19440. BABYLON.VertexBuffer = VertexBuffer;
  19441. })(BABYLON || (BABYLON = {}));
  19442. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19443. var BABYLON;
  19444. (function (BABYLON) {
  19445. /**
  19446. * Creates an instance based on a source mesh.
  19447. */
  19448. var InstancedMesh = (function (_super) {
  19449. __extends(InstancedMesh, _super);
  19450. function InstancedMesh(name, source) {
  19451. _super.call(this, name, source.getScene());
  19452. source.instances.push(this);
  19453. this._sourceMesh = source;
  19454. this.position.copyFrom(source.position);
  19455. this.rotation.copyFrom(source.rotation);
  19456. this.scaling.copyFrom(source.scaling);
  19457. if (source.rotationQuaternion) {
  19458. this.rotationQuaternion = source.rotationQuaternion.clone();
  19459. }
  19460. this.infiniteDistance = source.infiniteDistance;
  19461. this.setPivotMatrix(source.getPivotMatrix());
  19462. this.refreshBoundingInfo();
  19463. this._syncSubMeshes();
  19464. }
  19465. InstancedMesh.prototype.getClassName = function () {
  19466. return "InstancedMesh";
  19467. };
  19468. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19469. // Methods
  19470. get: function () {
  19471. return this._sourceMesh.receiveShadows;
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(InstancedMesh.prototype, "material", {
  19477. get: function () {
  19478. return this._sourceMesh.material;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19484. get: function () {
  19485. return this._sourceMesh.visibility;
  19486. },
  19487. enumerable: true,
  19488. configurable: true
  19489. });
  19490. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19491. get: function () {
  19492. return this._sourceMesh.skeleton;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19498. get: function () {
  19499. return this._sourceMesh.renderingGroupId;
  19500. },
  19501. enumerable: true,
  19502. configurable: true
  19503. });
  19504. InstancedMesh.prototype.getTotalVertices = function () {
  19505. return this._sourceMesh.getTotalVertices();
  19506. };
  19507. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19508. get: function () {
  19509. return this._sourceMesh;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19515. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19516. };
  19517. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19518. return this._sourceMesh.isVerticesDataPresent(kind);
  19519. };
  19520. InstancedMesh.prototype.getIndices = function () {
  19521. return this._sourceMesh.getIndices();
  19522. };
  19523. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19524. get: function () {
  19525. return this._sourceMesh._positions;
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19531. var meshBB = this._sourceMesh.getBoundingInfo();
  19532. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19533. this._updateBoundingInfo();
  19534. };
  19535. InstancedMesh.prototype._preActivate = function () {
  19536. if (this._currentLOD) {
  19537. this._currentLOD._preActivate();
  19538. }
  19539. };
  19540. InstancedMesh.prototype._activate = function (renderId) {
  19541. if (this._currentLOD) {
  19542. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19543. }
  19544. };
  19545. InstancedMesh.prototype.getLOD = function (camera) {
  19546. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19547. if (this._currentLOD === this.sourceMesh) {
  19548. return this;
  19549. }
  19550. return this._currentLOD;
  19551. };
  19552. InstancedMesh.prototype._syncSubMeshes = function () {
  19553. this.releaseSubMeshes();
  19554. if (this._sourceMesh.subMeshes) {
  19555. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19556. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19557. }
  19558. }
  19559. };
  19560. InstancedMesh.prototype._generatePointsArray = function () {
  19561. return this._sourceMesh._generatePointsArray();
  19562. };
  19563. // Clone
  19564. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19565. var result = this._sourceMesh.createInstance(name);
  19566. // Deep copy
  19567. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19568. // Bounding info
  19569. this.refreshBoundingInfo();
  19570. // Parent
  19571. if (newParent) {
  19572. result.parent = newParent;
  19573. }
  19574. if (!doNotCloneChildren) {
  19575. // Children
  19576. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19577. var mesh = this.getScene().meshes[index];
  19578. if (mesh.parent === this) {
  19579. mesh.clone(mesh.name, result);
  19580. }
  19581. }
  19582. }
  19583. result.computeWorldMatrix(true);
  19584. return result;
  19585. };
  19586. // Dispoe
  19587. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19588. // Remove from mesh
  19589. var index = this._sourceMesh.instances.indexOf(this);
  19590. this._sourceMesh.instances.splice(index, 1);
  19591. _super.prototype.dispose.call(this, doNotRecurse);
  19592. };
  19593. return InstancedMesh;
  19594. }(BABYLON.AbstractMesh));
  19595. BABYLON.InstancedMesh = InstancedMesh;
  19596. })(BABYLON || (BABYLON = {}));
  19597. //# sourceMappingURL=babylon.instancedMesh.js.map
  19598. var BABYLON;
  19599. (function (BABYLON) {
  19600. var _InstancesBatch = (function () {
  19601. function _InstancesBatch() {
  19602. this.mustReturn = false;
  19603. this.visibleInstances = new Array();
  19604. this.renderSelf = new Array();
  19605. }
  19606. return _InstancesBatch;
  19607. }());
  19608. BABYLON._InstancesBatch = _InstancesBatch;
  19609. var Mesh = (function (_super) {
  19610. __extends(Mesh, _super);
  19611. /**
  19612. * @constructor
  19613. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19614. * @param {Scene} scene The scene to add this mesh to.
  19615. * @param {Node} parent The parent of this mesh, if it has one
  19616. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19617. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19618. * When false, achieved by calling a clone(), also passing False.
  19619. * This will make creation of children, recursive.
  19620. */
  19621. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19622. if (parent === void 0) { parent = null; }
  19623. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19624. _super.call(this, name, scene);
  19625. // Events
  19626. /**
  19627. * An event triggered before rendering the mesh
  19628. * @type {BABYLON.Observable}
  19629. */
  19630. this.onBeforeRenderObservable = new BABYLON.Observable();
  19631. /**
  19632. * An event triggered after rendering the mesh
  19633. * @type {BABYLON.Observable}
  19634. */
  19635. this.onAfterRenderObservable = new BABYLON.Observable();
  19636. /**
  19637. * An event triggered before drawing the mesh
  19638. * @type {BABYLON.Observable}
  19639. */
  19640. this.onBeforeDrawObservable = new BABYLON.Observable();
  19641. // Members
  19642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19643. this.instances = new Array();
  19644. this._LODLevels = new Array();
  19645. this._visibleInstances = {};
  19646. this._renderIdForInstances = new Array();
  19647. this._batchCache = new _InstancesBatch();
  19648. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19649. this._sideOrientation = Mesh._DEFAULTSIDE;
  19650. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19651. if (source) {
  19652. // Geometry
  19653. if (source._geometry) {
  19654. source._geometry.applyToMesh(this);
  19655. }
  19656. // Deep copy
  19657. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19658. // Parent
  19659. this.parent = source.parent;
  19660. // Pivot
  19661. this.setPivotMatrix(source.getPivotMatrix());
  19662. this.id = name + "." + source.id;
  19663. // Material
  19664. this.material = source.material;
  19665. var index;
  19666. if (!doNotCloneChildren) {
  19667. // Children
  19668. for (index = 0; index < scene.meshes.length; index++) {
  19669. var mesh = scene.meshes[index];
  19670. if (mesh.parent === source) {
  19671. // doNotCloneChildren is always going to be False
  19672. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19673. }
  19674. }
  19675. }
  19676. // Physics clone
  19677. var physicsEngine = this.getScene().getPhysicsEngine();
  19678. if (clonePhysicsImpostor && physicsEngine) {
  19679. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19680. if (impostor) {
  19681. this.physicsImpostor = impostor.clone(this);
  19682. }
  19683. }
  19684. // Particles
  19685. for (index = 0; index < scene.particleSystems.length; index++) {
  19686. var system = scene.particleSystems[index];
  19687. if (system.emitter === source) {
  19688. system.clone(system.name, this);
  19689. }
  19690. }
  19691. this.computeWorldMatrix(true);
  19692. }
  19693. // Parent
  19694. if (parent !== null) {
  19695. this.parent = parent;
  19696. }
  19697. }
  19698. Object.defineProperty(Mesh, "FRONTSIDE", {
  19699. /**
  19700. * Mesh side orientation : usually the external or front surface
  19701. */
  19702. get: function () {
  19703. return Mesh._FRONTSIDE;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(Mesh, "BACKSIDE", {
  19709. /**
  19710. * Mesh side orientation : usually the internal or back surface
  19711. */
  19712. get: function () {
  19713. return Mesh._BACKSIDE;
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19719. /**
  19720. * Mesh side orientation : both internal and external or front and back surfaces
  19721. */
  19722. get: function () {
  19723. return Mesh._DOUBLESIDE;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19729. /**
  19730. * Mesh side orientation : by default, `FRONTSIDE`
  19731. */
  19732. get: function () {
  19733. return Mesh._DEFAULTSIDE;
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(Mesh, "NO_CAP", {
  19739. /**
  19740. * Mesh cap setting : no cap
  19741. */
  19742. get: function () {
  19743. return Mesh._NO_CAP;
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(Mesh, "CAP_START", {
  19749. /**
  19750. * Mesh cap setting : one cap at the beginning of the mesh
  19751. */
  19752. get: function () {
  19753. return Mesh._CAP_START;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(Mesh, "CAP_END", {
  19759. /**
  19760. * Mesh cap setting : one cap at the end of the mesh
  19761. */
  19762. get: function () {
  19763. return Mesh._CAP_END;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(Mesh, "CAP_ALL", {
  19769. /**
  19770. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19771. */
  19772. get: function () {
  19773. return Mesh._CAP_ALL;
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19779. set: function (callback) {
  19780. if (this._onBeforeDrawObserver) {
  19781. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19782. }
  19783. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. // Methods
  19789. Mesh.prototype.getClassName = function () {
  19790. return "Mesh";
  19791. };
  19792. /**
  19793. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19794. */
  19795. Mesh.prototype.toString = function (fullDetails) {
  19796. var ret = _super.prototype.toString.call(this, fullDetails);
  19797. ret += ", n vertices: " + this.getTotalVertices();
  19798. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19799. if (this.animations) {
  19800. for (var i = 0; i < this.animations.length; i++) {
  19801. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19802. }
  19803. }
  19804. if (fullDetails) {
  19805. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19806. }
  19807. return ret;
  19808. };
  19809. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19810. get: function () {
  19811. return this._LODLevels.length > 0;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Mesh.prototype._sortLODLevels = function () {
  19817. this._LODLevels.sort(function (a, b) {
  19818. if (a.distance < b.distance) {
  19819. return 1;
  19820. }
  19821. if (a.distance > b.distance) {
  19822. return -1;
  19823. }
  19824. return 0;
  19825. });
  19826. };
  19827. /**
  19828. * Add a mesh as LOD level triggered at the given distance.
  19829. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19830. * @param {number} distance The distance from the center of the object to show this level
  19831. * @param {Mesh} mesh The mesh to be added as LOD level
  19832. * @return {Mesh} This mesh (for chaining)
  19833. */
  19834. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19835. if (mesh && mesh._masterMesh) {
  19836. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19837. return this;
  19838. }
  19839. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19840. this._LODLevels.push(level);
  19841. if (mesh) {
  19842. mesh._masterMesh = this;
  19843. }
  19844. this._sortLODLevels();
  19845. return this;
  19846. };
  19847. /**
  19848. * Returns the LOD level mesh at the passed distance or null if not found.
  19849. * It is related to the method `addLODLevel(distance, mesh)`.
  19850. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19851. */
  19852. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19853. for (var index = 0; index < this._LODLevels.length; index++) {
  19854. var level = this._LODLevels[index];
  19855. if (level.distance === distance) {
  19856. return level.mesh;
  19857. }
  19858. }
  19859. return null;
  19860. };
  19861. /**
  19862. * Remove a mesh from the LOD array
  19863. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19864. * @param {Mesh} mesh The mesh to be removed.
  19865. * @return {Mesh} This mesh (for chaining)
  19866. */
  19867. Mesh.prototype.removeLODLevel = function (mesh) {
  19868. for (var index = 0; index < this._LODLevels.length; index++) {
  19869. if (this._LODLevels[index].mesh === mesh) {
  19870. this._LODLevels.splice(index, 1);
  19871. if (mesh) {
  19872. mesh._masterMesh = null;
  19873. }
  19874. }
  19875. }
  19876. this._sortLODLevels();
  19877. return this;
  19878. };
  19879. /**
  19880. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19881. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19882. */
  19883. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19884. if (!this._LODLevels || this._LODLevels.length === 0) {
  19885. return this;
  19886. }
  19887. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19888. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19889. if (this.onLODLevelSelection) {
  19890. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19891. }
  19892. return this;
  19893. }
  19894. for (var index = 0; index < this._LODLevels.length; index++) {
  19895. var level = this._LODLevels[index];
  19896. if (level.distance < distanceToCamera) {
  19897. if (level.mesh) {
  19898. level.mesh._preActivate();
  19899. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19900. }
  19901. if (this.onLODLevelSelection) {
  19902. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19903. }
  19904. return level.mesh;
  19905. }
  19906. }
  19907. if (this.onLODLevelSelection) {
  19908. this.onLODLevelSelection(distanceToCamera, this, this);
  19909. }
  19910. return this;
  19911. };
  19912. Object.defineProperty(Mesh.prototype, "geometry", {
  19913. /**
  19914. * Returns the mesh internal Geometry object.
  19915. */
  19916. get: function () {
  19917. return this._geometry;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. /**
  19923. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19924. */
  19925. Mesh.prototype.getTotalVertices = function () {
  19926. if (!this._geometry) {
  19927. return 0;
  19928. }
  19929. return this._geometry.getTotalVertices();
  19930. };
  19931. /**
  19932. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19933. * 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.
  19934. * Returns null if the mesh has no geometry or no vertex buffer.
  19935. * Possible `kind` values :
  19936. * - BABYLON.VertexBuffer.PositionKind
  19937. * - BABYLON.VertexBuffer.UVKind
  19938. * - BABYLON.VertexBuffer.UV2Kind
  19939. * - BABYLON.VertexBuffer.UV3Kind
  19940. * - BABYLON.VertexBuffer.UV4Kind
  19941. * - BABYLON.VertexBuffer.UV5Kind
  19942. * - BABYLON.VertexBuffer.UV6Kind
  19943. * - BABYLON.VertexBuffer.ColorKind
  19944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19948. */
  19949. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19950. if (!this._geometry) {
  19951. return null;
  19952. }
  19953. return this._geometry.getVerticesData(kind, copyWhenShared);
  19954. };
  19955. /**
  19956. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19957. * Returns `undefined` if the mesh has no geometry.
  19958. * Possible `kind` values :
  19959. * - BABYLON.VertexBuffer.PositionKind
  19960. * - BABYLON.VertexBuffer.UVKind
  19961. * - BABYLON.VertexBuffer.UV2Kind
  19962. * - BABYLON.VertexBuffer.UV3Kind
  19963. * - BABYLON.VertexBuffer.UV4Kind
  19964. * - BABYLON.VertexBuffer.UV5Kind
  19965. * - BABYLON.VertexBuffer.UV6Kind
  19966. * - BABYLON.VertexBuffer.ColorKind
  19967. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19968. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19969. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19970. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19971. */
  19972. Mesh.prototype.getVertexBuffer = function (kind) {
  19973. if (!this._geometry) {
  19974. return undefined;
  19975. }
  19976. return this._geometry.getVertexBuffer(kind);
  19977. };
  19978. /**
  19979. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19980. * Possible `kind` values :
  19981. * - BABYLON.VertexBuffer.PositionKind
  19982. * - BABYLON.VertexBuffer.UVKind
  19983. * - BABYLON.VertexBuffer.UV2Kind
  19984. * - BABYLON.VertexBuffer.UV3Kind
  19985. * - BABYLON.VertexBuffer.UV4Kind
  19986. * - BABYLON.VertexBuffer.UV5Kind
  19987. * - BABYLON.VertexBuffer.UV6Kind
  19988. * - BABYLON.VertexBuffer.ColorKind
  19989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19993. */
  19994. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19995. if (!this._geometry) {
  19996. if (this._delayInfo) {
  19997. return this._delayInfo.indexOf(kind) !== -1;
  19998. }
  19999. return false;
  20000. }
  20001. return this._geometry.isVerticesDataPresent(kind);
  20002. };
  20003. /**
  20004. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20005. * Possible `kind` values :
  20006. * - BABYLON.VertexBuffer.PositionKind
  20007. * - BABYLON.VertexBuffer.UVKind
  20008. * - BABYLON.VertexBuffer.UV2Kind
  20009. * - BABYLON.VertexBuffer.UV3Kind
  20010. * - BABYLON.VertexBuffer.UV4Kind
  20011. * - BABYLON.VertexBuffer.UV5Kind
  20012. * - BABYLON.VertexBuffer.UV6Kind
  20013. * - BABYLON.VertexBuffer.ColorKind
  20014. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20015. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20016. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20017. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20018. */
  20019. Mesh.prototype.getVerticesDataKinds = function () {
  20020. if (!this._geometry) {
  20021. var result = [];
  20022. if (this._delayInfo) {
  20023. this._delayInfo.forEach(function (kind, index, array) {
  20024. result.push(kind);
  20025. });
  20026. }
  20027. return result;
  20028. }
  20029. return this._geometry.getVerticesDataKinds();
  20030. };
  20031. /**
  20032. * Returns a positive integer : the total number of indices in this mesh geometry.
  20033. * Returns zero if the mesh has no geometry.
  20034. */
  20035. Mesh.prototype.getTotalIndices = function () {
  20036. if (!this._geometry) {
  20037. return 0;
  20038. }
  20039. return this._geometry.getTotalIndices();
  20040. };
  20041. /**
  20042. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20043. * 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.
  20044. * Returns an empty array if the mesh has no geometry.
  20045. */
  20046. Mesh.prototype.getIndices = function (copyWhenShared) {
  20047. if (!this._geometry) {
  20048. return [];
  20049. }
  20050. return this._geometry.getIndices(copyWhenShared);
  20051. };
  20052. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20053. get: function () {
  20054. return this._masterMesh !== null && this._masterMesh !== undefined;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. /**
  20060. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20061. */
  20062. Mesh.prototype.isReady = function () {
  20063. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20064. return false;
  20065. }
  20066. return _super.prototype.isReady.call(this);
  20067. };
  20068. /**
  20069. * Boolean : true if the mesh has been disposed.
  20070. */
  20071. Mesh.prototype.isDisposed = function () {
  20072. return this._isDisposed;
  20073. };
  20074. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20075. get: function () {
  20076. return this._sideOrientation;
  20077. },
  20078. /**
  20079. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20080. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20081. */
  20082. set: function (sideO) {
  20083. this._sideOrientation = sideO;
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20089. /**
  20090. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20091. * This property is pertinent only for updatable parametric shapes.
  20092. */
  20093. get: function () {
  20094. return this._areNormalsFrozen;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. /**
  20100. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20101. * It has no effect at all on other shapes.
  20102. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20103. */
  20104. Mesh.prototype.freezeNormals = function () {
  20105. this._areNormalsFrozen = true;
  20106. };
  20107. /**
  20108. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20109. * It has no effect at all on other shapes.
  20110. * It reactivates the mesh normals computation if it was previously frozen.
  20111. */
  20112. Mesh.prototype.unfreezeNormals = function () {
  20113. this._areNormalsFrozen = false;
  20114. };
  20115. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20116. /**
  20117. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20118. */
  20119. set: function (count) {
  20120. this._overridenInstanceCount = count;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. // Methods
  20126. Mesh.prototype._preActivate = function () {
  20127. var sceneRenderId = this.getScene().getRenderId();
  20128. if (this._preActivateId === sceneRenderId) {
  20129. return;
  20130. }
  20131. this._preActivateId = sceneRenderId;
  20132. this._visibleInstances = null;
  20133. };
  20134. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20135. if (this._visibleInstances) {
  20136. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20137. }
  20138. };
  20139. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20140. if (!this._visibleInstances) {
  20141. this._visibleInstances = {};
  20142. this._visibleInstances.defaultRenderId = renderId;
  20143. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20144. }
  20145. if (!this._visibleInstances[renderId]) {
  20146. this._visibleInstances[renderId] = new Array();
  20147. }
  20148. this._visibleInstances[renderId].push(instance);
  20149. };
  20150. /**
  20151. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20152. * This means the mesh underlying bounding box and sphere are recomputed.
  20153. */
  20154. Mesh.prototype.refreshBoundingInfo = function () {
  20155. if (this._boundingInfo.isLocked) {
  20156. return;
  20157. }
  20158. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20159. if (data) {
  20160. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20161. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20162. }
  20163. if (this.subMeshes) {
  20164. for (var index = 0; index < this.subMeshes.length; index++) {
  20165. this.subMeshes[index].refreshBoundingInfo();
  20166. }
  20167. }
  20168. this._updateBoundingInfo();
  20169. };
  20170. Mesh.prototype._createGlobalSubMesh = function () {
  20171. var totalVertices = this.getTotalVertices();
  20172. if (!totalVertices || !this.getIndices()) {
  20173. return null;
  20174. }
  20175. this.releaseSubMeshes();
  20176. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20177. };
  20178. Mesh.prototype.subdivide = function (count) {
  20179. if (count < 1) {
  20180. return;
  20181. }
  20182. var totalIndices = this.getTotalIndices();
  20183. var subdivisionSize = (totalIndices / count) | 0;
  20184. var offset = 0;
  20185. // Ensure that subdivisionSize is a multiple of 3
  20186. while (subdivisionSize % 3 !== 0) {
  20187. subdivisionSize++;
  20188. }
  20189. this.releaseSubMeshes();
  20190. for (var index = 0; index < count; index++) {
  20191. if (offset >= totalIndices) {
  20192. break;
  20193. }
  20194. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20195. offset += subdivisionSize;
  20196. }
  20197. this.synchronizeInstances();
  20198. };
  20199. /**
  20200. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20201. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20202. * The `data` are either a numeric array either a Float32Array.
  20203. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20204. * 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).
  20205. * Note that a new underlying VertexBuffer object is created each call.
  20206. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20207. *
  20208. * Possible `kind` values :
  20209. * - BABYLON.VertexBuffer.PositionKind
  20210. * - BABYLON.VertexBuffer.UVKind
  20211. * - BABYLON.VertexBuffer.UV2Kind
  20212. * - BABYLON.VertexBuffer.UV3Kind
  20213. * - BABYLON.VertexBuffer.UV4Kind
  20214. * - BABYLON.VertexBuffer.UV5Kind
  20215. * - BABYLON.VertexBuffer.UV6Kind
  20216. * - BABYLON.VertexBuffer.ColorKind
  20217. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20218. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20219. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20220. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20221. */
  20222. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20223. if (!this._geometry) {
  20224. var vertexData = new BABYLON.VertexData();
  20225. vertexData.set(data, kind);
  20226. var scene = this.getScene();
  20227. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20228. }
  20229. else {
  20230. this._geometry.setVerticesData(kind, data, updatable, stride);
  20231. }
  20232. };
  20233. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20234. if (!this._geometry) {
  20235. var scene = this.getScene();
  20236. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20237. }
  20238. this._geometry.setVerticesBuffer(buffer);
  20239. };
  20240. /**
  20241. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20242. * If the mesh has no geometry, it is simply returned as it is.
  20243. * The `data` are either a numeric array either a Float32Array.
  20244. * No new underlying VertexBuffer object is created.
  20245. * 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.
  20246. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20247. *
  20248. * Possible `kind` values :
  20249. * - BABYLON.VertexBuffer.PositionKind
  20250. * - BABYLON.VertexBuffer.UVKind
  20251. * - BABYLON.VertexBuffer.UV2Kind
  20252. * - BABYLON.VertexBuffer.UV3Kind
  20253. * - BABYLON.VertexBuffer.UV4Kind
  20254. * - BABYLON.VertexBuffer.UV5Kind
  20255. * - BABYLON.VertexBuffer.UV6Kind
  20256. * - BABYLON.VertexBuffer.ColorKind
  20257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20261. */
  20262. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20263. if (!this._geometry) {
  20264. return;
  20265. }
  20266. if (!makeItUnique) {
  20267. this._geometry.updateVerticesData(kind, data, updateExtends);
  20268. }
  20269. else {
  20270. this.makeGeometryUnique();
  20271. this.updateVerticesData(kind, data, updateExtends, false);
  20272. }
  20273. };
  20274. /**
  20275. * Deprecated since BabylonJS v2.3
  20276. */
  20277. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20278. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20279. if (!this._geometry) {
  20280. return;
  20281. }
  20282. if (!makeItUnique) {
  20283. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20284. }
  20285. else {
  20286. this.makeGeometryUnique();
  20287. this.updateVerticesDataDirectly(kind, data, offset, false);
  20288. }
  20289. };
  20290. /**
  20291. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20292. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20293. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20294. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20295. */
  20296. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20297. if (computeNormals === void 0) { computeNormals = true; }
  20298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20299. positionFunction(positions);
  20300. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20301. if (computeNormals) {
  20302. var indices = this.getIndices();
  20303. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20304. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20305. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20306. }
  20307. };
  20308. Mesh.prototype.makeGeometryUnique = function () {
  20309. if (!this._geometry) {
  20310. return;
  20311. }
  20312. var oldGeometry = this._geometry;
  20313. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20314. oldGeometry.releaseForMesh(this, true);
  20315. geometry.applyToMesh(this);
  20316. };
  20317. /**
  20318. * Sets the mesh indices.
  20319. * Expects an array populated with integers or a Int32Array.
  20320. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20321. * This method creates a new index buffer each call.
  20322. */
  20323. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20324. if (!this._geometry) {
  20325. var vertexData = new BABYLON.VertexData();
  20326. vertexData.indices = indices;
  20327. var scene = this.getScene();
  20328. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20329. }
  20330. else {
  20331. this._geometry.setIndices(indices, totalVertices);
  20332. }
  20333. };
  20334. /**
  20335. * Invert the geometry to move from a right handed system to a left handed one.
  20336. */
  20337. Mesh.prototype.toLeftHanded = function () {
  20338. if (!this._geometry) {
  20339. return;
  20340. }
  20341. this._geometry.toLeftHanded();
  20342. };
  20343. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20344. var engine = this.getScene().getEngine();
  20345. // Wireframe
  20346. var indexToBind;
  20347. if (this._unIndexed) {
  20348. indexToBind = null;
  20349. }
  20350. else {
  20351. switch (fillMode) {
  20352. case BABYLON.Material.PointFillMode:
  20353. indexToBind = null;
  20354. break;
  20355. case BABYLON.Material.WireFrameFillMode:
  20356. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20357. break;
  20358. default:
  20359. case BABYLON.Material.TriangleFillMode:
  20360. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20361. break;
  20362. }
  20363. }
  20364. // VBOs
  20365. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20366. };
  20367. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20368. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20369. return;
  20370. }
  20371. this.onBeforeDrawObservable.notifyObservers(this);
  20372. var engine = this.getScene().getEngine();
  20373. // Draw order
  20374. switch (fillMode) {
  20375. case BABYLON.Material.PointFillMode:
  20376. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20377. break;
  20378. case BABYLON.Material.WireFrameFillMode:
  20379. if (this._unIndexed) {
  20380. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20381. }
  20382. else {
  20383. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20384. }
  20385. break;
  20386. default:
  20387. if (this._unIndexed) {
  20388. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20389. }
  20390. else {
  20391. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20392. }
  20393. }
  20394. };
  20395. /**
  20396. * Registers for this mesh a javascript function called just before the rendering process.
  20397. * This function is passed the current mesh and doesn't return anything.
  20398. */
  20399. Mesh.prototype.registerBeforeRender = function (func) {
  20400. this.onBeforeRenderObservable.add(func);
  20401. };
  20402. /**
  20403. * Disposes a previously registered javascript function called before the rendering.
  20404. * This function is passed the current mesh and doesn't return anything.
  20405. */
  20406. Mesh.prototype.unregisterBeforeRender = function (func) {
  20407. this.onBeforeRenderObservable.removeCallback(func);
  20408. };
  20409. /**
  20410. * Registers for this mesh a javascript function called just after the rendering is complete.
  20411. * This function is passed the current mesh and doesn't return anything.
  20412. */
  20413. Mesh.prototype.registerAfterRender = function (func) {
  20414. this.onAfterRenderObservable.add(func);
  20415. };
  20416. /**
  20417. * Disposes a previously registered javascript function called after the rendering.
  20418. * This function is passed the current mesh and doesn't return anything.
  20419. */
  20420. Mesh.prototype.unregisterAfterRender = function (func) {
  20421. this.onAfterRenderObservable.removeCallback(func);
  20422. };
  20423. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20424. var scene = this.getScene();
  20425. this._batchCache.mustReturn = false;
  20426. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20427. this._batchCache.visibleInstances[subMeshId] = null;
  20428. if (this._visibleInstances) {
  20429. var currentRenderId = scene.getRenderId();
  20430. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20431. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20432. var selfRenderId = this._renderId;
  20433. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20434. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20435. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20436. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20437. }
  20438. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20439. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20440. this._batchCache.mustReturn = true;
  20441. return this._batchCache;
  20442. }
  20443. if (currentRenderId !== selfRenderId) {
  20444. this._batchCache.renderSelf[subMeshId] = false;
  20445. }
  20446. }
  20447. this._renderIdForInstances[subMeshId] = currentRenderId;
  20448. }
  20449. return this._batchCache;
  20450. };
  20451. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20452. var visibleInstances = batch.visibleInstances[subMesh._id];
  20453. var matricesCount = visibleInstances.length + 1;
  20454. var bufferSize = matricesCount * 16 * 4;
  20455. var currentInstancesBufferSize = this._instancesBufferSize;
  20456. var instancesBuffer = this._instancesBuffer;
  20457. while (this._instancesBufferSize < bufferSize) {
  20458. this._instancesBufferSize *= 2;
  20459. }
  20460. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20461. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20462. }
  20463. var offset = 0;
  20464. var instancesCount = 0;
  20465. var world = this.getWorldMatrix();
  20466. if (batch.renderSelf[subMesh._id]) {
  20467. world.copyToArray(this._instancesData, offset);
  20468. offset += 16;
  20469. instancesCount++;
  20470. }
  20471. if (visibleInstances) {
  20472. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20473. var instance = visibleInstances[instanceIndex];
  20474. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20475. offset += 16;
  20476. instancesCount++;
  20477. }
  20478. }
  20479. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20480. if (instancesBuffer) {
  20481. instancesBuffer.dispose();
  20482. }
  20483. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20484. this._instancesBuffer = instancesBuffer;
  20485. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20486. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20487. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20488. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20489. }
  20490. else {
  20491. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20492. }
  20493. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20494. this._draw(subMesh, fillMode, instancesCount);
  20495. engine.unbindInstanceAttributes();
  20496. };
  20497. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20498. var scene = this.getScene();
  20499. var engine = scene.getEngine();
  20500. if (hardwareInstancedRendering) {
  20501. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20502. }
  20503. else {
  20504. if (batch.renderSelf[subMesh._id]) {
  20505. // Draw
  20506. if (onBeforeDraw) {
  20507. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20508. }
  20509. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20510. }
  20511. if (batch.visibleInstances[subMesh._id]) {
  20512. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20513. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20514. // World
  20515. var world = instance.getWorldMatrix();
  20516. if (onBeforeDraw) {
  20517. onBeforeDraw(true, world, effectiveMaterial);
  20518. }
  20519. // Draw
  20520. this._draw(subMesh, fillMode);
  20521. }
  20522. }
  20523. }
  20524. };
  20525. /**
  20526. * Triggers the draw call for the mesh.
  20527. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20528. */
  20529. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20530. var scene = this.getScene();
  20531. // Managing instances
  20532. var batch = this._getInstancesRenderList(subMesh._id);
  20533. if (batch.mustReturn) {
  20534. return;
  20535. }
  20536. // Checking geometry state
  20537. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20538. return;
  20539. }
  20540. var callbackIndex;
  20541. this.onBeforeRenderObservable.notifyObservers(this);
  20542. var engine = scene.getEngine();
  20543. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20544. // Material
  20545. var effectiveMaterial = subMesh.getMaterial();
  20546. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20547. return;
  20548. }
  20549. // Outline - step 1
  20550. var savedDepthWrite = engine.getDepthWrite();
  20551. if (this.renderOutline) {
  20552. engine.setDepthWrite(false);
  20553. scene.getOutlineRenderer().render(subMesh, batch);
  20554. engine.setDepthWrite(savedDepthWrite);
  20555. }
  20556. effectiveMaterial._preBind();
  20557. var effect = effectiveMaterial.getEffect();
  20558. // Bind
  20559. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20560. this._bind(subMesh, effect, fillMode);
  20561. var world = this.getWorldMatrix();
  20562. effectiveMaterial.bind(world, this);
  20563. // Alpha mode
  20564. if (enableAlphaMode) {
  20565. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20566. }
  20567. // Draw
  20568. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20569. // Unbind
  20570. effectiveMaterial.unbind();
  20571. // Outline - step 2
  20572. if (this.renderOutline && savedDepthWrite) {
  20573. engine.setDepthWrite(true);
  20574. engine.setColorWrite(false);
  20575. scene.getOutlineRenderer().render(subMesh, batch);
  20576. engine.setColorWrite(true);
  20577. }
  20578. // Overlay
  20579. if (this.renderOverlay) {
  20580. var currentMode = engine.getAlphaMode();
  20581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20582. scene.getOutlineRenderer().render(subMesh, batch, true);
  20583. engine.setAlphaMode(currentMode);
  20584. }
  20585. this.onAfterRenderObservable.notifyObservers(this);
  20586. };
  20587. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20588. if (isInstance) {
  20589. effectiveMaterial.bindOnlyWorldMatrix(world);
  20590. }
  20591. };
  20592. /**
  20593. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20594. */
  20595. Mesh.prototype.getEmittedParticleSystems = function () {
  20596. var results = new Array();
  20597. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20598. var particleSystem = this.getScene().particleSystems[index];
  20599. if (particleSystem.emitter === this) {
  20600. results.push(particleSystem);
  20601. }
  20602. }
  20603. return results;
  20604. };
  20605. /**
  20606. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20607. */
  20608. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20609. var results = new Array();
  20610. var descendants = this.getDescendants();
  20611. descendants.push(this);
  20612. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20613. var particleSystem = this.getScene().particleSystems[index];
  20614. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20615. results.push(particleSystem);
  20616. }
  20617. }
  20618. return results;
  20619. };
  20620. Mesh.prototype._checkDelayState = function () {
  20621. var scene = this.getScene();
  20622. if (this._geometry) {
  20623. this._geometry.load(scene);
  20624. }
  20625. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20626. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20627. this._queueLoad(this, scene);
  20628. }
  20629. };
  20630. Mesh.prototype._queueLoad = function (mesh, scene) {
  20631. var _this = this;
  20632. scene._addPendingData(mesh);
  20633. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20634. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20635. if (data instanceof ArrayBuffer) {
  20636. _this._delayLoadingFunction(data, _this);
  20637. }
  20638. else {
  20639. _this._delayLoadingFunction(JSON.parse(data), _this);
  20640. }
  20641. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20642. scene._removePendingData(_this);
  20643. }, function () { }, scene.database, getBinaryData);
  20644. };
  20645. /**
  20646. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20647. */
  20648. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20649. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20650. return false;
  20651. }
  20652. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20653. return false;
  20654. }
  20655. this._checkDelayState();
  20656. return true;
  20657. };
  20658. /**
  20659. * Sets the mesh material by the material or multiMaterial `id` property.
  20660. * The material `id` is a string identifying the material or the multiMaterial.
  20661. * This method returns nothing.
  20662. */
  20663. Mesh.prototype.setMaterialByID = function (id) {
  20664. var materials = this.getScene().materials;
  20665. var index;
  20666. for (index = 0; index < materials.length; index++) {
  20667. if (materials[index].id === id) {
  20668. this.material = materials[index];
  20669. return;
  20670. }
  20671. }
  20672. // Multi
  20673. var multiMaterials = this.getScene().multiMaterials;
  20674. for (index = 0; index < multiMaterials.length; index++) {
  20675. if (multiMaterials[index].id === id) {
  20676. this.material = multiMaterials[index];
  20677. return;
  20678. }
  20679. }
  20680. };
  20681. /**
  20682. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20683. */
  20684. Mesh.prototype.getAnimatables = function () {
  20685. var results = [];
  20686. if (this.material) {
  20687. results.push(this.material);
  20688. }
  20689. if (this.skeleton) {
  20690. results.push(this.skeleton);
  20691. }
  20692. return results;
  20693. };
  20694. /**
  20695. * Modifies the mesh geometry according to the passed transformation matrix.
  20696. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20697. * The mesh normals are modified accordingly the same transformation.
  20698. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20699. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20700. */
  20701. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20702. // Position
  20703. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20704. return;
  20705. }
  20706. var submeshes = this.subMeshes.splice(0);
  20707. this._resetPointsArrayCache();
  20708. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20709. var temp = [];
  20710. var index;
  20711. for (index = 0; index < data.length; index += 3) {
  20712. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20713. }
  20714. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20715. // Normals
  20716. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20717. return;
  20718. }
  20719. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20720. temp = [];
  20721. for (index = 0; index < data.length; index += 3) {
  20722. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20723. }
  20724. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20725. // flip faces?
  20726. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20727. this.flipFaces();
  20728. }
  20729. // Restore submeshes
  20730. this.releaseSubMeshes();
  20731. this.subMeshes = submeshes;
  20732. };
  20733. /**
  20734. * Modifies the mesh geometry according to its own current World Matrix.
  20735. * The mesh World Matrix is then reset.
  20736. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20737. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20738. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20739. */
  20740. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20741. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20742. this.scaling.copyFromFloats(1, 1, 1);
  20743. this.position.copyFromFloats(0, 0, 0);
  20744. this.rotation.copyFromFloats(0, 0, 0);
  20745. //only if quaternion is already set
  20746. if (this.rotationQuaternion) {
  20747. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20748. }
  20749. this._worldMatrix = BABYLON.Matrix.Identity();
  20750. };
  20751. // Cache
  20752. Mesh.prototype._resetPointsArrayCache = function () {
  20753. this._positions = null;
  20754. };
  20755. Mesh.prototype._generatePointsArray = function () {
  20756. if (this._positions)
  20757. return true;
  20758. this._positions = [];
  20759. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20760. if (!data) {
  20761. return false;
  20762. }
  20763. for (var index = 0; index < data.length; index += 3) {
  20764. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20765. }
  20766. return true;
  20767. };
  20768. /**
  20769. * Returns a new Mesh object generated from the current mesh properties.
  20770. * This method must not get confused with createInstance().
  20771. * The parameter `name` is a string, the name given to the new mesh.
  20772. * The optional parameter `newParent` can be any Node object (default `null`).
  20773. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20774. * 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.
  20775. */
  20776. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20777. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20778. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20779. };
  20780. /**
  20781. * Disposes the mesh.
  20782. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20783. */
  20784. Mesh.prototype.dispose = function (doNotRecurse) {
  20785. if (this._geometry) {
  20786. this._geometry.releaseForMesh(this, true);
  20787. }
  20788. // Instances
  20789. if (this._instancesBuffer) {
  20790. this._instancesBuffer.dispose();
  20791. this._instancesBuffer = null;
  20792. }
  20793. while (this.instances.length) {
  20794. this.instances[0].dispose();
  20795. }
  20796. // Highlight layers.
  20797. var highlightLayers = this.getScene().highlightLayers;
  20798. for (var i = 0; i < highlightLayers.length; i++) {
  20799. var highlightLayer = highlightLayers[i];
  20800. if (highlightLayer) {
  20801. highlightLayer.removeMesh(this);
  20802. highlightLayer.removeExcludedMesh(this);
  20803. }
  20804. }
  20805. _super.prototype.dispose.call(this, doNotRecurse);
  20806. };
  20807. /**
  20808. * Modifies the mesh geometry according to a displacement map.
  20809. * 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.
  20810. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20811. * This method returns nothing.
  20812. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20813. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20814. * 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.
  20815. */
  20816. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20817. var _this = this;
  20818. var scene = this.getScene();
  20819. var onload = function (img) {
  20820. // Getting height map data
  20821. var canvas = document.createElement("canvas");
  20822. var context = canvas.getContext("2d");
  20823. var heightMapWidth = img.width;
  20824. var heightMapHeight = img.height;
  20825. canvas.width = heightMapWidth;
  20826. canvas.height = heightMapHeight;
  20827. context.drawImage(img, 0, 0);
  20828. // Create VertexData from map data
  20829. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20830. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20831. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20832. //execute success callback, if set
  20833. if (onSuccess) {
  20834. onSuccess(_this);
  20835. }
  20836. };
  20837. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20838. };
  20839. /**
  20840. * Modifies the mesh geometry according to a displacementMap buffer.
  20841. * 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.
  20842. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20843. * This method returns nothing.
  20844. * 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.
  20845. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20846. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20847. */
  20848. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20849. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20850. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20851. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20852. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20853. return;
  20854. }
  20855. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20856. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20857. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20858. var position = BABYLON.Vector3.Zero();
  20859. var normal = BABYLON.Vector3.Zero();
  20860. var uv = BABYLON.Vector2.Zero();
  20861. for (var index = 0; index < positions.length; index += 3) {
  20862. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20863. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20864. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20865. // Compute height
  20866. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20867. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20868. var pos = (u + v * heightMapWidth) * 4;
  20869. var r = buffer[pos] / 255.0;
  20870. var g = buffer[pos + 1] / 255.0;
  20871. var b = buffer[pos + 2] / 255.0;
  20872. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20873. normal.normalize();
  20874. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20875. position = position.add(normal);
  20876. position.toArray(positions, index);
  20877. }
  20878. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20879. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20880. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20881. };
  20882. /**
  20883. * Modify the mesh to get a flat shading rendering.
  20884. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20885. * This method returns nothing.
  20886. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20887. */
  20888. Mesh.prototype.convertToFlatShadedMesh = function () {
  20889. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20890. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20891. var kinds = this.getVerticesDataKinds();
  20892. var vbs = [];
  20893. var data = [];
  20894. var newdata = [];
  20895. var updatableNormals = false;
  20896. var kindIndex;
  20897. var kind;
  20898. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20899. kind = kinds[kindIndex];
  20900. var vertexBuffer = this.getVertexBuffer(kind);
  20901. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20902. updatableNormals = vertexBuffer.isUpdatable();
  20903. kinds.splice(kindIndex, 1);
  20904. kindIndex--;
  20905. continue;
  20906. }
  20907. vbs[kind] = vertexBuffer;
  20908. data[kind] = vbs[kind].getData();
  20909. newdata[kind] = [];
  20910. }
  20911. // Save previous submeshes
  20912. var previousSubmeshes = this.subMeshes.slice(0);
  20913. var indices = this.getIndices();
  20914. var totalIndices = this.getTotalIndices();
  20915. // Generating unique vertices per face
  20916. var index;
  20917. for (index = 0; index < totalIndices; index++) {
  20918. var vertexIndex = indices[index];
  20919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20920. kind = kinds[kindIndex];
  20921. var stride = vbs[kind].getStrideSize();
  20922. for (var offset = 0; offset < stride; offset++) {
  20923. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20924. }
  20925. }
  20926. }
  20927. // Updating faces & normal
  20928. var normals = [];
  20929. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20930. for (index = 0; index < totalIndices; index += 3) {
  20931. indices[index] = index;
  20932. indices[index + 1] = index + 1;
  20933. indices[index + 2] = index + 2;
  20934. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20935. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20936. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20937. var p1p2 = p1.subtract(p2);
  20938. var p3p2 = p3.subtract(p2);
  20939. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20940. // Store same normals for every vertex
  20941. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20942. normals.push(normal.x);
  20943. normals.push(normal.y);
  20944. normals.push(normal.z);
  20945. }
  20946. }
  20947. this.setIndices(indices);
  20948. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20949. // Updating vertex buffers
  20950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20951. kind = kinds[kindIndex];
  20952. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20953. }
  20954. // Updating submeshes
  20955. this.releaseSubMeshes();
  20956. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20957. var previousOne = previousSubmeshes[submeshIndex];
  20958. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20959. }
  20960. this.synchronizeInstances();
  20961. };
  20962. /**
  20963. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20964. * In other words, more vertices, no more indices and a single bigger VBO.
  20965. * This method returns nothing.
  20966. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20967. *
  20968. */
  20969. Mesh.prototype.convertToUnIndexedMesh = function () {
  20970. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20971. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20972. var kinds = this.getVerticesDataKinds();
  20973. var vbs = [];
  20974. var data = [];
  20975. var newdata = [];
  20976. var updatableNormals = false;
  20977. var kindIndex;
  20978. var kind;
  20979. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20980. kind = kinds[kindIndex];
  20981. var vertexBuffer = this.getVertexBuffer(kind);
  20982. vbs[kind] = vertexBuffer;
  20983. data[kind] = vbs[kind].getData();
  20984. newdata[kind] = [];
  20985. }
  20986. // Save previous submeshes
  20987. var previousSubmeshes = this.subMeshes.slice(0);
  20988. var indices = this.getIndices();
  20989. var totalIndices = this.getTotalIndices();
  20990. // Generating unique vertices per face
  20991. var index;
  20992. for (index = 0; index < totalIndices; index++) {
  20993. var vertexIndex = indices[index];
  20994. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20995. kind = kinds[kindIndex];
  20996. var stride = vbs[kind].getStrideSize();
  20997. for (var offset = 0; offset < stride; offset++) {
  20998. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20999. }
  21000. }
  21001. }
  21002. // Updating indices
  21003. for (index = 0; index < totalIndices; index += 3) {
  21004. indices[index] = index;
  21005. indices[index + 1] = index + 1;
  21006. indices[index + 2] = index + 2;
  21007. }
  21008. this.setIndices(indices);
  21009. // Updating vertex buffers
  21010. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21011. kind = kinds[kindIndex];
  21012. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21013. }
  21014. // Updating submeshes
  21015. this.releaseSubMeshes();
  21016. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21017. var previousOne = previousSubmeshes[submeshIndex];
  21018. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21019. }
  21020. this._unIndexed = true;
  21021. this.synchronizeInstances();
  21022. };
  21023. /**
  21024. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21025. * This method returns nothing.
  21026. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21027. */
  21028. Mesh.prototype.flipFaces = function (flipNormals) {
  21029. if (flipNormals === void 0) { flipNormals = false; }
  21030. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21031. var i;
  21032. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21033. for (i = 0; i < vertex_data.normals.length; i++) {
  21034. vertex_data.normals[i] *= -1;
  21035. }
  21036. }
  21037. var temp;
  21038. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21039. // reassign indices
  21040. temp = vertex_data.indices[i + 1];
  21041. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21042. vertex_data.indices[i + 2] = temp;
  21043. }
  21044. vertex_data.applyToMesh(this);
  21045. };
  21046. // Instances
  21047. /**
  21048. * Creates a new InstancedMesh object from the mesh model.
  21049. * An instance shares the same properties and the same material than its model.
  21050. * Only these properties of each instance can then be set individually :
  21051. * - position
  21052. * - rotation
  21053. * - rotationQuaternion
  21054. * - setPivotMatrix
  21055. * - scaling
  21056. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21057. * Warning : this method is not supported for Line mesh and LineSystem
  21058. */
  21059. Mesh.prototype.createInstance = function (name) {
  21060. return new BABYLON.InstancedMesh(name, this);
  21061. };
  21062. /**
  21063. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21064. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21065. * This method returns nothing.
  21066. */
  21067. Mesh.prototype.synchronizeInstances = function () {
  21068. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21069. var instance = this.instances[instanceIndex];
  21070. instance._syncSubMeshes();
  21071. }
  21072. };
  21073. /**
  21074. * Simplify the mesh according to the given array of settings.
  21075. * Function will return immediately and will simplify async. It returns nothing.
  21076. * @param settings a collection of simplification settings.
  21077. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21078. * @param type the type of simplification to run.
  21079. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21080. */
  21081. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21082. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21083. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21084. this.getScene().simplificationQueue.addTask({
  21085. settings: settings,
  21086. parallelProcessing: parallelProcessing,
  21087. mesh: this,
  21088. simplificationType: simplificationType,
  21089. successCallback: successCallback
  21090. });
  21091. };
  21092. /**
  21093. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21094. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21095. * This should be used together with the simplification to avoid disappearing triangles.
  21096. * @param successCallback an optional success callback to be called after the optimization finished.
  21097. */
  21098. Mesh.prototype.optimizeIndices = function (successCallback) {
  21099. var _this = this;
  21100. var indices = this.getIndices();
  21101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21102. var vectorPositions = [];
  21103. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21104. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21105. }
  21106. var dupes = [];
  21107. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21108. var realPos = vectorPositions.length - 1 - iteration;
  21109. var testedPosition = vectorPositions[realPos];
  21110. for (var j = 0; j < realPos; ++j) {
  21111. var againstPosition = vectorPositions[j];
  21112. if (testedPosition.equals(againstPosition)) {
  21113. dupes[realPos] = j;
  21114. break;
  21115. }
  21116. }
  21117. }, function () {
  21118. for (var i = 0; i < indices.length; ++i) {
  21119. indices[i] = dupes[indices[i]] || indices[i];
  21120. }
  21121. //indices are now reordered
  21122. var originalSubMeshes = _this.subMeshes.slice(0);
  21123. _this.setIndices(indices);
  21124. _this.subMeshes = originalSubMeshes;
  21125. if (successCallback) {
  21126. successCallback(_this);
  21127. }
  21128. });
  21129. };
  21130. // Statics
  21131. /**
  21132. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21133. * The parameter `parsedMesh` is the mesh to be copied.
  21134. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21135. */
  21136. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21137. var mesh = new Mesh(parsedMesh.name, scene);
  21138. mesh.id = parsedMesh.id;
  21139. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21140. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21141. if (parsedMesh.metadata !== undefined) {
  21142. mesh.metadata = parsedMesh.metadata;
  21143. }
  21144. if (parsedMesh.rotationQuaternion) {
  21145. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21146. }
  21147. else if (parsedMesh.rotation) {
  21148. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21149. }
  21150. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21151. if (parsedMesh.localMatrix) {
  21152. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21153. }
  21154. else if (parsedMesh.pivotMatrix) {
  21155. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21156. }
  21157. mesh.setEnabled(parsedMesh.isEnabled);
  21158. mesh.isVisible = parsedMesh.isVisible;
  21159. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21160. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21161. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21162. if (parsedMesh.applyFog !== undefined) {
  21163. mesh.applyFog = parsedMesh.applyFog;
  21164. }
  21165. if (parsedMesh.pickable !== undefined) {
  21166. mesh.isPickable = parsedMesh.pickable;
  21167. }
  21168. if (parsedMesh.alphaIndex !== undefined) {
  21169. mesh.alphaIndex = parsedMesh.alphaIndex;
  21170. }
  21171. mesh.receiveShadows = parsedMesh.receiveShadows;
  21172. mesh.billboardMode = parsedMesh.billboardMode;
  21173. if (parsedMesh.visibility !== undefined) {
  21174. mesh.visibility = parsedMesh.visibility;
  21175. }
  21176. mesh.checkCollisions = parsedMesh.checkCollisions;
  21177. if (parsedMesh.isBlocker !== undefined) {
  21178. mesh.isBlocker = parsedMesh.isBlocker;
  21179. }
  21180. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21181. // freezeWorldMatrix
  21182. if (parsedMesh.freezeWorldMatrix) {
  21183. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21184. }
  21185. // Parent
  21186. if (parsedMesh.parentId) {
  21187. mesh._waitingParentId = parsedMesh.parentId;
  21188. }
  21189. // Actions
  21190. if (parsedMesh.actions !== undefined) {
  21191. mesh._waitingActions = parsedMesh.actions;
  21192. }
  21193. // Overlay
  21194. if (parsedMesh.overlayAlpha !== undefined) {
  21195. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21196. }
  21197. if (parsedMesh.overlayColor !== undefined) {
  21198. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21199. }
  21200. if (parsedMesh.renderOverlay !== undefined) {
  21201. mesh.renderOverlay = parsedMesh.renderOverlay;
  21202. }
  21203. // Geometry
  21204. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21205. if (parsedMesh.delayLoadingFile) {
  21206. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21207. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21208. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21209. if (parsedMesh._binaryInfo) {
  21210. mesh._binaryInfo = parsedMesh._binaryInfo;
  21211. }
  21212. mesh._delayInfo = [];
  21213. if (parsedMesh.hasUVs) {
  21214. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21215. }
  21216. if (parsedMesh.hasUVs2) {
  21217. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21218. }
  21219. if (parsedMesh.hasUVs3) {
  21220. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21221. }
  21222. if (parsedMesh.hasUVs4) {
  21223. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21224. }
  21225. if (parsedMesh.hasUVs5) {
  21226. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21227. }
  21228. if (parsedMesh.hasUVs6) {
  21229. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21230. }
  21231. if (parsedMesh.hasColors) {
  21232. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21233. }
  21234. if (parsedMesh.hasMatricesIndices) {
  21235. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21236. }
  21237. if (parsedMesh.hasMatricesWeights) {
  21238. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21239. }
  21240. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21241. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21242. mesh._checkDelayState();
  21243. }
  21244. }
  21245. else {
  21246. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21247. }
  21248. // Material
  21249. if (parsedMesh.materialId) {
  21250. mesh.setMaterialByID(parsedMesh.materialId);
  21251. }
  21252. else {
  21253. mesh.material = null;
  21254. }
  21255. // Skeleton
  21256. if (parsedMesh.skeletonId > -1) {
  21257. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21258. if (parsedMesh.numBoneInfluencers) {
  21259. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21260. }
  21261. }
  21262. // Animations
  21263. if (parsedMesh.animations) {
  21264. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21265. var parsedAnimation = parsedMesh.animations[animationIndex];
  21266. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21267. }
  21268. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21269. }
  21270. if (parsedMesh.autoAnimate) {
  21271. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21272. }
  21273. // Layer Mask
  21274. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21275. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21276. }
  21277. else {
  21278. mesh.layerMask = 0x0FFFFFFF;
  21279. }
  21280. //(Deprecated) physics
  21281. if (parsedMesh.physicsImpostor) {
  21282. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21283. mass: parsedMesh.physicsMass,
  21284. friction: parsedMesh.physicsFriction,
  21285. restitution: parsedMesh.physicsRestitution
  21286. }, scene);
  21287. }
  21288. // Instances
  21289. if (parsedMesh.instances) {
  21290. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21291. var parsedInstance = parsedMesh.instances[index];
  21292. var instance = mesh.createInstance(parsedInstance.name);
  21293. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21294. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21295. if (parsedInstance.parentId) {
  21296. instance._waitingParentId = parsedInstance.parentId;
  21297. }
  21298. if (parsedInstance.rotationQuaternion) {
  21299. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21300. }
  21301. else if (parsedInstance.rotation) {
  21302. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21303. }
  21304. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21305. instance.checkCollisions = mesh.checkCollisions;
  21306. if (parsedMesh.animations) {
  21307. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21308. parsedAnimation = parsedMesh.animations[animationIndex];
  21309. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21310. }
  21311. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21312. }
  21313. }
  21314. }
  21315. return mesh;
  21316. };
  21317. /**
  21318. * Creates a ribbon mesh.
  21319. * Please consider using the same method from the MeshBuilder class instead.
  21320. * 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.
  21321. *
  21322. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21323. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21324. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21325. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21326. * 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.
  21327. * 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.
  21328. * 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
  21329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21332. */
  21333. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21334. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21335. pathArray: pathArray,
  21336. closeArray: closeArray,
  21337. closePath: closePath,
  21338. offset: offset,
  21339. updatable: updatable,
  21340. sideOrientation: sideOrientation,
  21341. instance: instance
  21342. }, scene);
  21343. };
  21344. /**
  21345. * Creates a plane polygonal mesh. By default, this is a disc.
  21346. * Please consider using the same method from the MeshBuilder class instead.
  21347. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21348. * 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.
  21349. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21352. */
  21353. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21354. var options = {
  21355. radius: radius,
  21356. tessellation: tessellation,
  21357. sideOrientation: sideOrientation,
  21358. updatable: updatable
  21359. };
  21360. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21361. };
  21362. /**
  21363. * Creates a box mesh.
  21364. * Please consider using the same method from the MeshBuilder class instead.
  21365. * The parameter `size` sets the size (float) of each box side (default 1).
  21366. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21369. */
  21370. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21371. var options = {
  21372. size: size,
  21373. sideOrientation: sideOrientation,
  21374. updatable: updatable
  21375. };
  21376. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21377. };
  21378. /**
  21379. * Creates a sphere mesh.
  21380. * Please consider using the same method from the MeshBuilder class instead.
  21381. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21382. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21383. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21384. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21386. */
  21387. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21388. var options = {
  21389. segments: segments,
  21390. diameterX: diameter,
  21391. diameterY: diameter,
  21392. diameterZ: diameter,
  21393. sideOrientation: sideOrientation,
  21394. updatable: updatable
  21395. };
  21396. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21397. };
  21398. /**
  21399. * Creates a cylinder or a cone mesh.
  21400. * Please consider using the same method from the MeshBuilder class instead.
  21401. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21402. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21403. * 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.
  21404. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21405. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21409. */
  21410. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21411. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21412. if (scene !== undefined) {
  21413. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21414. updatable = scene;
  21415. }
  21416. scene = subdivisions;
  21417. subdivisions = 1;
  21418. }
  21419. var options = {
  21420. height: height,
  21421. diameterTop: diameterTop,
  21422. diameterBottom: diameterBottom,
  21423. tessellation: tessellation,
  21424. subdivisions: subdivisions,
  21425. sideOrientation: sideOrientation,
  21426. updatable: updatable
  21427. };
  21428. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21429. };
  21430. // Torus (Code from SharpDX.org)
  21431. /**
  21432. * Creates a torus mesh.
  21433. * Please consider using the same method from the MeshBuilder class instead.
  21434. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21435. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21436. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21438. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21440. */
  21441. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21442. var options = {
  21443. diameter: diameter,
  21444. thickness: thickness,
  21445. tessellation: tessellation,
  21446. sideOrientation: sideOrientation,
  21447. updatable: updatable
  21448. };
  21449. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21450. };
  21451. /**
  21452. * Creates a torus knot mesh.
  21453. * Please consider using the same method from the MeshBuilder class instead.
  21454. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21455. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21456. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21457. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21461. */
  21462. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21463. var options = {
  21464. radius: radius,
  21465. tube: tube,
  21466. radialSegments: radialSegments,
  21467. tubularSegments: tubularSegments,
  21468. p: p,
  21469. q: q,
  21470. sideOrientation: sideOrientation,
  21471. updatable: updatable
  21472. };
  21473. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21474. };
  21475. /**
  21476. * Creates a line mesh.
  21477. * Please consider using the same method from the MeshBuilder class instead.
  21478. * 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.
  21479. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21480. * The parameter `points` is an array successive Vector3.
  21481. * 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
  21482. * When updating an instance, remember that only point positions can change, not the number of points.
  21483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21484. */
  21485. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21486. var options = {
  21487. points: points,
  21488. updatable: updatable,
  21489. instance: instance
  21490. };
  21491. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21492. };
  21493. /**
  21494. * Creates a dashed line mesh.
  21495. * Please consider using the same method from the MeshBuilder class instead.
  21496. * 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.
  21497. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21498. * The parameter `points` is an array successive Vector3.
  21499. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21500. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21501. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21502. * 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
  21503. * When updating an instance, remember that only point positions can change, not the number of points.
  21504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21505. */
  21506. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21507. var options = {
  21508. points: points,
  21509. dashSize: dashSize,
  21510. gapSize: gapSize,
  21511. dashNb: dashNb,
  21512. updatable: updatable,
  21513. instance: instance
  21514. };
  21515. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21516. };
  21517. /**
  21518. * Creates an extruded shape mesh.
  21519. * 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.
  21520. * Please consider using the same method from the MeshBuilder class instead.
  21521. *
  21522. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21523. * 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
  21524. * extruded along the Z axis.
  21525. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21526. * 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.
  21527. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21528. * 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
  21529. * 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
  21530. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21534. */
  21535. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21536. var options = {
  21537. shape: shape,
  21538. path: path,
  21539. scale: scale,
  21540. rotation: rotation,
  21541. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21542. sideOrientation: sideOrientation,
  21543. instance: instance,
  21544. updatable: updatable
  21545. };
  21546. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21547. };
  21548. /**
  21549. * Creates an custom extruded shape mesh.
  21550. * 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.
  21551. * Please consider using the same method from the MeshBuilder class instead.
  21552. *
  21553. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21554. * 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
  21555. * extruded along the Z axis.
  21556. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21557. * 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
  21558. * and the distance of this point from the begining of the path :
  21559. * ```javascript
  21560. * var rotationFunction = function(i, distance) {
  21561. * // do things
  21562. * return rotationValue; }
  21563. * ```
  21564. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21565. * 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
  21566. * and the distance of this point from the begining of the path :
  21567. * ```javascript
  21568. * var scaleFunction = function(i, distance) {
  21569. * // do things
  21570. * return scaleValue;}
  21571. * ```
  21572. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21573. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21574. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21575. * 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
  21576. * 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
  21577. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21579. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21581. */
  21582. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21583. var options = {
  21584. shape: shape,
  21585. path: path,
  21586. scaleFunction: scaleFunction,
  21587. rotationFunction: rotationFunction,
  21588. ribbonCloseArray: ribbonCloseArray,
  21589. ribbonClosePath: ribbonClosePath,
  21590. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21591. sideOrientation: sideOrientation,
  21592. instance: instance,
  21593. updatable: updatable
  21594. };
  21595. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21596. };
  21597. /**
  21598. * Creates lathe mesh.
  21599. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21600. * Please consider using the same method from the MeshBuilder class instead.
  21601. * 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
  21602. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21603. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21604. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21608. */
  21609. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21610. var options = {
  21611. shape: shape,
  21612. radius: radius,
  21613. tessellation: tessellation,
  21614. sideOrientation: sideOrientation,
  21615. updatable: updatable
  21616. };
  21617. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21618. };
  21619. /**
  21620. * Creates a plane mesh.
  21621. * Please consider using the same method from the MeshBuilder class instead.
  21622. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21626. */
  21627. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21628. var options = {
  21629. size: size,
  21630. width: size,
  21631. height: size,
  21632. sideOrientation: sideOrientation,
  21633. updatable: updatable
  21634. };
  21635. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21636. };
  21637. /**
  21638. * Creates a ground mesh.
  21639. * Please consider using the same method from the MeshBuilder class instead.
  21640. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21641. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21643. */
  21644. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21645. var options = {
  21646. width: width,
  21647. height: height,
  21648. subdivisions: subdivisions,
  21649. updatable: updatable
  21650. };
  21651. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21652. };
  21653. /**
  21654. * Creates a tiled ground mesh.
  21655. * Please consider using the same method from the MeshBuilder class instead.
  21656. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21657. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21658. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21659. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21660. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21661. * numbers of subdivisions on the ground width and height of each tile.
  21662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21663. */
  21664. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21665. var options = {
  21666. xmin: xmin,
  21667. zmin: zmin,
  21668. xmax: xmax,
  21669. zmax: zmax,
  21670. subdivisions: subdivisions,
  21671. precision: precision,
  21672. updatable: updatable
  21673. };
  21674. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21675. };
  21676. /**
  21677. * Creates a ground mesh from a height map.
  21678. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21679. * Please consider using the same method from the MeshBuilder class instead.
  21680. * The parameter `url` sets the URL of the height map image resource.
  21681. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21682. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21683. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21684. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21685. * 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).
  21686. * This function is passed the newly built mesh :
  21687. * ```javascript
  21688. * function(mesh) { // do things
  21689. * return; }
  21690. * ```
  21691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21692. */
  21693. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21694. var options = {
  21695. width: width,
  21696. height: height,
  21697. subdivisions: subdivisions,
  21698. minHeight: minHeight,
  21699. maxHeight: maxHeight,
  21700. updatable: updatable,
  21701. onReady: onReady
  21702. };
  21703. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21704. };
  21705. /**
  21706. * Creates a tube mesh.
  21707. * 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.
  21708. * Please consider using the same method from the MeshBuilder class instead.
  21709. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21710. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21711. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21712. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21713. * 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.
  21714. * It must return a radius value (positive float) :
  21715. * ```javascript
  21716. * var radiusFunction = function(i, distance) {
  21717. * // do things
  21718. * return radius; }
  21719. * ```
  21720. * 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
  21721. * 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
  21722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21723. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21725. */
  21726. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21727. var options = {
  21728. path: path,
  21729. radius: radius,
  21730. tessellation: tessellation,
  21731. radiusFunction: radiusFunction,
  21732. arc: 1,
  21733. cap: cap,
  21734. updatable: updatable,
  21735. sideOrientation: sideOrientation,
  21736. instance: instance
  21737. };
  21738. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21739. };
  21740. /**
  21741. * Creates a polyhedron mesh.
  21742. * Please consider using the same method from the MeshBuilder class instead.
  21743. * 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
  21744. * to choose the wanted type.
  21745. * The parameter `size` (positive float, default 1) sets the polygon size.
  21746. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21747. * 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`.
  21748. * 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
  21749. * 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)`).
  21750. * 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
  21751. * 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.
  21752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21753. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21755. */
  21756. Mesh.CreatePolyhedron = function (name, options, scene) {
  21757. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21758. };
  21759. /**
  21760. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21761. * Please consider using the same method from the MeshBuilder class instead.
  21762. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21763. * 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`).
  21764. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21765. * 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.
  21766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21769. */
  21770. Mesh.CreateIcoSphere = function (name, options, scene) {
  21771. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21772. };
  21773. /**
  21774. * Creates a decal mesh.
  21775. * Please consider using the same method from the MeshBuilder class instead.
  21776. * 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.
  21777. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21778. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21779. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21780. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21781. */
  21782. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21783. var options = {
  21784. position: position,
  21785. normal: normal,
  21786. size: size,
  21787. angle: angle
  21788. };
  21789. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21790. };
  21791. // Skeletons
  21792. /**
  21793. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21794. */
  21795. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21796. var source;
  21797. if (!this._sourcePositions) {
  21798. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21799. this._sourcePositions = new Float32Array(source);
  21800. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21801. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21802. }
  21803. }
  21804. return this._sourcePositions;
  21805. };
  21806. /**
  21807. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21808. */
  21809. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21810. var source;
  21811. if (!this._sourceNormals) {
  21812. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21813. this._sourceNormals = new Float32Array(source);
  21814. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21816. }
  21817. }
  21818. return this._sourceNormals;
  21819. };
  21820. /**
  21821. * Update the vertex buffers by applying transformation from the bones
  21822. * @param {skeleton} skeleton to apply
  21823. */
  21824. Mesh.prototype.applySkeleton = function (skeleton) {
  21825. if (!this.geometry) {
  21826. return;
  21827. }
  21828. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21829. return;
  21830. }
  21831. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21832. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21833. return this;
  21834. }
  21835. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21836. return this;
  21837. }
  21838. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21839. return this;
  21840. }
  21841. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21842. return this;
  21843. }
  21844. if (!this._sourcePositions) {
  21845. var submeshes = this.subMeshes.slice();
  21846. this.setPositionsForCPUSkinning();
  21847. this.subMeshes = submeshes;
  21848. }
  21849. if (!this._sourceNormals) {
  21850. this.setNormalsForCPUSkinning();
  21851. }
  21852. // positionsData checks for not being Float32Array will only pass at most once
  21853. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21854. if (!(positionsData instanceof Float32Array)) {
  21855. positionsData = new Float32Array(positionsData);
  21856. }
  21857. // normalsData checks for not being Float32Array will only pass at most once
  21858. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21859. if (!(normalsData instanceof Float32Array)) {
  21860. normalsData = new Float32Array(normalsData);
  21861. }
  21862. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21863. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21864. var needExtras = this.numBoneInfluencers > 4;
  21865. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21866. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21867. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21868. var tempVector3 = BABYLON.Vector3.Zero();
  21869. var finalMatrix = new BABYLON.Matrix();
  21870. var tempMatrix = new BABYLON.Matrix();
  21871. var matWeightIdx = 0;
  21872. var inf;
  21873. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21874. var weight;
  21875. for (inf = 0; inf < 4; inf++) {
  21876. weight = matricesWeightsData[matWeightIdx + inf];
  21877. if (weight > 0) {
  21878. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21879. finalMatrix.addToSelf(tempMatrix);
  21880. }
  21881. else
  21882. break;
  21883. }
  21884. if (needExtras) {
  21885. for (inf = 0; inf < 4; inf++) {
  21886. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21887. if (weight > 0) {
  21888. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21889. finalMatrix.addToSelf(tempMatrix);
  21890. }
  21891. else
  21892. break;
  21893. }
  21894. }
  21895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21896. tempVector3.toArray(positionsData, index);
  21897. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21898. tempVector3.toArray(normalsData, index);
  21899. finalMatrix.reset();
  21900. }
  21901. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21902. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21903. return this;
  21904. };
  21905. // Tools
  21906. /**
  21907. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21908. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21909. */
  21910. Mesh.MinMax = function (meshes) {
  21911. var minVector = null;
  21912. var maxVector = null;
  21913. meshes.forEach(function (mesh, index, array) {
  21914. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21915. if (!minVector) {
  21916. minVector = boundingBox.minimumWorld;
  21917. maxVector = boundingBox.maximumWorld;
  21918. }
  21919. else {
  21920. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21921. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21922. }
  21923. });
  21924. return {
  21925. min: minVector,
  21926. max: maxVector
  21927. };
  21928. };
  21929. /**
  21930. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21931. */
  21932. Mesh.Center = function (meshesOrMinMaxVector) {
  21933. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21934. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21935. };
  21936. /**
  21937. * Merge the array of meshes into a single mesh for performance reasons.
  21938. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21939. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21940. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21941. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21942. */
  21943. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21944. if (disposeSource === void 0) { disposeSource = true; }
  21945. var index;
  21946. if (!allow32BitsIndices) {
  21947. var totalVertices = 0;
  21948. // Counting vertices
  21949. for (index = 0; index < meshes.length; index++) {
  21950. if (meshes[index]) {
  21951. totalVertices += meshes[index].getTotalVertices();
  21952. if (totalVertices > 65536) {
  21953. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21954. return null;
  21955. }
  21956. }
  21957. }
  21958. }
  21959. // Merge
  21960. var vertexData;
  21961. var otherVertexData;
  21962. var source;
  21963. for (index = 0; index < meshes.length; index++) {
  21964. if (meshes[index]) {
  21965. meshes[index].computeWorldMatrix(true);
  21966. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21967. otherVertexData.transform(meshes[index].getWorldMatrix());
  21968. if (vertexData) {
  21969. vertexData.merge(otherVertexData);
  21970. }
  21971. else {
  21972. vertexData = otherVertexData;
  21973. source = meshes[index];
  21974. }
  21975. }
  21976. }
  21977. if (!meshSubclass) {
  21978. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21979. }
  21980. vertexData.applyToMesh(meshSubclass);
  21981. // Setting properties
  21982. meshSubclass.material = source.material;
  21983. meshSubclass.checkCollisions = source.checkCollisions;
  21984. // Cleaning
  21985. if (disposeSource) {
  21986. for (index = 0; index < meshes.length; index++) {
  21987. if (meshes[index]) {
  21988. meshes[index].dispose();
  21989. }
  21990. }
  21991. }
  21992. return meshSubclass;
  21993. };
  21994. // Consts
  21995. Mesh._FRONTSIDE = 0;
  21996. Mesh._BACKSIDE = 1;
  21997. Mesh._DOUBLESIDE = 2;
  21998. Mesh._DEFAULTSIDE = 0;
  21999. Mesh._NO_CAP = 0;
  22000. Mesh._CAP_START = 1;
  22001. Mesh._CAP_END = 2;
  22002. Mesh._CAP_ALL = 3;
  22003. return Mesh;
  22004. }(BABYLON.AbstractMesh));
  22005. BABYLON.Mesh = Mesh;
  22006. })(BABYLON || (BABYLON = {}));
  22007. //# sourceMappingURL=babylon.mesh.js.map
  22008. var BABYLON;
  22009. (function (BABYLON) {
  22010. var SubMesh = (function () {
  22011. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22012. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22013. this.materialIndex = materialIndex;
  22014. this.verticesStart = verticesStart;
  22015. this.verticesCount = verticesCount;
  22016. this.indexStart = indexStart;
  22017. this.indexCount = indexCount;
  22018. this._renderId = 0;
  22019. this._mesh = mesh;
  22020. this._renderingMesh = renderingMesh || mesh;
  22021. mesh.subMeshes.push(this);
  22022. this._trianglePlanes = [];
  22023. this._id = mesh.subMeshes.length - 1;
  22024. if (createBoundingBox) {
  22025. this.refreshBoundingInfo();
  22026. mesh.computeWorldMatrix(true);
  22027. }
  22028. }
  22029. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22030. get: function () {
  22031. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. SubMesh.prototype.getBoundingInfo = function () {
  22037. if (this.IsGlobal) {
  22038. return this._mesh.getBoundingInfo();
  22039. }
  22040. return this._boundingInfo;
  22041. };
  22042. SubMesh.prototype.getMesh = function () {
  22043. return this._mesh;
  22044. };
  22045. SubMesh.prototype.getRenderingMesh = function () {
  22046. return this._renderingMesh;
  22047. };
  22048. SubMesh.prototype.getMaterial = function () {
  22049. var rootMaterial = this._renderingMesh.material;
  22050. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22051. var multiMaterial = rootMaterial;
  22052. return multiMaterial.getSubMaterial(this.materialIndex);
  22053. }
  22054. if (!rootMaterial) {
  22055. return this._mesh.getScene().defaultMaterial;
  22056. }
  22057. return rootMaterial;
  22058. };
  22059. // Methods
  22060. SubMesh.prototype.refreshBoundingInfo = function () {
  22061. this._lastColliderWorldVertices = null;
  22062. if (this.IsGlobal) {
  22063. return;
  22064. }
  22065. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22066. if (!data) {
  22067. this._boundingInfo = this._mesh._boundingInfo;
  22068. return;
  22069. }
  22070. var indices = this._renderingMesh.getIndices();
  22071. var extend;
  22072. //is this the only submesh?
  22073. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22074. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22075. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22076. }
  22077. else {
  22078. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22079. }
  22080. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22081. };
  22082. SubMesh.prototype._checkCollision = function (collider) {
  22083. return this.getBoundingInfo()._checkCollision(collider);
  22084. };
  22085. SubMesh.prototype.updateBoundingInfo = function (world) {
  22086. if (!this.getBoundingInfo()) {
  22087. this.refreshBoundingInfo();
  22088. }
  22089. this.getBoundingInfo().update(world);
  22090. };
  22091. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22092. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22093. };
  22094. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22095. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22096. };
  22097. SubMesh.prototype.render = function (enableAlphaMode) {
  22098. this._renderingMesh.render(this, enableAlphaMode);
  22099. };
  22100. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22101. if (!this._linesIndexBuffer) {
  22102. var linesIndices = [];
  22103. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22104. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22105. }
  22106. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22107. this.linesIndexCount = linesIndices.length;
  22108. }
  22109. return this._linesIndexBuffer;
  22110. };
  22111. SubMesh.prototype.canIntersects = function (ray) {
  22112. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22113. };
  22114. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22115. var intersectInfo = null;
  22116. // LineMesh first as it's also a Mesh...
  22117. if (this._mesh instanceof BABYLON.LinesMesh) {
  22118. var lineMesh = this._mesh;
  22119. // Line test
  22120. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22121. var p0 = positions[indices[index]];
  22122. var p1 = positions[indices[index + 1]];
  22123. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22124. if (length < 0) {
  22125. continue;
  22126. }
  22127. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22128. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22129. if (fastCheck) {
  22130. break;
  22131. }
  22132. }
  22133. }
  22134. }
  22135. else {
  22136. // Triangles test
  22137. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22138. var p0 = positions[indices[index]];
  22139. var p1 = positions[indices[index + 1]];
  22140. var p2 = positions[indices[index + 2]];
  22141. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22142. if (currentIntersectInfo) {
  22143. if (currentIntersectInfo.distance < 0) {
  22144. continue;
  22145. }
  22146. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22147. intersectInfo = currentIntersectInfo;
  22148. intersectInfo.faceId = index / 3;
  22149. if (fastCheck) {
  22150. break;
  22151. }
  22152. }
  22153. }
  22154. }
  22155. }
  22156. return intersectInfo;
  22157. };
  22158. // Clone
  22159. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22160. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22161. if (!this.IsGlobal) {
  22162. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22163. }
  22164. return result;
  22165. };
  22166. // Dispose
  22167. SubMesh.prototype.dispose = function () {
  22168. if (this._linesIndexBuffer) {
  22169. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22170. this._linesIndexBuffer = null;
  22171. }
  22172. // Remove from mesh
  22173. var index = this._mesh.subMeshes.indexOf(this);
  22174. this._mesh.subMeshes.splice(index, 1);
  22175. };
  22176. // Statics
  22177. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22178. var minVertexIndex = Number.MAX_VALUE;
  22179. var maxVertexIndex = -Number.MAX_VALUE;
  22180. renderingMesh = renderingMesh || mesh;
  22181. var indices = renderingMesh.getIndices();
  22182. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22183. var vertexIndex = indices[index];
  22184. if (vertexIndex < minVertexIndex)
  22185. minVertexIndex = vertexIndex;
  22186. if (vertexIndex > maxVertexIndex)
  22187. maxVertexIndex = vertexIndex;
  22188. }
  22189. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22190. };
  22191. return SubMesh;
  22192. }());
  22193. BABYLON.SubMesh = SubMesh;
  22194. })(BABYLON || (BABYLON = {}));
  22195. //# sourceMappingURL=babylon.subMesh.js.map
  22196. var BABYLON;
  22197. (function (BABYLON) {
  22198. var MeshBuilder = (function () {
  22199. function MeshBuilder() {
  22200. }
  22201. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22202. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22203. return BABYLON.Mesh.DOUBLESIDE;
  22204. }
  22205. if (orientation === undefined || orientation === null) {
  22206. return BABYLON.Mesh.FRONTSIDE;
  22207. }
  22208. return orientation;
  22209. };
  22210. /**
  22211. * Creates a box mesh.
  22212. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22213. * The parameter `size` sets the size (float) of each box side (default 1).
  22214. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22215. * 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).
  22216. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  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.CreateBox = function (name, options, scene) {
  22222. var box = new BABYLON.Mesh(name, scene);
  22223. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22224. box.sideOrientation = options.sideOrientation;
  22225. var vertexData = BABYLON.VertexData.CreateBox(options);
  22226. vertexData.applyToMesh(box, options.updatable);
  22227. return box;
  22228. };
  22229. /**
  22230. * Creates a sphere mesh.
  22231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22232. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22233. * 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`).
  22234. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22235. * 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
  22236. * 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).
  22237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22240. */
  22241. MeshBuilder.CreateSphere = function (name, options, scene) {
  22242. var sphere = new BABYLON.Mesh(name, scene);
  22243. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22244. sphere.sideOrientation = options.sideOrientation;
  22245. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22246. vertexData.applyToMesh(sphere, options.updatable);
  22247. return sphere;
  22248. };
  22249. /**
  22250. * Creates a plane polygonal mesh. By default, this is a disc.
  22251. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22252. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22253. * 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.
  22254. * 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
  22255. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22258. */
  22259. MeshBuilder.CreateDisc = function (name, options, scene) {
  22260. var disc = new BABYLON.Mesh(name, scene);
  22261. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22262. disc.sideOrientation = options.sideOrientation;
  22263. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22264. vertexData.applyToMesh(disc, options.updatable);
  22265. return disc;
  22266. };
  22267. /**
  22268. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22269. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22270. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22271. * 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`).
  22272. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22273. * 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.
  22274. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22275. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22277. */
  22278. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22279. var sphere = new BABYLON.Mesh(name, scene);
  22280. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22281. sphere.sideOrientation = options.sideOrientation;
  22282. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22283. vertexData.applyToMesh(sphere, options.updatable);
  22284. return sphere;
  22285. };
  22286. ;
  22287. /**
  22288. * Creates a ribbon mesh.
  22289. * 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.
  22290. *
  22291. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22292. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22293. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22294. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22295. * 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.
  22296. * 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.
  22297. * 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
  22298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22300. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22302. */
  22303. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22304. var pathArray = options.pathArray;
  22305. var closeArray = options.closeArray;
  22306. var closePath = options.closePath;
  22307. var offset = options.offset;
  22308. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22309. var instance = options.instance;
  22310. var updatable = options.updatable;
  22311. if (instance) {
  22312. // positionFunction : ribbon case
  22313. // only pathArray and sideOrientation parameters are taken into account for positions update
  22314. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22315. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22316. var positionFunction = function (positions) {
  22317. var minlg = pathArray[0].length;
  22318. var i = 0;
  22319. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22320. for (var si = 1; si <= ns; si++) {
  22321. for (var p = 0; p < pathArray.length; p++) {
  22322. var path = pathArray[p];
  22323. var l = path.length;
  22324. minlg = (minlg < l) ? minlg : l;
  22325. var j = 0;
  22326. while (j < minlg) {
  22327. positions[i] = path[j].x;
  22328. positions[i + 1] = path[j].y;
  22329. positions[i + 2] = path[j].z;
  22330. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22331. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22332. }
  22333. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22334. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22335. }
  22336. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22337. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22338. }
  22339. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22340. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22341. }
  22342. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22343. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22344. }
  22345. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22346. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22347. }
  22348. j++;
  22349. i += 3;
  22350. }
  22351. if (instance._closePath) {
  22352. positions[i] = path[0].x;
  22353. positions[i + 1] = path[0].y;
  22354. positions[i + 2] = path[0].z;
  22355. i += 3;
  22356. }
  22357. }
  22358. }
  22359. };
  22360. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22361. positionFunction(positions);
  22362. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22363. instance._boundingInfo.update(instance._worldMatrix);
  22364. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22365. if (!(instance.areNormalsFrozen)) {
  22366. var indices = instance.getIndices();
  22367. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22368. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22369. if (instance._closePath) {
  22370. var indexFirst = 0;
  22371. var indexLast = 0;
  22372. for (var p = 0; p < pathArray.length; p++) {
  22373. indexFirst = instance._idx[p] * 3;
  22374. if (p + 1 < pathArray.length) {
  22375. indexLast = (instance._idx[p + 1] - 1) * 3;
  22376. }
  22377. else {
  22378. indexLast = normals.length - 3;
  22379. }
  22380. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22381. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22382. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22383. normals[indexLast] = normals[indexFirst];
  22384. normals[indexLast + 1] = normals[indexFirst + 1];
  22385. normals[indexLast + 2] = normals[indexFirst + 2];
  22386. }
  22387. }
  22388. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22389. }
  22390. return instance;
  22391. }
  22392. else {
  22393. var ribbon = new BABYLON.Mesh(name, scene);
  22394. ribbon.sideOrientation = sideOrientation;
  22395. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22396. if (closePath) {
  22397. ribbon._idx = vertexData._idx;
  22398. }
  22399. ribbon._closePath = closePath;
  22400. ribbon._closeArray = closeArray;
  22401. vertexData.applyToMesh(ribbon, updatable);
  22402. return ribbon;
  22403. }
  22404. };
  22405. /**
  22406. * Creates a cylinder or a cone mesh.
  22407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22408. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22409. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22410. * 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.
  22411. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22412. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22413. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22414. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22415. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22416. * 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).
  22417. * 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
  22418. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22419. * 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
  22420. * 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.
  22421. * If `enclose` is false, a ring surface is one element.
  22422. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22423. * 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
  22424. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22425. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22427. */
  22428. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22429. var cylinder = new BABYLON.Mesh(name, scene);
  22430. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22431. cylinder.sideOrientation = options.sideOrientation;
  22432. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22433. vertexData.applyToMesh(cylinder, options.updatable);
  22434. return cylinder;
  22435. };
  22436. /**
  22437. * Creates a torus mesh.
  22438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22439. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22440. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22441. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22445. */
  22446. MeshBuilder.CreateTorus = function (name, options, scene) {
  22447. var torus = new BABYLON.Mesh(name, scene);
  22448. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22449. torus.sideOrientation = options.sideOrientation;
  22450. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22451. vertexData.applyToMesh(torus, options.updatable);
  22452. return torus;
  22453. };
  22454. /**
  22455. * Creates a torus knot mesh.
  22456. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22457. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22458. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22459. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22460. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22464. */
  22465. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22466. var torusKnot = new BABYLON.Mesh(name, scene);
  22467. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22468. torusKnot.sideOrientation = options.sideOrientation;
  22469. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22470. vertexData.applyToMesh(torusKnot, options.updatable);
  22471. return torusKnot;
  22472. };
  22473. /**
  22474. * Creates a line system mesh.
  22475. * A line system is a pool of many lines gathered in a single mesh.
  22476. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22477. * 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.
  22478. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22479. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22480. * 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
  22481. * 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
  22482. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22484. */
  22485. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22486. var instance = options.instance;
  22487. var lines = options.lines;
  22488. if (instance) {
  22489. var positionFunction = function (positions) {
  22490. var i = 0;
  22491. for (var l = 0; l < lines.length; l++) {
  22492. var points = lines[l];
  22493. for (var p = 0; p < points.length; p++) {
  22494. positions[i] = points[p].x;
  22495. positions[i + 1] = points[p].y;
  22496. positions[i + 2] = points[p].z;
  22497. i += 3;
  22498. }
  22499. }
  22500. };
  22501. instance.updateMeshPositions(positionFunction, false);
  22502. return instance;
  22503. }
  22504. // line system creation
  22505. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22506. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22507. vertexData.applyToMesh(lineSystem, options.updatable);
  22508. return lineSystem;
  22509. };
  22510. /**
  22511. * Creates a line mesh.
  22512. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22513. * 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.
  22514. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22515. * The parameter `points` is an array successive Vector3.
  22516. * 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
  22517. * When updating an instance, remember that only point positions can change, not the number of points.
  22518. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22519. */
  22520. MeshBuilder.CreateLines = function (name, options, scene) {
  22521. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22522. return lines;
  22523. };
  22524. /**
  22525. * Creates a dashed line mesh.
  22526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22527. * 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.
  22528. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22529. * The parameter `points` is an array successive Vector3.
  22530. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22531. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22532. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22533. * 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
  22534. * When updating an instance, remember that only point positions can change, not the number of points.
  22535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22536. */
  22537. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22538. var points = options.points;
  22539. var instance = options.instance;
  22540. var gapSize = options.gapSize;
  22541. var dashNb = options.dashNb;
  22542. var dashSize = options.dashSize;
  22543. if (instance) {
  22544. var positionFunction = function (positions) {
  22545. var curvect = BABYLON.Vector3.Zero();
  22546. var nbSeg = positions.length / 6;
  22547. var lg = 0;
  22548. var nb = 0;
  22549. var shft = 0;
  22550. var dashshft = 0;
  22551. var curshft = 0;
  22552. var p = 0;
  22553. var i = 0;
  22554. var j = 0;
  22555. for (i = 0; i < points.length - 1; i++) {
  22556. points[i + 1].subtractToRef(points[i], curvect);
  22557. lg += curvect.length();
  22558. }
  22559. shft = lg / nbSeg;
  22560. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22561. for (i = 0; i < points.length - 1; i++) {
  22562. points[i + 1].subtractToRef(points[i], curvect);
  22563. nb = Math.floor(curvect.length() / shft);
  22564. curvect.normalize();
  22565. j = 0;
  22566. while (j < nb && p < positions.length) {
  22567. curshft = shft * j;
  22568. positions[p] = points[i].x + curshft * curvect.x;
  22569. positions[p + 1] = points[i].y + curshft * curvect.y;
  22570. positions[p + 2] = points[i].z + curshft * curvect.z;
  22571. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22572. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22573. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22574. p += 6;
  22575. j++;
  22576. }
  22577. }
  22578. while (p < positions.length) {
  22579. positions[p] = points[i].x;
  22580. positions[p + 1] = points[i].y;
  22581. positions[p + 2] = points[i].z;
  22582. p += 3;
  22583. }
  22584. };
  22585. instance.updateMeshPositions(positionFunction, false);
  22586. return instance;
  22587. }
  22588. // dashed lines creation
  22589. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22590. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22591. vertexData.applyToMesh(dashedLines, options.updatable);
  22592. dashedLines.dashSize = dashSize;
  22593. dashedLines.gapSize = gapSize;
  22594. return dashedLines;
  22595. };
  22596. /**
  22597. * Creates an extruded shape mesh.
  22598. * 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.
  22599. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22600. *
  22601. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22602. * 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
  22603. * extruded along the Z axis.
  22604. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22605. * 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.
  22606. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22607. * 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
  22608. * 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
  22609. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22611. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22612. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22614. */
  22615. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22616. var path = options.path;
  22617. var shape = options.shape;
  22618. var scale = options.scale || 1;
  22619. var rotation = options.rotation || 0;
  22620. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22621. var updatable = options.updatable;
  22622. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22623. var instance = options.instance;
  22624. var invertUV = options.invertUV || false;
  22625. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22626. };
  22627. /**
  22628. * Creates an custom extruded shape mesh.
  22629. * 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.
  22630. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22631. *
  22632. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22633. * 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
  22634. * extruded along the Z axis.
  22635. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22636. * 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
  22637. * and the distance of this point from the begining of the path :
  22638. * ```javascript
  22639. * var rotationFunction = function(i, distance) {
  22640. * // do things
  22641. * return rotationValue; }
  22642. * ```
  22643. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22644. * 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
  22645. * and the distance of this point from the begining of the path :
  22646. * ```javascript
  22647. * var scaleFunction = function(i, distance) {
  22648. * // do things
  22649. * return scaleValue;}
  22650. * ```
  22651. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22652. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22653. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22654. * 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
  22655. * 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
  22656. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22659. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22661. */
  22662. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22663. var path = options.path;
  22664. var shape = options.shape;
  22665. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22666. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22667. var ribbonCloseArray = options.ribbonCloseArray || false;
  22668. var ribbonClosePath = options.ribbonClosePath || false;
  22669. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22670. var updatable = options.updatable;
  22671. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22672. var instance = options.instance;
  22673. var invertUV = options.invertUV || false;
  22674. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22675. };
  22676. /**
  22677. * Creates lathe mesh.
  22678. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22679. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22680. *
  22681. * 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
  22682. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22683. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22684. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22685. * 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.
  22686. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22687. * 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
  22688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22689. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22690. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22692. */
  22693. MeshBuilder.CreateLathe = function (name, options, scene) {
  22694. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22695. var closed = (options.closed === undefined) ? true : options.closed;
  22696. var shape = options.shape;
  22697. var radius = options.radius || 1;
  22698. var tessellation = options.tessellation || 64;
  22699. var updatable = options.updatable;
  22700. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22701. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22702. var pi2 = Math.PI * 2;
  22703. var paths = new Array();
  22704. var invertUV = options.invertUV || false;
  22705. var i = 0;
  22706. var p = 0;
  22707. var step = pi2 / tessellation * arc;
  22708. var rotated;
  22709. var path = new Array();
  22710. ;
  22711. for (i = 0; i <= tessellation; i++) {
  22712. var path = [];
  22713. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22714. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22715. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22716. }
  22717. for (p = 0; p < shape.length; p++) {
  22718. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22719. path.push(rotated);
  22720. }
  22721. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22722. 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));
  22723. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22724. }
  22725. paths.push(path);
  22726. }
  22727. // lathe ribbon
  22728. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22729. return lathe;
  22730. };
  22731. /**
  22732. * Creates a plane mesh.
  22733. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22734. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22735. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22736. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22740. */
  22741. MeshBuilder.CreatePlane = function (name, options, scene) {
  22742. var plane = new BABYLON.Mesh(name, scene);
  22743. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22744. plane.sideOrientation = options.sideOrientation;
  22745. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22746. vertexData.applyToMesh(plane, options.updatable);
  22747. if (options.sourcePlane) {
  22748. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22749. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22750. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22751. plane.rotate(vectorProduct, product);
  22752. }
  22753. return plane;
  22754. };
  22755. /**
  22756. * Creates a ground mesh.
  22757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22758. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22759. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22761. */
  22762. MeshBuilder.CreateGround = function (name, options, scene) {
  22763. var ground = new BABYLON.GroundMesh(name, scene);
  22764. ground._setReady(false);
  22765. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22766. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22767. ground._width = options.width || 1;
  22768. ground._height = options.height || 1;
  22769. ground._maxX = ground._width / 2;
  22770. ground._maxZ = ground._height / 2;
  22771. ground._minX = -ground._maxX;
  22772. ground._minZ = -ground._maxZ;
  22773. var vertexData = BABYLON.VertexData.CreateGround(options);
  22774. vertexData.applyToMesh(ground, options.updatable);
  22775. ground._setReady(true);
  22776. return ground;
  22777. };
  22778. /**
  22779. * Creates a tiled ground mesh.
  22780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22781. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22782. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22783. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22784. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22785. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22786. * numbers of subdivisions on the ground width and height of each tile.
  22787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22788. */
  22789. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22790. var tiledGround = new BABYLON.Mesh(name, scene);
  22791. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22792. vertexData.applyToMesh(tiledGround, options.updatable);
  22793. return tiledGround;
  22794. };
  22795. /**
  22796. * Creates a ground mesh from a height map.
  22797. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22798. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22799. * The parameter `url` sets the URL of the height map image resource.
  22800. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22801. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22802. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22803. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22804. * 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).
  22805. * This function is passed the newly built mesh :
  22806. * ```javascript
  22807. * function(mesh) { // do things
  22808. * return; }
  22809. * ```
  22810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22811. */
  22812. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22813. var width = options.width || 10.0;
  22814. var height = options.height || 10.0;
  22815. var subdivisions = options.subdivisions || 1 | 0;
  22816. var minHeight = options.minHeight || 0.0;
  22817. var maxHeight = options.maxHeight || 10.0;
  22818. var updatable = options.updatable;
  22819. var onReady = options.onReady;
  22820. var ground = new BABYLON.GroundMesh(name, scene);
  22821. ground._subdivisionsX = subdivisions;
  22822. ground._subdivisionsY = subdivisions;
  22823. ground._width = width;
  22824. ground._height = height;
  22825. ground._maxX = ground._width / 2.0;
  22826. ground._maxZ = ground._height / 2.0;
  22827. ground._minX = -ground._maxX;
  22828. ground._minZ = -ground._maxZ;
  22829. ground._setReady(false);
  22830. var onload = function (img) {
  22831. // Getting height map data
  22832. var canvas = document.createElement("canvas");
  22833. var context = canvas.getContext("2d");
  22834. var bufferWidth = img.width;
  22835. var bufferHeight = img.height;
  22836. canvas.width = bufferWidth;
  22837. canvas.height = bufferHeight;
  22838. context.drawImage(img, 0, 0);
  22839. // Create VertexData from map data
  22840. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22841. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22842. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22843. width: width, height: height,
  22844. subdivisions: subdivisions,
  22845. minHeight: minHeight, maxHeight: maxHeight,
  22846. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22847. });
  22848. vertexData.applyToMesh(ground, updatable);
  22849. ground._setReady(true);
  22850. //execute ready callback, if set
  22851. if (onReady) {
  22852. onReady(ground);
  22853. }
  22854. };
  22855. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22856. return ground;
  22857. };
  22858. /**
  22859. * Creates a tube mesh.
  22860. * 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.
  22861. *
  22862. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22863. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22864. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22865. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22866. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22867. * 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.
  22868. * It must return a radius value (positive float) :
  22869. * ```javascript
  22870. * var radiusFunction = function(i, distance) {
  22871. * // do things
  22872. * return radius; }
  22873. * ```
  22874. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22875. * 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
  22876. * 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
  22877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22879. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22881. */
  22882. MeshBuilder.CreateTube = function (name, options, scene) {
  22883. var path = options.path;
  22884. var radius = options.radius || 1.0;
  22885. var tessellation = options.tessellation || 64 | 0;
  22886. var radiusFunction = options.radiusFunction;
  22887. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22888. var invertUV = options.invertUV || false;
  22889. var updatable = options.updatable;
  22890. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22891. var instance = options.instance;
  22892. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22893. // tube geometry
  22894. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22895. var tangents = path3D.getTangents();
  22896. var normals = path3D.getNormals();
  22897. var distances = path3D.getDistances();
  22898. var pi2 = Math.PI * 2;
  22899. var step = pi2 / tessellation * arc;
  22900. var returnRadius = function () { return radius; };
  22901. var radiusFunctionFinal = radiusFunction || returnRadius;
  22902. var circlePath;
  22903. var rad;
  22904. var normal;
  22905. var rotated;
  22906. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22907. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22908. for (var i = 0; i < path.length; i++) {
  22909. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22910. circlePath = Array(); // current circle array
  22911. normal = normals[i]; // current normal
  22912. for (var t = 0; t < tessellation; t++) {
  22913. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22914. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22915. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22916. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22917. circlePath[t] = rotated;
  22918. }
  22919. circlePaths[index] = circlePath;
  22920. index++;
  22921. }
  22922. // cap
  22923. var capPath = function (nbPoints, pathIndex) {
  22924. var pointCap = Array();
  22925. for (var i = 0; i < nbPoints; i++) {
  22926. pointCap.push(path[pathIndex]);
  22927. }
  22928. return pointCap;
  22929. };
  22930. switch (cap) {
  22931. case BABYLON.Mesh.NO_CAP:
  22932. break;
  22933. case BABYLON.Mesh.CAP_START:
  22934. circlePaths[0] = capPath(tessellation, 0);
  22935. circlePaths[1] = circlePaths[2].slice(0);
  22936. break;
  22937. case BABYLON.Mesh.CAP_END:
  22938. circlePaths[index] = circlePaths[index - 1].slice(0);
  22939. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22940. break;
  22941. case BABYLON.Mesh.CAP_ALL:
  22942. circlePaths[0] = capPath(tessellation, 0);
  22943. circlePaths[1] = circlePaths[2].slice(0);
  22944. circlePaths[index] = circlePaths[index - 1].slice(0);
  22945. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22946. break;
  22947. default:
  22948. break;
  22949. }
  22950. return circlePaths;
  22951. };
  22952. var path3D;
  22953. var pathArray;
  22954. if (instance) {
  22955. var arc = options.arc || instance.arc;
  22956. path3D = (instance.path3D).update(path);
  22957. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22958. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22959. instance.path3D = path3D;
  22960. instance.pathArray = pathArray;
  22961. instance.arc = arc;
  22962. return instance;
  22963. }
  22964. // tube creation
  22965. path3D = new BABYLON.Path3D(path);
  22966. var newPathArray = new Array();
  22967. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22968. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22969. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22970. tube.pathArray = pathArray;
  22971. tube.path3D = path3D;
  22972. tube.tessellation = tessellation;
  22973. tube.cap = cap;
  22974. tube.arc = options.arc;
  22975. return tube;
  22976. };
  22977. /**
  22978. * Creates a polyhedron mesh.
  22979. *
  22980. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22981. * 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
  22982. * to choose the wanted type.
  22983. * The parameter `size` (positive float, default 1) sets the polygon size.
  22984. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22985. * 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`.
  22986. * 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
  22987. * 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)`).
  22988. * 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
  22989. * 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.
  22990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22993. */
  22994. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22995. var polyhedron = new BABYLON.Mesh(name, scene);
  22996. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22997. polyhedron.sideOrientation = options.sideOrientation;
  22998. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22999. vertexData.applyToMesh(polyhedron, options.updatable);
  23000. return polyhedron;
  23001. };
  23002. /**
  23003. * Creates a decal mesh.
  23004. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23005. * 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.
  23006. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23007. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23008. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23009. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23010. */
  23011. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23012. var indices = sourceMesh.getIndices();
  23013. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23014. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23015. var position = options.position || BABYLON.Vector3.Zero();
  23016. var normal = options.normal || BABYLON.Vector3.Up();
  23017. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23018. var angle = options.angle || 0;
  23019. // Getting correct rotation
  23020. if (!normal) {
  23021. var target = new BABYLON.Vector3(0, 0, 1);
  23022. var camera = sourceMesh.getScene().activeCamera;
  23023. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23024. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23025. }
  23026. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23027. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23028. var pitch = Math.atan2(normal.y, len);
  23029. // Matrix
  23030. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23031. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23032. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23033. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23034. var vertexData = new BABYLON.VertexData();
  23035. vertexData.indices = [];
  23036. vertexData.positions = [];
  23037. vertexData.normals = [];
  23038. vertexData.uvs = [];
  23039. var currentVertexDataIndex = 0;
  23040. var extractDecalVector3 = function (indexId) {
  23041. var vertexId = indices[indexId];
  23042. var result = new BABYLON.PositionNormalVertex();
  23043. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23044. // Send vector to decal local world
  23045. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23046. // Get normal
  23047. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23048. return result;
  23049. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23050. var clip = function (vertices, axis) {
  23051. if (vertices.length === 0) {
  23052. return vertices;
  23053. }
  23054. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23055. var clipVertices = function (v0, v1) {
  23056. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23057. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23058. };
  23059. var result = new Array();
  23060. for (var index = 0; index < vertices.length; index += 3) {
  23061. var v1Out;
  23062. var v2Out;
  23063. var v3Out;
  23064. var total = 0;
  23065. var nV1, nV2, nV3, nV4;
  23066. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23067. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23068. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23069. v1Out = d1 > 0;
  23070. v2Out = d2 > 0;
  23071. v3Out = d3 > 0;
  23072. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23073. switch (total) {
  23074. case 0:
  23075. result.push(vertices[index]);
  23076. result.push(vertices[index + 1]);
  23077. result.push(vertices[index + 2]);
  23078. break;
  23079. case 1:
  23080. if (v1Out) {
  23081. nV1 = vertices[index + 1];
  23082. nV2 = vertices[index + 2];
  23083. nV3 = clipVertices(vertices[index], nV1);
  23084. nV4 = clipVertices(vertices[index], nV2);
  23085. }
  23086. if (v2Out) {
  23087. nV1 = vertices[index];
  23088. nV2 = vertices[index + 2];
  23089. nV3 = clipVertices(vertices[index + 1], nV1);
  23090. nV4 = clipVertices(vertices[index + 1], nV2);
  23091. result.push(nV3);
  23092. result.push(nV2.clone());
  23093. result.push(nV1.clone());
  23094. result.push(nV2.clone());
  23095. result.push(nV3.clone());
  23096. result.push(nV4);
  23097. break;
  23098. }
  23099. if (v3Out) {
  23100. nV1 = vertices[index];
  23101. nV2 = vertices[index + 1];
  23102. nV3 = clipVertices(vertices[index + 2], nV1);
  23103. nV4 = clipVertices(vertices[index + 2], nV2);
  23104. }
  23105. result.push(nV1.clone());
  23106. result.push(nV2.clone());
  23107. result.push(nV3);
  23108. result.push(nV4);
  23109. result.push(nV3.clone());
  23110. result.push(nV2.clone());
  23111. break;
  23112. case 2:
  23113. if (!v1Out) {
  23114. nV1 = vertices[index].clone();
  23115. nV2 = clipVertices(nV1, vertices[index + 1]);
  23116. nV3 = clipVertices(nV1, vertices[index + 2]);
  23117. result.push(nV1);
  23118. result.push(nV2);
  23119. result.push(nV3);
  23120. }
  23121. if (!v2Out) {
  23122. nV1 = vertices[index + 1].clone();
  23123. nV2 = clipVertices(nV1, vertices[index + 2]);
  23124. nV3 = clipVertices(nV1, vertices[index]);
  23125. result.push(nV1);
  23126. result.push(nV2);
  23127. result.push(nV3);
  23128. }
  23129. if (!v3Out) {
  23130. nV1 = vertices[index + 2].clone();
  23131. nV2 = clipVertices(nV1, vertices[index]);
  23132. nV3 = clipVertices(nV1, vertices[index + 1]);
  23133. result.push(nV1);
  23134. result.push(nV2);
  23135. result.push(nV3);
  23136. }
  23137. break;
  23138. case 3:
  23139. break;
  23140. }
  23141. }
  23142. return result;
  23143. };
  23144. for (var index = 0; index < indices.length; index += 3) {
  23145. var faceVertices = new Array();
  23146. faceVertices.push(extractDecalVector3(index));
  23147. faceVertices.push(extractDecalVector3(index + 1));
  23148. faceVertices.push(extractDecalVector3(index + 2));
  23149. // Clip
  23150. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23151. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23154. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23155. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23156. if (faceVertices.length === 0) {
  23157. continue;
  23158. }
  23159. // Add UVs and get back to world
  23160. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23161. var vertex = faceVertices[vIndex];
  23162. //TODO check for Int32Array
  23163. vertexData.indices.push(currentVertexDataIndex);
  23164. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23165. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23166. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23167. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23168. currentVertexDataIndex++;
  23169. }
  23170. }
  23171. // Return mesh
  23172. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23173. vertexData.applyToMesh(decal);
  23174. decal.position = position.clone();
  23175. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23176. return decal;
  23177. };
  23178. // Privates
  23179. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23180. // extrusion geometry
  23181. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23182. var tangents = path3D.getTangents();
  23183. var normals = path3D.getNormals();
  23184. var binormals = path3D.getBinormals();
  23185. var distances = path3D.getDistances();
  23186. var angle = 0;
  23187. var returnScale = function () { return scale; };
  23188. var returnRotation = function () { return rotation; };
  23189. var rotate = custom ? rotateFunction : returnRotation;
  23190. var scl = custom ? scaleFunction : returnScale;
  23191. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23192. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23193. for (var i = 0; i < curve.length; i++) {
  23194. var shapePath = new Array();
  23195. var angleStep = rotate(i, distances[i]);
  23196. var scaleRatio = scl(i, distances[i]);
  23197. for (var p = 0; p < shape.length; p++) {
  23198. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23199. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23200. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23201. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23202. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23203. shapePath[p] = rotated;
  23204. }
  23205. shapePaths[index] = shapePath;
  23206. angle += angleStep;
  23207. index++;
  23208. }
  23209. // cap
  23210. var capPath = function (shapePath) {
  23211. var pointCap = Array();
  23212. var barycenter = BABYLON.Vector3.Zero();
  23213. var i;
  23214. for (i = 0; i < shapePath.length; i++) {
  23215. barycenter.addInPlace(shapePath[i]);
  23216. }
  23217. barycenter.scaleInPlace(1 / shapePath.length);
  23218. for (i = 0; i < shapePath.length; i++) {
  23219. pointCap.push(barycenter);
  23220. }
  23221. return pointCap;
  23222. };
  23223. switch (cap) {
  23224. case BABYLON.Mesh.NO_CAP:
  23225. break;
  23226. case BABYLON.Mesh.CAP_START:
  23227. shapePaths[0] = capPath(shapePaths[2]);
  23228. shapePaths[1] = shapePaths[2].slice(0);
  23229. break;
  23230. case BABYLON.Mesh.CAP_END:
  23231. shapePaths[index] = shapePaths[index - 1];
  23232. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23233. break;
  23234. case BABYLON.Mesh.CAP_ALL:
  23235. shapePaths[0] = capPath(shapePaths[2]);
  23236. shapePaths[1] = shapePaths[2].slice(0);
  23237. shapePaths[index] = shapePaths[index - 1];
  23238. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23239. break;
  23240. default:
  23241. break;
  23242. }
  23243. return shapePaths;
  23244. };
  23245. var path3D;
  23246. var pathArray;
  23247. if (instance) {
  23248. path3D = (instance.path3D).update(curve);
  23249. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23250. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23251. return instance;
  23252. }
  23253. // extruded shape creation
  23254. path3D = new BABYLON.Path3D(curve);
  23255. var newShapePaths = new Array();
  23256. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23257. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23258. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23259. extrudedGeneric.pathArray = pathArray;
  23260. extrudedGeneric.path3D = path3D;
  23261. extrudedGeneric.cap = cap;
  23262. return extrudedGeneric;
  23263. };
  23264. return MeshBuilder;
  23265. }());
  23266. BABYLON.MeshBuilder = MeshBuilder;
  23267. })(BABYLON || (BABYLON = {}));
  23268. //# sourceMappingURL=babylon.meshBuilder.js.map
  23269. var BABYLON;
  23270. (function (BABYLON) {
  23271. var BaseTexture = (function () {
  23272. function BaseTexture(scene) {
  23273. this.hasAlpha = false;
  23274. this.getAlphaFromRGB = false;
  23275. this.level = 1;
  23276. this.coordinatesIndex = 0;
  23277. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23278. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23279. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23280. this.anisotropicFilteringLevel = 4;
  23281. this.isCube = false;
  23282. this.isRenderTarget = false;
  23283. this.animations = new Array();
  23284. /**
  23285. * An event triggered when the texture is disposed.
  23286. * @type {BABYLON.Observable}
  23287. */
  23288. this.onDisposeObservable = new BABYLON.Observable();
  23289. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23290. this._scene = scene;
  23291. this._scene.textures.push(this);
  23292. this._uid = null;
  23293. }
  23294. Object.defineProperty(BaseTexture.prototype, "uid", {
  23295. get: function () {
  23296. if (!this._uid) {
  23297. this._uid = BABYLON.Tools.RandomId();
  23298. }
  23299. return this._uid;
  23300. },
  23301. enumerable: true,
  23302. configurable: true
  23303. });
  23304. BaseTexture.prototype.toString = function () {
  23305. return this.name;
  23306. };
  23307. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23308. set: function (callback) {
  23309. if (this._onDisposeObserver) {
  23310. this.onDisposeObservable.remove(this._onDisposeObserver);
  23311. }
  23312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23313. },
  23314. enumerable: true,
  23315. configurable: true
  23316. });
  23317. BaseTexture.prototype.getScene = function () {
  23318. return this._scene;
  23319. };
  23320. BaseTexture.prototype.getTextureMatrix = function () {
  23321. return null;
  23322. };
  23323. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23324. return null;
  23325. };
  23326. BaseTexture.prototype.getInternalTexture = function () {
  23327. return this._texture;
  23328. };
  23329. BaseTexture.prototype.isReady = function () {
  23330. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23331. return true;
  23332. }
  23333. if (this._texture) {
  23334. return this._texture.isReady;
  23335. }
  23336. return false;
  23337. };
  23338. BaseTexture.prototype.getSize = function () {
  23339. if (this._texture._width) {
  23340. return new BABYLON.Size(this._texture._width, this._texture._height);
  23341. }
  23342. if (this._texture._size) {
  23343. return new BABYLON.Size(this._texture._size, this._texture._size);
  23344. }
  23345. return BABYLON.Size.Zero();
  23346. };
  23347. BaseTexture.prototype.getBaseSize = function () {
  23348. if (!this.isReady() || !this._texture)
  23349. return BABYLON.Size.Zero();
  23350. if (this._texture._size) {
  23351. return new BABYLON.Size(this._texture._size, this._texture._size);
  23352. }
  23353. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23354. };
  23355. BaseTexture.prototype.scale = function (ratio) {
  23356. };
  23357. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23358. get: function () {
  23359. return false;
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23365. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23366. for (var index = 0; index < texturesCache.length; index++) {
  23367. var texturesCacheEntry = texturesCache[index];
  23368. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23369. texturesCache.splice(index, 1);
  23370. return;
  23371. }
  23372. }
  23373. };
  23374. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23375. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23376. for (var index = 0; index < texturesCache.length; index++) {
  23377. var texturesCacheEntry = texturesCache[index];
  23378. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23379. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23380. texturesCacheEntry.references++;
  23381. return texturesCacheEntry;
  23382. }
  23383. }
  23384. }
  23385. return null;
  23386. };
  23387. BaseTexture.prototype.delayLoad = function () {
  23388. };
  23389. BaseTexture.prototype.clone = function () {
  23390. return null;
  23391. };
  23392. BaseTexture.prototype.releaseInternalTexture = function () {
  23393. if (this._texture) {
  23394. this._scene.getEngine().releaseInternalTexture(this._texture);
  23395. delete this._texture;
  23396. }
  23397. };
  23398. BaseTexture.prototype.dispose = function () {
  23399. // Animations
  23400. this.getScene().stopAnimation(this);
  23401. // Remove from scene
  23402. var index = this._scene.textures.indexOf(this);
  23403. if (index >= 0) {
  23404. this._scene.textures.splice(index, 1);
  23405. }
  23406. if (this._texture === undefined) {
  23407. return;
  23408. }
  23409. // Release
  23410. this.releaseInternalTexture();
  23411. // Callback
  23412. this.onDisposeObservable.notifyObservers(this);
  23413. this.onDisposeObservable.clear();
  23414. };
  23415. BaseTexture.prototype.serialize = function () {
  23416. if (!this.name) {
  23417. return null;
  23418. }
  23419. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23420. // Animations
  23421. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23422. return serializationObject;
  23423. };
  23424. __decorate([
  23425. BABYLON.serialize()
  23426. ], BaseTexture.prototype, "name", void 0);
  23427. __decorate([
  23428. BABYLON.serialize()
  23429. ], BaseTexture.prototype, "hasAlpha", void 0);
  23430. __decorate([
  23431. BABYLON.serialize()
  23432. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23433. __decorate([
  23434. BABYLON.serialize()
  23435. ], BaseTexture.prototype, "level", void 0);
  23436. __decorate([
  23437. BABYLON.serialize()
  23438. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23439. __decorate([
  23440. BABYLON.serialize()
  23441. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23442. __decorate([
  23443. BABYLON.serialize()
  23444. ], BaseTexture.prototype, "wrapU", void 0);
  23445. __decorate([
  23446. BABYLON.serialize()
  23447. ], BaseTexture.prototype, "wrapV", void 0);
  23448. __decorate([
  23449. BABYLON.serialize()
  23450. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23451. __decorate([
  23452. BABYLON.serialize()
  23453. ], BaseTexture.prototype, "isCube", void 0);
  23454. __decorate([
  23455. BABYLON.serialize()
  23456. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23457. return BaseTexture;
  23458. }());
  23459. BABYLON.BaseTexture = BaseTexture;
  23460. })(BABYLON || (BABYLON = {}));
  23461. //# sourceMappingURL=babylon.baseTexture.js.map
  23462. var BABYLON;
  23463. (function (BABYLON) {
  23464. var Texture = (function (_super) {
  23465. __extends(Texture, _super);
  23466. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23467. var _this = this;
  23468. if (noMipmap === void 0) { noMipmap = false; }
  23469. if (invertY === void 0) { invertY = true; }
  23470. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23471. if (onLoad === void 0) { onLoad = null; }
  23472. if (onError === void 0) { onError = null; }
  23473. if (buffer === void 0) { buffer = null; }
  23474. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23475. _super.call(this, scene);
  23476. this.uOffset = 0;
  23477. this.vOffset = 0;
  23478. this.uScale = 1.0;
  23479. this.vScale = 1.0;
  23480. this.uAng = 0;
  23481. this.vAng = 0;
  23482. this.wAng = 0;
  23483. this.name = url;
  23484. this.url = url;
  23485. this._noMipmap = noMipmap;
  23486. this._invertY = invertY;
  23487. this._samplingMode = samplingMode;
  23488. this._buffer = buffer;
  23489. this._deleteBuffer = deleteBuffer;
  23490. if (!url) {
  23491. return;
  23492. }
  23493. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23494. var load = function () {
  23495. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23496. _this.onLoadObservable.notifyObservers(true);
  23497. }
  23498. if (onLoad) {
  23499. onLoad();
  23500. }
  23501. };
  23502. if (!this._texture) {
  23503. if (!scene.useDelayedTextureLoading) {
  23504. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23505. if (deleteBuffer) {
  23506. delete this._buffer;
  23507. }
  23508. }
  23509. else {
  23510. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23511. this._delayedOnLoad = load;
  23512. this._delayedOnError = onError;
  23513. }
  23514. }
  23515. else {
  23516. if (this._texture.isReady) {
  23517. BABYLON.Tools.SetImmediate(function () { return load(); });
  23518. }
  23519. else {
  23520. this._texture.onLoadedCallbacks.push(load);
  23521. }
  23522. }
  23523. }
  23524. Object.defineProperty(Texture.prototype, "noMipmap", {
  23525. get: function () {
  23526. return this._noMipmap;
  23527. },
  23528. enumerable: true,
  23529. configurable: true
  23530. });
  23531. Texture.prototype.delayLoad = function () {
  23532. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23533. return;
  23534. }
  23535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23536. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23537. if (!this._texture) {
  23538. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23539. if (this._deleteBuffer) {
  23540. delete this._buffer;
  23541. }
  23542. }
  23543. };
  23544. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23545. if (!this._texture) {
  23546. return;
  23547. }
  23548. this._samplingMode = samplingMode;
  23549. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23550. };
  23551. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23552. x *= this.uScale;
  23553. y *= this.vScale;
  23554. x -= 0.5 * this.uScale;
  23555. y -= 0.5 * this.vScale;
  23556. z -= 0.5;
  23557. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23558. t.x += 0.5 * this.uScale + this.uOffset;
  23559. t.y += 0.5 * this.vScale + this.vOffset;
  23560. t.z += 0.5;
  23561. };
  23562. Texture.prototype.getTextureMatrix = function () {
  23563. if (this.uOffset === this._cachedUOffset &&
  23564. this.vOffset === this._cachedVOffset &&
  23565. this.uScale === this._cachedUScale &&
  23566. this.vScale === this._cachedVScale &&
  23567. this.uAng === this._cachedUAng &&
  23568. this.vAng === this._cachedVAng &&
  23569. this.wAng === this._cachedWAng) {
  23570. return this._cachedTextureMatrix;
  23571. }
  23572. this._cachedUOffset = this.uOffset;
  23573. this._cachedVOffset = this.vOffset;
  23574. this._cachedUScale = this.uScale;
  23575. this._cachedVScale = this.vScale;
  23576. this._cachedUAng = this.uAng;
  23577. this._cachedVAng = this.vAng;
  23578. this._cachedWAng = this.wAng;
  23579. if (!this._cachedTextureMatrix) {
  23580. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23581. this._rowGenerationMatrix = new BABYLON.Matrix();
  23582. this._t0 = BABYLON.Vector3.Zero();
  23583. this._t1 = BABYLON.Vector3.Zero();
  23584. this._t2 = BABYLON.Vector3.Zero();
  23585. }
  23586. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23587. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23588. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23589. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23590. this._t1.subtractInPlace(this._t0);
  23591. this._t2.subtractInPlace(this._t0);
  23592. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23593. this._cachedTextureMatrix.m[0] = this._t1.x;
  23594. this._cachedTextureMatrix.m[1] = this._t1.y;
  23595. this._cachedTextureMatrix.m[2] = this._t1.z;
  23596. this._cachedTextureMatrix.m[4] = this._t2.x;
  23597. this._cachedTextureMatrix.m[5] = this._t2.y;
  23598. this._cachedTextureMatrix.m[6] = this._t2.z;
  23599. this._cachedTextureMatrix.m[8] = this._t0.x;
  23600. this._cachedTextureMatrix.m[9] = this._t0.y;
  23601. this._cachedTextureMatrix.m[10] = this._t0.z;
  23602. return this._cachedTextureMatrix;
  23603. };
  23604. Texture.prototype.getReflectionTextureMatrix = function () {
  23605. if (this.uOffset === this._cachedUOffset &&
  23606. this.vOffset === this._cachedVOffset &&
  23607. this.uScale === this._cachedUScale &&
  23608. this.vScale === this._cachedVScale &&
  23609. this.coordinatesMode === this._cachedCoordinatesMode) {
  23610. return this._cachedTextureMatrix;
  23611. }
  23612. if (!this._cachedTextureMatrix) {
  23613. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23614. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23615. }
  23616. this._cachedCoordinatesMode = this.coordinatesMode;
  23617. switch (this.coordinatesMode) {
  23618. case Texture.PLANAR_MODE:
  23619. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23620. this._cachedTextureMatrix[0] = this.uScale;
  23621. this._cachedTextureMatrix[5] = this.vScale;
  23622. this._cachedTextureMatrix[12] = this.uOffset;
  23623. this._cachedTextureMatrix[13] = this.vOffset;
  23624. break;
  23625. case Texture.PROJECTION_MODE:
  23626. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23627. this._projectionModeMatrix.m[0] = 0.5;
  23628. this._projectionModeMatrix.m[5] = -0.5;
  23629. this._projectionModeMatrix.m[10] = 0.0;
  23630. this._projectionModeMatrix.m[12] = 0.5;
  23631. this._projectionModeMatrix.m[13] = 0.5;
  23632. this._projectionModeMatrix.m[14] = 1.0;
  23633. this._projectionModeMatrix.m[15] = 1.0;
  23634. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23635. break;
  23636. default:
  23637. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23638. break;
  23639. }
  23640. return this._cachedTextureMatrix;
  23641. };
  23642. Texture.prototype.clone = function () {
  23643. var _this = this;
  23644. return BABYLON.SerializationHelper.Clone(function () {
  23645. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23646. }, this);
  23647. };
  23648. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23649. get: function () {
  23650. if (!this._onLoadObservarble) {
  23651. this._onLoadObservarble = new BABYLON.Observable();
  23652. }
  23653. return this._onLoadObservarble;
  23654. },
  23655. enumerable: true,
  23656. configurable: true
  23657. });
  23658. // Statics
  23659. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23660. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23661. if (onLoad === void 0) { onLoad = null; }
  23662. if (onError === void 0) { onError = null; }
  23663. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23664. };
  23665. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23666. if (parsedTexture.customType) {
  23667. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23668. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23669. }
  23670. if (parsedTexture.isCube) {
  23671. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23672. }
  23673. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23674. return null;
  23675. }
  23676. var texture = BABYLON.SerializationHelper.Parse(function () {
  23677. if (parsedTexture.mirrorPlane) {
  23678. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23679. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23680. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23681. return mirrorTexture;
  23682. }
  23683. else if (parsedTexture.isRenderTarget) {
  23684. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23685. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23686. return renderTargetTexture;
  23687. }
  23688. else {
  23689. var texture;
  23690. if (parsedTexture.base64String) {
  23691. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23692. }
  23693. else {
  23694. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23695. }
  23696. return texture;
  23697. }
  23698. }, parsedTexture, scene);
  23699. // Animations
  23700. if (parsedTexture.animations) {
  23701. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23702. var parsedAnimation = parsedTexture.animations[animationIndex];
  23703. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23704. }
  23705. }
  23706. return texture;
  23707. };
  23708. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23709. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23710. if (noMipmap === void 0) { noMipmap = false; }
  23711. if (invertY === void 0) { invertY = true; }
  23712. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23713. if (onLoad === void 0) { onLoad = null; }
  23714. if (onError === void 0) { onError = null; }
  23715. if (name.substr(0, 5) !== "data:") {
  23716. name = "data:" + name;
  23717. }
  23718. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23719. };
  23720. // Constants
  23721. Texture.NEAREST_SAMPLINGMODE = 1;
  23722. Texture.BILINEAR_SAMPLINGMODE = 2;
  23723. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23724. Texture.EXPLICIT_MODE = 0;
  23725. Texture.SPHERICAL_MODE = 1;
  23726. Texture.PLANAR_MODE = 2;
  23727. Texture.CUBIC_MODE = 3;
  23728. Texture.PROJECTION_MODE = 4;
  23729. Texture.SKYBOX_MODE = 5;
  23730. Texture.INVCUBIC_MODE = 6;
  23731. Texture.EQUIRECTANGULAR_MODE = 7;
  23732. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23733. Texture.CLAMP_ADDRESSMODE = 0;
  23734. Texture.WRAP_ADDRESSMODE = 1;
  23735. Texture.MIRROR_ADDRESSMODE = 2;
  23736. __decorate([
  23737. BABYLON.serialize()
  23738. ], Texture.prototype, "url", void 0);
  23739. __decorate([
  23740. BABYLON.serialize()
  23741. ], Texture.prototype, "uOffset", void 0);
  23742. __decorate([
  23743. BABYLON.serialize()
  23744. ], Texture.prototype, "vOffset", void 0);
  23745. __decorate([
  23746. BABYLON.serialize()
  23747. ], Texture.prototype, "uScale", void 0);
  23748. __decorate([
  23749. BABYLON.serialize()
  23750. ], Texture.prototype, "vScale", void 0);
  23751. __decorate([
  23752. BABYLON.serialize()
  23753. ], Texture.prototype, "uAng", void 0);
  23754. __decorate([
  23755. BABYLON.serialize()
  23756. ], Texture.prototype, "vAng", void 0);
  23757. __decorate([
  23758. BABYLON.serialize()
  23759. ], Texture.prototype, "wAng", void 0);
  23760. return Texture;
  23761. }(BABYLON.BaseTexture));
  23762. BABYLON.Texture = Texture;
  23763. })(BABYLON || (BABYLON = {}));
  23764. //# sourceMappingURL=babylon.texture.js.map
  23765. var BABYLON;
  23766. (function (BABYLON) {
  23767. var CubeTexture = (function (_super) {
  23768. __extends(CubeTexture, _super);
  23769. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23770. if (onLoad === void 0) { onLoad = null; }
  23771. if (onError === void 0) { onError = null; }
  23772. _super.call(this, scene);
  23773. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23774. this.name = rootUrl;
  23775. this.url = rootUrl;
  23776. this._noMipmap = noMipmap;
  23777. this.hasAlpha = false;
  23778. if (!rootUrl && !files) {
  23779. return;
  23780. }
  23781. this._texture = this._getFromCache(rootUrl, noMipmap);
  23782. if (!files) {
  23783. if (!extensions) {
  23784. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23785. }
  23786. files = [];
  23787. for (var index = 0; index < extensions.length; index++) {
  23788. files.push(rootUrl + extensions[index]);
  23789. }
  23790. this._extensions = extensions;
  23791. }
  23792. this._files = files;
  23793. if (!this._texture) {
  23794. if (!scene.useDelayedTextureLoading) {
  23795. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23796. }
  23797. else {
  23798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23799. }
  23800. }
  23801. else if (onLoad) {
  23802. if (this._texture.isReady) {
  23803. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23804. }
  23805. else {
  23806. this._texture.onLoadedCallbacks.push(onLoad);
  23807. }
  23808. }
  23809. this.isCube = true;
  23810. this._textureMatrix = BABYLON.Matrix.Identity();
  23811. }
  23812. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23813. return new CubeTexture("", scene, null, noMipmap, files);
  23814. };
  23815. // Methods
  23816. CubeTexture.prototype.delayLoad = function () {
  23817. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23818. return;
  23819. }
  23820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23821. this._texture = this._getFromCache(this.url, this._noMipmap);
  23822. if (!this._texture) {
  23823. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23824. }
  23825. };
  23826. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23827. return this._textureMatrix;
  23828. };
  23829. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23830. var texture = BABYLON.SerializationHelper.Parse(function () {
  23831. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23832. }, parsedTexture, scene);
  23833. // Animations
  23834. if (parsedTexture.animations) {
  23835. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23836. var parsedAnimation = parsedTexture.animations[animationIndex];
  23837. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23838. }
  23839. }
  23840. return texture;
  23841. };
  23842. CubeTexture.prototype.clone = function () {
  23843. var _this = this;
  23844. return BABYLON.SerializationHelper.Clone(function () {
  23845. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23846. }, this);
  23847. };
  23848. return CubeTexture;
  23849. }(BABYLON.BaseTexture));
  23850. BABYLON.CubeTexture = CubeTexture;
  23851. })(BABYLON || (BABYLON = {}));
  23852. //# sourceMappingURL=babylon.cubeTexture.js.map
  23853. var BABYLON;
  23854. (function (BABYLON) {
  23855. var RenderTargetTexture = (function (_super) {
  23856. __extends(RenderTargetTexture, _super);
  23857. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23858. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23859. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23860. if (isCube === void 0) { isCube = false; }
  23861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23862. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23863. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23864. _super.call(this, null, scene, !generateMipMaps);
  23865. this.isCube = isCube;
  23866. /**
  23867. * Use this list to define the list of mesh you want to render.
  23868. */
  23869. this.renderList = new Array();
  23870. this.renderParticles = true;
  23871. this.renderSprites = false;
  23872. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23873. // Events
  23874. /**
  23875. * An event triggered when the texture is unbind.
  23876. * @type {BABYLON.Observable}
  23877. */
  23878. this.onAfterUnbindObservable = new BABYLON.Observable();
  23879. /**
  23880. * An event triggered before rendering the texture
  23881. * @type {BABYLON.Observable}
  23882. */
  23883. this.onBeforeRenderObservable = new BABYLON.Observable();
  23884. /**
  23885. * An event triggered after rendering the texture
  23886. * @type {BABYLON.Observable}
  23887. */
  23888. this.onAfterRenderObservable = new BABYLON.Observable();
  23889. /**
  23890. * An event triggered after the texture clear
  23891. * @type {BABYLON.Observable}
  23892. */
  23893. this.onClearObservable = new BABYLON.Observable();
  23894. this._currentRefreshId = -1;
  23895. this._refreshRate = 1;
  23896. this.name = name;
  23897. this.isRenderTarget = true;
  23898. this._size = size;
  23899. this._generateMipMaps = generateMipMaps;
  23900. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23901. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23902. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23903. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23904. }
  23905. if (isCube) {
  23906. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23907. generateMipMaps: generateMipMaps,
  23908. samplingMode: samplingMode,
  23909. generateDepthBuffer: generateDepthBuffer,
  23910. generateStencilBuffer: generateStencilBuffer
  23911. });
  23912. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23913. this._textureMatrix = BABYLON.Matrix.Identity();
  23914. }
  23915. else {
  23916. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23917. generateMipMaps: generateMipMaps,
  23918. type: type,
  23919. samplingMode: samplingMode,
  23920. generateDepthBuffer: generateDepthBuffer,
  23921. generateStencilBuffer: generateStencilBuffer
  23922. });
  23923. }
  23924. // Rendering groups
  23925. this._renderingManager = new BABYLON.RenderingManager(scene);
  23926. }
  23927. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23928. get: function () {
  23929. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23930. },
  23931. enumerable: true,
  23932. configurable: true
  23933. });
  23934. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23935. get: function () {
  23936. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23937. },
  23938. enumerable: true,
  23939. configurable: true
  23940. });
  23941. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23942. get: function () {
  23943. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23944. },
  23945. enumerable: true,
  23946. configurable: true
  23947. });
  23948. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23949. set: function (callback) {
  23950. if (this._onAfterUnbindObserver) {
  23951. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23952. }
  23953. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23954. },
  23955. enumerable: true,
  23956. configurable: true
  23957. });
  23958. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23959. set: function (callback) {
  23960. if (this._onBeforeRenderObserver) {
  23961. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23962. }
  23963. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23964. },
  23965. enumerable: true,
  23966. configurable: true
  23967. });
  23968. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23969. set: function (callback) {
  23970. if (this._onAfterRenderObserver) {
  23971. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23972. }
  23973. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23979. set: function (callback) {
  23980. if (this._onClearObserver) {
  23981. this.onClearObservable.remove(this._onClearObserver);
  23982. }
  23983. this._onClearObserver = this.onClearObservable.add(callback);
  23984. },
  23985. enumerable: true,
  23986. configurable: true
  23987. });
  23988. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23989. this._currentRefreshId = -1;
  23990. };
  23991. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23992. get: function () {
  23993. return this._refreshRate;
  23994. },
  23995. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23996. set: function (value) {
  23997. this._refreshRate = value;
  23998. this.resetRefreshCounter();
  23999. },
  24000. enumerable: true,
  24001. configurable: true
  24002. });
  24003. RenderTargetTexture.prototype._shouldRender = function () {
  24004. if (this._currentRefreshId === -1) {
  24005. this._currentRefreshId = 1;
  24006. return true;
  24007. }
  24008. if (this.refreshRate === this._currentRefreshId) {
  24009. this._currentRefreshId = 1;
  24010. return true;
  24011. }
  24012. this._currentRefreshId++;
  24013. return false;
  24014. };
  24015. RenderTargetTexture.prototype.isReady = function () {
  24016. if (!this.getScene().renderTargetsEnabled) {
  24017. return false;
  24018. }
  24019. return _super.prototype.isReady.call(this);
  24020. };
  24021. RenderTargetTexture.prototype.getRenderSize = function () {
  24022. return this._size;
  24023. };
  24024. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24025. get: function () {
  24026. return true;
  24027. },
  24028. enumerable: true,
  24029. configurable: true
  24030. });
  24031. RenderTargetTexture.prototype.scale = function (ratio) {
  24032. var newSize = this._size * ratio;
  24033. this.resize(newSize, this._generateMipMaps);
  24034. };
  24035. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24036. if (this.isCube) {
  24037. return this._textureMatrix;
  24038. }
  24039. return _super.prototype.getReflectionTextureMatrix.call(this);
  24040. };
  24041. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  24042. this.releaseInternalTexture();
  24043. if (this.isCube) {
  24044. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  24045. }
  24046. else {
  24047. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24048. }
  24049. };
  24050. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24051. var scene = this.getScene();
  24052. var engine = scene.getEngine();
  24053. if (this.useCameraPostProcesses !== undefined) {
  24054. useCameraPostProcess = this.useCameraPostProcesses;
  24055. }
  24056. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24057. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24058. }
  24059. else {
  24060. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24061. }
  24062. if (this._waitingRenderList) {
  24063. this.renderList = [];
  24064. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24065. var id = this._waitingRenderList[index];
  24066. this.renderList.push(scene.getMeshByID(id));
  24067. }
  24068. delete this._waitingRenderList;
  24069. }
  24070. // Is predicate defined?
  24071. if (this.renderListPredicate) {
  24072. this.renderList.splice(0); // Clear previous renderList
  24073. var sceneMeshes = this.getScene().meshes;
  24074. for (var index = 0; index < sceneMeshes.length; index++) {
  24075. var mesh = sceneMeshes[index];
  24076. if (this.renderListPredicate(mesh)) {
  24077. this.renderList.push(mesh);
  24078. }
  24079. }
  24080. }
  24081. if (this.renderList && this.renderList.length === 0) {
  24082. return;
  24083. }
  24084. // Prepare renderingManager
  24085. this._renderingManager.reset();
  24086. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24087. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24088. var sceneRenderId = scene.getRenderId();
  24089. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24090. var mesh = currentRenderList[meshIndex];
  24091. if (mesh) {
  24092. if (!mesh.isReady()) {
  24093. // Reset _currentRefreshId
  24094. this.resetRefreshCounter();
  24095. continue;
  24096. }
  24097. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24098. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24099. mesh._activate(sceneRenderId);
  24100. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24101. var subMesh = mesh.subMeshes[subIndex];
  24102. scene._activeIndices.addCount(subMesh.indexCount, false);
  24103. this._renderingManager.dispatch(subMesh);
  24104. }
  24105. }
  24106. }
  24107. }
  24108. if (this.isCube) {
  24109. for (var face = 0; face < 6; face++) {
  24110. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24111. scene.incrementRenderId();
  24112. scene.resetCachedMaterial();
  24113. }
  24114. }
  24115. else {
  24116. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24117. }
  24118. this.onAfterUnbindObservable.notifyObservers(this);
  24119. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24120. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24121. }
  24122. engine.setViewport(scene.activeCamera.viewport);
  24123. scene.resetCachedMaterial();
  24124. };
  24125. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24126. var scene = this.getScene();
  24127. var engine = scene.getEngine();
  24128. // Bind
  24129. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24130. if (this.isCube) {
  24131. engine.bindFramebuffer(this._texture, faceIndex);
  24132. }
  24133. else {
  24134. engine.bindFramebuffer(this._texture);
  24135. }
  24136. }
  24137. if (this.activeCamera) {
  24138. engine.setViewport(this.activeCamera.viewport);
  24139. }
  24140. else {
  24141. engine.setViewport(scene.activeCamera.viewport);
  24142. }
  24143. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24144. // Clear
  24145. if (this.onClearObservable.hasObservers()) {
  24146. this.onClearObservable.notifyObservers(engine);
  24147. }
  24148. else {
  24149. engine.clear(scene.clearColor, true, true, true);
  24150. }
  24151. if (!this._doNotChangeAspectRatio) {
  24152. scene.updateTransformMatrix(true);
  24153. }
  24154. // Render
  24155. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24156. if (useCameraPostProcess) {
  24157. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24158. }
  24159. if (!this._doNotChangeAspectRatio) {
  24160. scene.updateTransformMatrix(true);
  24161. }
  24162. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24163. // Dump ?
  24164. if (dumpForDebug) {
  24165. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24166. }
  24167. // Unbind
  24168. if (!this.isCube || faceIndex === 5) {
  24169. if (this.isCube) {
  24170. if (faceIndex === 5) {
  24171. engine.generateMipMapsForCubemap(this._texture);
  24172. }
  24173. }
  24174. engine.unBindFramebuffer(this._texture, this.isCube);
  24175. }
  24176. };
  24177. /**
  24178. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24179. * This allowed control for front to back rendering or reversly depending of the special needs.
  24180. *
  24181. * @param renderingGroupId The rendering group id corresponding to its index
  24182. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24183. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24184. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24185. */
  24186. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24187. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24188. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24189. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24190. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24191. };
  24192. /**
  24193. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24194. *
  24195. * @param renderingGroupId The rendering group id corresponding to its index
  24196. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24197. */
  24198. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24199. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24200. };
  24201. RenderTargetTexture.prototype.clone = function () {
  24202. var textureSize = this.getSize();
  24203. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24204. // Base texture
  24205. newTexture.hasAlpha = this.hasAlpha;
  24206. newTexture.level = this.level;
  24207. // RenderTarget Texture
  24208. newTexture.coordinatesMode = this.coordinatesMode;
  24209. newTexture.renderList = this.renderList.slice(0);
  24210. return newTexture;
  24211. };
  24212. RenderTargetTexture.prototype.serialize = function () {
  24213. if (!this.name) {
  24214. return null;
  24215. }
  24216. var serializationObject = _super.prototype.serialize.call(this);
  24217. serializationObject.renderTargetSize = this.getRenderSize();
  24218. serializationObject.renderList = [];
  24219. for (var index = 0; index < this.renderList.length; index++) {
  24220. serializationObject.renderList.push(this.renderList[index].id);
  24221. }
  24222. return serializationObject;
  24223. };
  24224. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24225. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24226. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24227. return RenderTargetTexture;
  24228. }(BABYLON.Texture));
  24229. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24230. })(BABYLON || (BABYLON = {}));
  24231. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24232. var BABYLON;
  24233. (function (BABYLON) {
  24234. var ProceduralTexture = (function (_super) {
  24235. __extends(ProceduralTexture, _super);
  24236. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24238. if (isCube === void 0) { isCube = false; }
  24239. _super.call(this, null, scene, !generateMipMaps);
  24240. this.isCube = isCube;
  24241. this.isEnabled = true;
  24242. this._currentRefreshId = -1;
  24243. this._refreshRate = 1;
  24244. this._vertexBuffers = {};
  24245. this._uniforms = new Array();
  24246. this._samplers = new Array();
  24247. this._textures = new Array();
  24248. this._floats = new Array();
  24249. this._floatsArrays = {};
  24250. this._colors3 = new Array();
  24251. this._colors4 = new Array();
  24252. this._vectors2 = new Array();
  24253. this._vectors3 = new Array();
  24254. this._matrices = new Array();
  24255. this._fallbackTextureUsed = false;
  24256. scene._proceduralTextures.push(this);
  24257. this.name = name;
  24258. this.isRenderTarget = true;
  24259. this._size = size;
  24260. this._generateMipMaps = generateMipMaps;
  24261. this.setFragment(fragment);
  24262. this._fallbackTexture = fallbackTexture;
  24263. var engine = scene.getEngine();
  24264. if (isCube) {
  24265. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24266. this.setFloat("face", 0);
  24267. }
  24268. else {
  24269. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24270. }
  24271. // VBO
  24272. var vertices = [];
  24273. vertices.push(1, 1);
  24274. vertices.push(-1, 1);
  24275. vertices.push(-1, -1);
  24276. vertices.push(1, -1);
  24277. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24278. // Indices
  24279. var indices = [];
  24280. indices.push(0);
  24281. indices.push(1);
  24282. indices.push(2);
  24283. indices.push(0);
  24284. indices.push(2);
  24285. indices.push(3);
  24286. this._indexBuffer = engine.createIndexBuffer(indices);
  24287. }
  24288. ProceduralTexture.prototype.reset = function () {
  24289. if (this._effect === undefined) {
  24290. return;
  24291. }
  24292. var engine = this.getScene().getEngine();
  24293. engine._releaseEffect(this._effect);
  24294. };
  24295. ProceduralTexture.prototype.isReady = function () {
  24296. var _this = this;
  24297. var engine = this.getScene().getEngine();
  24298. var shaders;
  24299. if (!this._fragment) {
  24300. return false;
  24301. }
  24302. if (this._fallbackTextureUsed) {
  24303. return true;
  24304. }
  24305. if (this._fragment.fragmentElement !== undefined) {
  24306. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24307. }
  24308. else {
  24309. shaders = { vertex: "procedural", fragment: this._fragment };
  24310. }
  24311. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24312. _this.releaseInternalTexture();
  24313. if (_this._fallbackTexture) {
  24314. _this._texture = _this._fallbackTexture._texture;
  24315. _this._texture.references++;
  24316. }
  24317. _this._fallbackTextureUsed = true;
  24318. });
  24319. return this._effect.isReady();
  24320. };
  24321. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24322. this._currentRefreshId = -1;
  24323. };
  24324. ProceduralTexture.prototype.setFragment = function (fragment) {
  24325. this._fragment = fragment;
  24326. };
  24327. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24328. get: function () {
  24329. return this._refreshRate;
  24330. },
  24331. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24332. set: function (value) {
  24333. this._refreshRate = value;
  24334. this.resetRefreshCounter();
  24335. },
  24336. enumerable: true,
  24337. configurable: true
  24338. });
  24339. ProceduralTexture.prototype._shouldRender = function () {
  24340. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24341. return false;
  24342. }
  24343. if (this._fallbackTextureUsed) {
  24344. return false;
  24345. }
  24346. if (this._currentRefreshId === -1) {
  24347. this._currentRefreshId = 1;
  24348. return true;
  24349. }
  24350. if (this.refreshRate === this._currentRefreshId) {
  24351. this._currentRefreshId = 1;
  24352. return true;
  24353. }
  24354. this._currentRefreshId++;
  24355. return false;
  24356. };
  24357. ProceduralTexture.prototype.getRenderSize = function () {
  24358. return this._size;
  24359. };
  24360. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24361. if (this._fallbackTextureUsed) {
  24362. return;
  24363. }
  24364. this.releaseInternalTexture();
  24365. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24366. };
  24367. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24368. if (this._uniforms.indexOf(uniformName) === -1) {
  24369. this._uniforms.push(uniformName);
  24370. }
  24371. };
  24372. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24373. if (this._samplers.indexOf(name) === -1) {
  24374. this._samplers.push(name);
  24375. }
  24376. this._textures[name] = texture;
  24377. return this;
  24378. };
  24379. ProceduralTexture.prototype.setFloat = function (name, value) {
  24380. this._checkUniform(name);
  24381. this._floats[name] = value;
  24382. return this;
  24383. };
  24384. ProceduralTexture.prototype.setFloats = function (name, value) {
  24385. this._checkUniform(name);
  24386. this._floatsArrays[name] = value;
  24387. return this;
  24388. };
  24389. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24390. this._checkUniform(name);
  24391. this._colors3[name] = value;
  24392. return this;
  24393. };
  24394. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24395. this._checkUniform(name);
  24396. this._colors4[name] = value;
  24397. return this;
  24398. };
  24399. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24400. this._checkUniform(name);
  24401. this._vectors2[name] = value;
  24402. return this;
  24403. };
  24404. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24405. this._checkUniform(name);
  24406. this._vectors3[name] = value;
  24407. return this;
  24408. };
  24409. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24410. this._checkUniform(name);
  24411. this._matrices[name] = value;
  24412. return this;
  24413. };
  24414. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24415. var scene = this.getScene();
  24416. var engine = scene.getEngine();
  24417. // Render
  24418. engine.enableEffect(this._effect);
  24419. engine.setState(false);
  24420. // Texture
  24421. for (var name in this._textures) {
  24422. this._effect.setTexture(name, this._textures[name]);
  24423. }
  24424. // Float
  24425. for (name in this._floats) {
  24426. this._effect.setFloat(name, this._floats[name]);
  24427. }
  24428. // Floats
  24429. for (name in this._floatsArrays) {
  24430. this._effect.setArray(name, this._floatsArrays[name]);
  24431. }
  24432. // Color3
  24433. for (name in this._colors3) {
  24434. this._effect.setColor3(name, this._colors3[name]);
  24435. }
  24436. // Color4
  24437. for (name in this._colors4) {
  24438. var color = this._colors4[name];
  24439. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24440. }
  24441. // Vector2
  24442. for (name in this._vectors2) {
  24443. this._effect.setVector2(name, this._vectors2[name]);
  24444. }
  24445. // Vector3
  24446. for (name in this._vectors3) {
  24447. this._effect.setVector3(name, this._vectors3[name]);
  24448. }
  24449. // Matrix
  24450. for (name in this._matrices) {
  24451. this._effect.setMatrix(name, this._matrices[name]);
  24452. }
  24453. // VBOs
  24454. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24455. if (this.isCube) {
  24456. for (var face = 0; face < 6; face++) {
  24457. engine.bindFramebuffer(this._texture, face);
  24458. this._effect.setFloat("face", face);
  24459. // Clear
  24460. engine.clear(scene.clearColor, true, true, true);
  24461. // Draw order
  24462. engine.draw(true, 0, 6);
  24463. // Mipmaps
  24464. if (face === 5) {
  24465. engine.generateMipMapsForCubemap(this._texture);
  24466. }
  24467. }
  24468. }
  24469. else {
  24470. engine.bindFramebuffer(this._texture);
  24471. // Clear
  24472. engine.clear(scene.clearColor, true, true, true);
  24473. // Draw order
  24474. engine.draw(true, 0, 6);
  24475. }
  24476. // Unbind
  24477. engine.unBindFramebuffer(this._texture, this.isCube);
  24478. if (this.onGenerated) {
  24479. this.onGenerated();
  24480. }
  24481. };
  24482. ProceduralTexture.prototype.clone = function () {
  24483. var textureSize = this.getSize();
  24484. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24485. // Base texture
  24486. newTexture.hasAlpha = this.hasAlpha;
  24487. newTexture.level = this.level;
  24488. // RenderTarget Texture
  24489. newTexture.coordinatesMode = this.coordinatesMode;
  24490. return newTexture;
  24491. };
  24492. ProceduralTexture.prototype.dispose = function () {
  24493. var index = this.getScene()._proceduralTextures.indexOf(this);
  24494. if (index >= 0) {
  24495. this.getScene()._proceduralTextures.splice(index, 1);
  24496. }
  24497. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24498. if (vertexBuffer) {
  24499. vertexBuffer.dispose();
  24500. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24501. }
  24502. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24503. this._indexBuffer = null;
  24504. }
  24505. _super.prototype.dispose.call(this);
  24506. };
  24507. return ProceduralTexture;
  24508. }(BABYLON.Texture));
  24509. BABYLON.ProceduralTexture = ProceduralTexture;
  24510. })(BABYLON || (BABYLON = {}));
  24511. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24512. var BABYLON;
  24513. (function (BABYLON) {
  24514. var MirrorTexture = (function (_super) {
  24515. __extends(MirrorTexture, _super);
  24516. function MirrorTexture(name, size, scene, generateMipMaps) {
  24517. var _this = this;
  24518. _super.call(this, name, size, scene, generateMipMaps, true);
  24519. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24520. this._transformMatrix = BABYLON.Matrix.Zero();
  24521. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24522. this.onBeforeRenderObservable.add(function () {
  24523. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24524. _this._savedViewMatrix = scene.getViewMatrix();
  24525. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24526. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24527. scene.clipPlane = _this.mirrorPlane;
  24528. scene.getEngine().cullBackFaces = false;
  24529. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24530. });
  24531. this.onAfterRenderObservable.add(function () {
  24532. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24533. scene.getEngine().cullBackFaces = true;
  24534. scene._mirroredCameraPosition = null;
  24535. delete scene.clipPlane;
  24536. });
  24537. }
  24538. MirrorTexture.prototype.clone = function () {
  24539. var textureSize = this.getSize();
  24540. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24541. // Base texture
  24542. newTexture.hasAlpha = this.hasAlpha;
  24543. newTexture.level = this.level;
  24544. // Mirror Texture
  24545. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24546. newTexture.renderList = this.renderList.slice(0);
  24547. return newTexture;
  24548. };
  24549. MirrorTexture.prototype.serialize = function () {
  24550. if (!this.name) {
  24551. return null;
  24552. }
  24553. var serializationObject = _super.prototype.serialize.call(this);
  24554. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24555. return serializationObject;
  24556. };
  24557. return MirrorTexture;
  24558. }(BABYLON.RenderTargetTexture));
  24559. BABYLON.MirrorTexture = MirrorTexture;
  24560. })(BABYLON || (BABYLON = {}));
  24561. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24562. var BABYLON;
  24563. (function (BABYLON) {
  24564. /**
  24565. * Creates a refraction texture used by refraction channel of the standard material.
  24566. * @param name the texture name
  24567. * @param size size of the underlying texture
  24568. * @param scene root scene
  24569. */
  24570. var RefractionTexture = (function (_super) {
  24571. __extends(RefractionTexture, _super);
  24572. function RefractionTexture(name, size, scene, generateMipMaps) {
  24573. var _this = this;
  24574. _super.call(this, name, size, scene, generateMipMaps, true);
  24575. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24576. this.depth = 2.0;
  24577. this.onBeforeRenderObservable.add(function () {
  24578. scene.clipPlane = _this.refractionPlane;
  24579. });
  24580. this.onAfterRenderObservable.add(function () {
  24581. delete scene.clipPlane;
  24582. });
  24583. }
  24584. RefractionTexture.prototype.clone = function () {
  24585. var textureSize = this.getSize();
  24586. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24587. // Base texture
  24588. newTexture.hasAlpha = this.hasAlpha;
  24589. newTexture.level = this.level;
  24590. // Refraction Texture
  24591. newTexture.refractionPlane = this.refractionPlane.clone();
  24592. newTexture.renderList = this.renderList.slice(0);
  24593. newTexture.depth = this.depth;
  24594. return newTexture;
  24595. };
  24596. RefractionTexture.prototype.serialize = function () {
  24597. if (!this.name) {
  24598. return null;
  24599. }
  24600. var serializationObject = _super.prototype.serialize.call(this);
  24601. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24602. serializationObject.depth = this.depth;
  24603. return serializationObject;
  24604. };
  24605. return RefractionTexture;
  24606. }(BABYLON.RenderTargetTexture));
  24607. BABYLON.RefractionTexture = RefractionTexture;
  24608. })(BABYLON || (BABYLON = {}));
  24609. //# sourceMappingURL=babylon.refractionTexture.js.map
  24610. var BABYLON;
  24611. (function (BABYLON) {
  24612. var DynamicTexture = (function (_super) {
  24613. __extends(DynamicTexture, _super);
  24614. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24616. _super.call(this, null, scene, !generateMipMaps);
  24617. this.name = name;
  24618. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24619. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24620. this._generateMipMaps = generateMipMaps;
  24621. if (options.getContext) {
  24622. this._canvas = options;
  24623. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24624. }
  24625. else {
  24626. this._canvas = document.createElement("canvas");
  24627. if (options.width) {
  24628. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24629. }
  24630. else {
  24631. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24632. }
  24633. }
  24634. var textureSize = this.getSize();
  24635. this._canvas.width = textureSize.width;
  24636. this._canvas.height = textureSize.height;
  24637. this._context = this._canvas.getContext("2d");
  24638. }
  24639. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24640. get: function () {
  24641. return true;
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. DynamicTexture.prototype.scale = function (ratio) {
  24647. var textureSize = this.getSize();
  24648. textureSize.width *= ratio;
  24649. textureSize.height *= ratio;
  24650. this._canvas.width = textureSize.width;
  24651. this._canvas.height = textureSize.height;
  24652. this.releaseInternalTexture();
  24653. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24654. };
  24655. DynamicTexture.prototype.getContext = function () {
  24656. return this._context;
  24657. };
  24658. DynamicTexture.prototype.clear = function () {
  24659. var size = this.getSize();
  24660. this._context.fillRect(0, 0, size.width, size.height);
  24661. };
  24662. DynamicTexture.prototype.update = function (invertY) {
  24663. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24664. };
  24665. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24666. if (update === void 0) { update = true; }
  24667. var size = this.getSize();
  24668. if (clearColor) {
  24669. this._context.fillStyle = clearColor;
  24670. this._context.fillRect(0, 0, size.width, size.height);
  24671. }
  24672. this._context.font = font;
  24673. if (x === null) {
  24674. var textSize = this._context.measureText(text);
  24675. x = (size.width - textSize.width) / 2;
  24676. }
  24677. this._context.fillStyle = color;
  24678. this._context.fillText(text, x, y);
  24679. if (update) {
  24680. this.update(invertY);
  24681. }
  24682. };
  24683. DynamicTexture.prototype.clone = function () {
  24684. var textureSize = this.getSize();
  24685. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24686. // Base texture
  24687. newTexture.hasAlpha = this.hasAlpha;
  24688. newTexture.level = this.level;
  24689. // Dynamic Texture
  24690. newTexture.wrapU = this.wrapU;
  24691. newTexture.wrapV = this.wrapV;
  24692. return newTexture;
  24693. };
  24694. return DynamicTexture;
  24695. }(BABYLON.Texture));
  24696. BABYLON.DynamicTexture = DynamicTexture;
  24697. })(BABYLON || (BABYLON = {}));
  24698. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24699. var BABYLON;
  24700. (function (BABYLON) {
  24701. var VideoTexture = (function (_super) {
  24702. __extends(VideoTexture, _super);
  24703. /**
  24704. * Creates a video texture.
  24705. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24706. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24707. * @param {BABYLON.Scene} scene is obviously the current scene.
  24708. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24709. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24710. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24711. */
  24712. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24713. var _this = this;
  24714. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24715. if (invertY === void 0) { invertY = false; }
  24716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24717. _super.call(this, null, scene, !generateMipMaps, invertY);
  24718. this._autoLaunch = true;
  24719. var urls;
  24720. this.name = name;
  24721. if (urlsOrVideo instanceof HTMLVideoElement) {
  24722. this.video = urlsOrVideo;
  24723. }
  24724. else {
  24725. urls = urlsOrVideo;
  24726. this.video = document.createElement("video");
  24727. this.video.autoplay = false;
  24728. this.video.loop = true;
  24729. }
  24730. this._generateMipMaps = generateMipMaps;
  24731. this._samplingMode = samplingMode;
  24732. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24733. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24734. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24735. }
  24736. else {
  24737. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24738. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24739. this._generateMipMaps = false;
  24740. }
  24741. if (urls) {
  24742. this.video.addEventListener("canplaythrough", function () {
  24743. _this._createTexture();
  24744. });
  24745. urls.forEach(function (url) {
  24746. var source = document.createElement("source");
  24747. source.src = url;
  24748. _this.video.appendChild(source);
  24749. });
  24750. }
  24751. else {
  24752. this._createTexture();
  24753. }
  24754. this._lastUpdate = BABYLON.Tools.Now;
  24755. }
  24756. VideoTexture.prototype._createTexture = function () {
  24757. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24758. this._texture.isReady = true;
  24759. };
  24760. VideoTexture.prototype.update = function () {
  24761. if (this._autoLaunch) {
  24762. this._autoLaunch = false;
  24763. this.video.play();
  24764. }
  24765. var now = BABYLON.Tools.Now;
  24766. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24767. return false;
  24768. }
  24769. this._lastUpdate = now;
  24770. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24771. return true;
  24772. };
  24773. return VideoTexture;
  24774. }(BABYLON.Texture));
  24775. BABYLON.VideoTexture = VideoTexture;
  24776. })(BABYLON || (BABYLON = {}));
  24777. //# sourceMappingURL=babylon.videoTexture.js.map
  24778. var BABYLON;
  24779. (function (BABYLON) {
  24780. var CustomProceduralTexture = (function (_super) {
  24781. __extends(CustomProceduralTexture, _super);
  24782. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24783. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24784. this._animate = true;
  24785. this._time = 0;
  24786. this._texturePath = texturePath;
  24787. //Try to load json
  24788. this.loadJson(texturePath);
  24789. this.refreshRate = 1;
  24790. }
  24791. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24792. var _this = this;
  24793. var that = this;
  24794. function noConfigFile() {
  24795. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24796. try {
  24797. that.setFragment(that._texturePath);
  24798. }
  24799. catch (ex) {
  24800. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24801. }
  24802. }
  24803. var configFileUrl = jsonUrl + "/config.json";
  24804. var xhr = new XMLHttpRequest();
  24805. xhr.open("GET", configFileUrl, true);
  24806. xhr.addEventListener("load", function () {
  24807. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24808. try {
  24809. _this._config = JSON.parse(xhr.response);
  24810. _this.updateShaderUniforms();
  24811. _this.updateTextures();
  24812. _this.setFragment(_this._texturePath + "/custom");
  24813. _this._animate = _this._config.animate;
  24814. _this.refreshRate = _this._config.refreshrate;
  24815. }
  24816. catch (ex) {
  24817. noConfigFile();
  24818. }
  24819. }
  24820. else {
  24821. noConfigFile();
  24822. }
  24823. }, false);
  24824. xhr.addEventListener("error", function () {
  24825. noConfigFile();
  24826. }, false);
  24827. try {
  24828. xhr.send();
  24829. }
  24830. catch (ex) {
  24831. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24832. }
  24833. };
  24834. CustomProceduralTexture.prototype.isReady = function () {
  24835. if (!_super.prototype.isReady.call(this)) {
  24836. return false;
  24837. }
  24838. for (var name in this._textures) {
  24839. var texture = this._textures[name];
  24840. if (!texture.isReady()) {
  24841. return false;
  24842. }
  24843. }
  24844. return true;
  24845. };
  24846. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24847. if (this._animate) {
  24848. this._time += this.getScene().getAnimationRatio() * 0.03;
  24849. this.updateShaderUniforms();
  24850. }
  24851. _super.prototype.render.call(this, useCameraPostProcess);
  24852. };
  24853. CustomProceduralTexture.prototype.updateTextures = function () {
  24854. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24855. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24856. }
  24857. };
  24858. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24859. if (this._config) {
  24860. for (var j = 0; j < this._config.uniforms.length; j++) {
  24861. var uniform = this._config.uniforms[j];
  24862. switch (uniform.type) {
  24863. case "float":
  24864. this.setFloat(uniform.name, uniform.value);
  24865. break;
  24866. case "color3":
  24867. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24868. break;
  24869. case "color4":
  24870. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24871. break;
  24872. case "vector2":
  24873. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24874. break;
  24875. case "vector3":
  24876. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24877. break;
  24878. }
  24879. }
  24880. }
  24881. this.setFloat("time", this._time);
  24882. };
  24883. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24884. get: function () {
  24885. return this._animate;
  24886. },
  24887. set: function (value) {
  24888. this._animate = value;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. return CustomProceduralTexture;
  24894. }(BABYLON.ProceduralTexture));
  24895. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24896. })(BABYLON || (BABYLON = {}));
  24897. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24898. var BABYLON;
  24899. (function (BABYLON) {
  24900. var EffectFallbacks = (function () {
  24901. function EffectFallbacks() {
  24902. this._defines = {};
  24903. this._currentRank = 32;
  24904. this._maxRank = -1;
  24905. }
  24906. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24907. if (!this._defines[rank]) {
  24908. if (rank < this._currentRank) {
  24909. this._currentRank = rank;
  24910. }
  24911. if (rank > this._maxRank) {
  24912. this._maxRank = rank;
  24913. }
  24914. this._defines[rank] = new Array();
  24915. }
  24916. this._defines[rank].push(define);
  24917. };
  24918. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24919. this._meshRank = rank;
  24920. this._mesh = mesh;
  24921. if (rank > this._maxRank) {
  24922. this._maxRank = rank;
  24923. }
  24924. };
  24925. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24926. get: function () {
  24927. return this._currentRank <= this._maxRank;
  24928. },
  24929. enumerable: true,
  24930. configurable: true
  24931. });
  24932. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24933. var currentFallbacks = this._defines[this._currentRank];
  24934. for (var index = 0; index < currentFallbacks.length; index++) {
  24935. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24936. }
  24937. if (this._mesh && this._currentRank === this._meshRank) {
  24938. this._mesh.computeBonesUsingShaders = false;
  24939. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24940. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24941. }
  24942. this._currentRank++;
  24943. return currentDefines;
  24944. };
  24945. return EffectFallbacks;
  24946. }());
  24947. BABYLON.EffectFallbacks = EffectFallbacks;
  24948. var Effect = (function () {
  24949. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24950. var _this = this;
  24951. this._isReady = false;
  24952. this._compilationError = "";
  24953. this._valueCache = {};
  24954. this._engine = engine;
  24955. this.name = baseName;
  24956. this.defines = defines;
  24957. this._uniformsNames = uniformsNames.concat(samplers);
  24958. this._samplers = samplers;
  24959. this._attributesNames = attributesNames;
  24960. this.onError = onError;
  24961. this.onCompiled = onCompiled;
  24962. this._indexParameters = indexParameters;
  24963. var vertexSource;
  24964. var fragmentSource;
  24965. if (baseName.vertexElement) {
  24966. vertexSource = document.getElementById(baseName.vertexElement);
  24967. if (!vertexSource) {
  24968. vertexSource = baseName.vertexElement;
  24969. }
  24970. }
  24971. else {
  24972. vertexSource = baseName.vertex || baseName;
  24973. }
  24974. if (baseName.fragmentElement) {
  24975. fragmentSource = document.getElementById(baseName.fragmentElement);
  24976. if (!fragmentSource) {
  24977. fragmentSource = baseName.fragmentElement;
  24978. }
  24979. }
  24980. else {
  24981. fragmentSource = baseName.fragment || baseName;
  24982. }
  24983. this._loadVertexShader(vertexSource, function (vertexCode) {
  24984. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24985. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24986. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24987. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24988. });
  24989. });
  24990. });
  24991. });
  24992. }
  24993. // Properties
  24994. Effect.prototype.isReady = function () {
  24995. return this._isReady;
  24996. };
  24997. Effect.prototype.getProgram = function () {
  24998. return this._program;
  24999. };
  25000. Effect.prototype.getAttributesNames = function () {
  25001. return this._attributesNames;
  25002. };
  25003. Effect.prototype.getAttributeLocation = function (index) {
  25004. return this._attributes[index];
  25005. };
  25006. Effect.prototype.getAttributeLocationByName = function (name) {
  25007. var index = this._attributesNames.indexOf(name);
  25008. return this._attributes[index];
  25009. };
  25010. Effect.prototype.getAttributesCount = function () {
  25011. return this._attributes.length;
  25012. };
  25013. Effect.prototype.getUniformIndex = function (uniformName) {
  25014. return this._uniformsNames.indexOf(uniformName);
  25015. };
  25016. Effect.prototype.getUniform = function (uniformName) {
  25017. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25018. };
  25019. Effect.prototype.getSamplers = function () {
  25020. return this._samplers;
  25021. };
  25022. Effect.prototype.getCompilationError = function () {
  25023. return this._compilationError;
  25024. };
  25025. Effect.prototype.getVertexShaderSource = function () {
  25026. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25027. };
  25028. Effect.prototype.getFragmentShaderSource = function () {
  25029. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25030. };
  25031. // Methods
  25032. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25033. // DOM element ?
  25034. if (vertex instanceof HTMLElement) {
  25035. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25036. callback(vertexCode);
  25037. return;
  25038. }
  25039. // Base64 encoded ?
  25040. if (vertex.substr(0, 7) === "base64:") {
  25041. var vertexBinary = window.atob(vertex.substr(7));
  25042. callback(vertexBinary);
  25043. return;
  25044. }
  25045. // Is in local store ?
  25046. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25047. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25048. return;
  25049. }
  25050. var vertexShaderUrl;
  25051. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25052. vertexShaderUrl = vertex;
  25053. }
  25054. else {
  25055. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25056. }
  25057. // Vertex shader
  25058. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25059. };
  25060. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25061. // DOM element ?
  25062. if (fragment instanceof HTMLElement) {
  25063. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25064. callback(fragmentCode);
  25065. return;
  25066. }
  25067. // Base64 encoded ?
  25068. if (fragment.substr(0, 7) === "base64:") {
  25069. var fragmentBinary = window.atob(fragment.substr(7));
  25070. callback(fragmentBinary);
  25071. return;
  25072. }
  25073. // Is in local store ?
  25074. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25075. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25076. return;
  25077. }
  25078. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25079. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25080. return;
  25081. }
  25082. var fragmentShaderUrl;
  25083. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25084. fragmentShaderUrl = fragment;
  25085. }
  25086. else {
  25087. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25088. }
  25089. // Fragment shader
  25090. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25091. };
  25092. Effect.prototype._dumpShadersName = function () {
  25093. if (this.name.vertexElement) {
  25094. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25095. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25096. }
  25097. else if (this.name.vertex) {
  25098. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25099. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25100. }
  25101. else {
  25102. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25103. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25104. }
  25105. };
  25106. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25107. var _this = this;
  25108. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25109. var match = regex.exec(sourceCode);
  25110. var returnValue = new String(sourceCode);
  25111. while (match != null) {
  25112. var includeFile = match[1];
  25113. if (Effect.IncludesShadersStore[includeFile]) {
  25114. // Substitution
  25115. var includeContent = Effect.IncludesShadersStore[includeFile];
  25116. if (match[2]) {
  25117. var splits = match[3].split(",");
  25118. for (var index = 0; index < splits.length; index += 2) {
  25119. var source = new RegExp(splits[index], "g");
  25120. var dest = splits[index + 1];
  25121. includeContent = includeContent.replace(source, dest);
  25122. }
  25123. }
  25124. if (match[4]) {
  25125. var indexString = match[5];
  25126. if (indexString.indexOf("..") !== -1) {
  25127. var indexSplits = indexString.split("..");
  25128. var minIndex = parseInt(indexSplits[0]);
  25129. var maxIndex = parseInt(indexSplits[1]);
  25130. var sourceIncludeContent = includeContent.slice(0);
  25131. includeContent = "";
  25132. if (isNaN(maxIndex)) {
  25133. maxIndex = this._indexParameters[indexSplits[1]];
  25134. }
  25135. for (var i = minIndex; i <= maxIndex; i++) {
  25136. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25137. }
  25138. }
  25139. else {
  25140. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25141. }
  25142. }
  25143. // Replace
  25144. returnValue = returnValue.replace(match[0], includeContent);
  25145. }
  25146. else {
  25147. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25148. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25149. Effect.IncludesShadersStore[includeFile] = fileContent;
  25150. _this._processIncludes(returnValue, callback);
  25151. });
  25152. return;
  25153. }
  25154. match = regex.exec(sourceCode);
  25155. }
  25156. callback(returnValue);
  25157. };
  25158. Effect.prototype._processPrecision = function (source) {
  25159. if (source.indexOf("precision highp float") === -1) {
  25160. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25161. source = "precision mediump float;\n" + source;
  25162. }
  25163. else {
  25164. source = "precision highp float;\n" + source;
  25165. }
  25166. }
  25167. else {
  25168. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25169. source = source.replace("precision highp float", "precision mediump float");
  25170. }
  25171. }
  25172. return source;
  25173. };
  25174. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25175. try {
  25176. var engine = this._engine;
  25177. // Precision
  25178. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25179. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25180. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25181. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25182. this._attributes = engine.getAttributes(this._program, attributesNames);
  25183. var index;
  25184. for (index = 0; index < this._samplers.length; index++) {
  25185. var sampler = this.getUniform(this._samplers[index]);
  25186. if (sampler == null) {
  25187. this._samplers.splice(index, 1);
  25188. index--;
  25189. }
  25190. }
  25191. engine.bindSamplers(this);
  25192. this._compilationError = "";
  25193. this._isReady = true;
  25194. if (this.onCompiled) {
  25195. this.onCompiled(this);
  25196. }
  25197. }
  25198. catch (e) {
  25199. this._compilationError = e.message;
  25200. // Let's go through fallbacks then
  25201. BABYLON.Tools.Error("Unable to compile effect: ");
  25202. BABYLON.Tools.Error("Defines: " + defines);
  25203. BABYLON.Tools.Error("Error: " + this._compilationError);
  25204. this._dumpShadersName();
  25205. if (fallbacks && fallbacks.isMoreFallbacks) {
  25206. BABYLON.Tools.Error("Trying next fallback.");
  25207. defines = fallbacks.reduce(defines);
  25208. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25209. }
  25210. else {
  25211. if (this.onError) {
  25212. this.onError(this, this._compilationError);
  25213. }
  25214. }
  25215. }
  25216. };
  25217. Object.defineProperty(Effect.prototype, "isSupported", {
  25218. get: function () {
  25219. return this._compilationError === "";
  25220. },
  25221. enumerable: true,
  25222. configurable: true
  25223. });
  25224. Effect.prototype._bindTexture = function (channel, texture) {
  25225. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25226. };
  25227. Effect.prototype.setTexture = function (channel, texture) {
  25228. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25229. };
  25230. Effect.prototype.setTextureArray = function (channel, textures) {
  25231. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25232. var initialPos = this._samplers.indexOf(channel);
  25233. for (var index = 1; index < textures.length; index++) {
  25234. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25235. }
  25236. }
  25237. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25238. };
  25239. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25240. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25241. };
  25242. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25243. var changed = false;
  25244. var cache = this._valueCache[uniformName];
  25245. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25246. changed = true;
  25247. cache = new BABYLON.Matrix();
  25248. }
  25249. var tm = cache.m;
  25250. var om = matrix.m;
  25251. for (var index = 0; index < 16; index++) {
  25252. if (tm[index] !== om[index]) {
  25253. tm[index] = om[index];
  25254. changed = true;
  25255. }
  25256. }
  25257. this._valueCache[uniformName] = cache;
  25258. return changed;
  25259. };
  25260. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25261. var cache = this._valueCache[uniformName];
  25262. if (!cache) {
  25263. cache = [x, y];
  25264. this._valueCache[uniformName] = cache;
  25265. return true;
  25266. }
  25267. var changed = false;
  25268. if (cache[0] !== x) {
  25269. cache[0] = x;
  25270. changed = true;
  25271. }
  25272. if (cache[1] !== y) {
  25273. cache[1] = y;
  25274. changed = true;
  25275. }
  25276. return changed;
  25277. };
  25278. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25279. var cache = this._valueCache[uniformName];
  25280. if (!cache) {
  25281. cache = [x, y, z];
  25282. this._valueCache[uniformName] = cache;
  25283. return true;
  25284. }
  25285. var changed = false;
  25286. if (cache[0] !== x) {
  25287. cache[0] = x;
  25288. changed = true;
  25289. }
  25290. if (cache[1] !== y) {
  25291. cache[1] = y;
  25292. changed = true;
  25293. }
  25294. if (cache[2] !== z) {
  25295. cache[2] = z;
  25296. changed = true;
  25297. }
  25298. return changed;
  25299. };
  25300. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25301. var cache = this._valueCache[uniformName];
  25302. if (!cache) {
  25303. cache = [x, y, z, w];
  25304. this._valueCache[uniformName] = cache;
  25305. return true;
  25306. }
  25307. var changed = false;
  25308. if (cache[0] !== x) {
  25309. cache[0] = x;
  25310. changed = true;
  25311. }
  25312. if (cache[1] !== y) {
  25313. cache[1] = y;
  25314. changed = true;
  25315. }
  25316. if (cache[2] !== z) {
  25317. cache[2] = z;
  25318. changed = true;
  25319. }
  25320. if (cache[3] !== w) {
  25321. cache[3] = w;
  25322. changed = true;
  25323. }
  25324. return changed;
  25325. };
  25326. Effect.prototype.setIntArray = function (uniformName, array) {
  25327. this._valueCache[uniformName] = null;
  25328. this._engine.setIntArray(this.getUniform(uniformName), array);
  25329. return this;
  25330. };
  25331. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25332. this._valueCache[uniformName] = null;
  25333. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25334. return this;
  25335. };
  25336. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25337. this._valueCache[uniformName] = null;
  25338. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25339. return this;
  25340. };
  25341. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25342. this._valueCache[uniformName] = null;
  25343. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25344. return this;
  25345. };
  25346. Effect.prototype.setFloatArray = function (uniformName, array) {
  25347. this._valueCache[uniformName] = null;
  25348. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25349. return this;
  25350. };
  25351. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25352. this._valueCache[uniformName] = null;
  25353. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25354. return this;
  25355. };
  25356. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25357. this._valueCache[uniformName] = null;
  25358. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25359. return this;
  25360. };
  25361. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25362. this._valueCache[uniformName] = null;
  25363. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25364. return this;
  25365. };
  25366. Effect.prototype.setArray = function (uniformName, array) {
  25367. this._valueCache[uniformName] = null;
  25368. this._engine.setArray(this.getUniform(uniformName), array);
  25369. return this;
  25370. };
  25371. Effect.prototype.setArray2 = function (uniformName, array) {
  25372. this._valueCache[uniformName] = null;
  25373. this._engine.setArray2(this.getUniform(uniformName), array);
  25374. return this;
  25375. };
  25376. Effect.prototype.setArray3 = function (uniformName, array) {
  25377. this._valueCache[uniformName] = null;
  25378. this._engine.setArray3(this.getUniform(uniformName), array);
  25379. return this;
  25380. };
  25381. Effect.prototype.setArray4 = function (uniformName, array) {
  25382. this._valueCache[uniformName] = null;
  25383. this._engine.setArray4(this.getUniform(uniformName), array);
  25384. return this;
  25385. };
  25386. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25387. this._valueCache[uniformName] = null;
  25388. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25389. return this;
  25390. };
  25391. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25392. if (this._cacheMatrix(uniformName, matrix)) {
  25393. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25394. }
  25395. return this;
  25396. };
  25397. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25398. this._valueCache[uniformName] = null;
  25399. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25400. return this;
  25401. };
  25402. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25403. this._valueCache[uniformName] = null;
  25404. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25405. return this;
  25406. };
  25407. Effect.prototype.setFloat = function (uniformName, value) {
  25408. var cache = this._valueCache[uniformName];
  25409. if (cache !== undefined && cache === value)
  25410. return this;
  25411. this._valueCache[uniformName] = value;
  25412. this._engine.setFloat(this.getUniform(uniformName), value);
  25413. return this;
  25414. };
  25415. Effect.prototype.setBool = function (uniformName, bool) {
  25416. var cache = this._valueCache[uniformName];
  25417. if (cache !== undefined && cache === bool)
  25418. return this;
  25419. this._valueCache[uniformName] = bool;
  25420. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25421. return this;
  25422. };
  25423. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25424. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25425. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25426. }
  25427. return this;
  25428. };
  25429. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25430. if (this._cacheFloat2(uniformName, x, y)) {
  25431. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25432. }
  25433. return this;
  25434. };
  25435. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25436. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25437. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25438. }
  25439. return this;
  25440. };
  25441. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25442. if (this._cacheFloat3(uniformName, x, y, z)) {
  25443. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25444. }
  25445. return this;
  25446. };
  25447. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25448. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25449. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25450. }
  25451. return this;
  25452. };
  25453. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25454. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25455. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25456. }
  25457. return this;
  25458. };
  25459. Effect.prototype.setColor3 = function (uniformName, color3) {
  25460. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25461. this._engine.setColor3(this.getUniform(uniformName), color3);
  25462. }
  25463. return this;
  25464. };
  25465. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25466. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25467. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25468. }
  25469. return this;
  25470. };
  25471. Effect.prototype._recombineShader = function (node) {
  25472. if (node.define) {
  25473. if (node.condition) {
  25474. }
  25475. else if (node.ndef) {
  25476. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25477. return null;
  25478. }
  25479. }
  25480. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25481. return null;
  25482. }
  25483. }
  25484. var result = "";
  25485. for (var index = 0; index < node.children.length; index++) {
  25486. var line = node.children[index];
  25487. if (line.children) {
  25488. var combined = this._recombineShader(line) + "\r\n";
  25489. if (combined !== null) {
  25490. result += combined + "\r\n";
  25491. }
  25492. continue;
  25493. }
  25494. result += line + "\r\n";
  25495. }
  25496. return result;
  25497. };
  25498. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25499. var root = {
  25500. children: []
  25501. };
  25502. var currentNode = root;
  25503. var lines = shaderString.split("\n");
  25504. for (var index = 0; index < lines.length; index++) {
  25505. var line = lines[index].trim();
  25506. // #ifdef
  25507. var pos = line.indexOf("#ifdef ");
  25508. if (pos !== -1) {
  25509. var define = line.substr(pos + 7);
  25510. var newNode = {
  25511. condition: null,
  25512. ndef: false,
  25513. define: define,
  25514. children: [],
  25515. parent: currentNode
  25516. };
  25517. currentNode.children.push(newNode);
  25518. currentNode = newNode;
  25519. continue;
  25520. }
  25521. // #ifndef
  25522. var pos = line.indexOf("#ifndef ");
  25523. if (pos !== -1) {
  25524. var define = line.substr(pos + 8);
  25525. newNode = {
  25526. condition: null,
  25527. define: define,
  25528. ndef: true,
  25529. children: [],
  25530. parent: currentNode
  25531. };
  25532. currentNode.children.push(newNode);
  25533. currentNode = newNode;
  25534. continue;
  25535. }
  25536. // #if
  25537. var pos = line.indexOf("#if ");
  25538. if (pos !== -1) {
  25539. var define = line.substr(pos + 4).trim();
  25540. var conditionPos = define.indexOf(" ");
  25541. newNode = {
  25542. condition: define.substr(conditionPos + 1),
  25543. define: define.substr(0, conditionPos),
  25544. ndef: false,
  25545. children: [],
  25546. parent: currentNode
  25547. };
  25548. currentNode.children.push(newNode);
  25549. currentNode = newNode;
  25550. continue;
  25551. }
  25552. // #endif
  25553. pos = line.indexOf("#endif");
  25554. if (pos !== -1) {
  25555. currentNode = currentNode.parent;
  25556. continue;
  25557. }
  25558. currentNode.children.push(line);
  25559. }
  25560. // Recombine
  25561. return this._recombineShader(root);
  25562. };
  25563. // Statics
  25564. Effect.ShadersStore = {};
  25565. Effect.IncludesShadersStore = {};
  25566. return Effect;
  25567. }());
  25568. BABYLON.Effect = Effect;
  25569. })(BABYLON || (BABYLON = {}));
  25570. //# sourceMappingURL=babylon.effect.js.map
  25571. var BABYLON;
  25572. (function (BABYLON) {
  25573. var MaterialHelper = (function () {
  25574. function MaterialHelper() {
  25575. }
  25576. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25577. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25578. var lightIndex = 0;
  25579. var needNormals = false;
  25580. var needRebuild = false;
  25581. var needShadows = false;
  25582. var lightmapMode = false;
  25583. for (var index = 0; index < scene.lights.length; index++) {
  25584. var light = scene.lights[index];
  25585. if (!light.isEnabled()) {
  25586. continue;
  25587. }
  25588. // Excluded check
  25589. if (light._excludedMeshesIds.length > 0) {
  25590. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25591. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25592. if (excludedMesh) {
  25593. light.excludedMeshes.push(excludedMesh);
  25594. }
  25595. }
  25596. light._excludedMeshesIds = [];
  25597. }
  25598. // Included check
  25599. if (light._includedOnlyMeshesIds.length > 0) {
  25600. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25601. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25602. if (includedOnlyMesh) {
  25603. light.includedOnlyMeshes.push(includedOnlyMesh);
  25604. }
  25605. }
  25606. light._includedOnlyMeshesIds = [];
  25607. }
  25608. if (!light.canAffectMesh(mesh)) {
  25609. continue;
  25610. }
  25611. needNormals = true;
  25612. if (defines["LIGHT" + lightIndex] === undefined) {
  25613. needRebuild = true;
  25614. }
  25615. defines["LIGHT" + lightIndex] = true;
  25616. var type;
  25617. if (light instanceof BABYLON.SpotLight) {
  25618. type = "SPOTLIGHT" + lightIndex;
  25619. }
  25620. else if (light instanceof BABYLON.HemisphericLight) {
  25621. type = "HEMILIGHT" + lightIndex;
  25622. }
  25623. else if (light instanceof BABYLON.PointLight) {
  25624. type = "POINTLIGHT" + lightIndex;
  25625. }
  25626. else {
  25627. type = "DIRLIGHT" + lightIndex;
  25628. }
  25629. if (defines[type] === undefined) {
  25630. needRebuild = true;
  25631. }
  25632. defines[type] = true;
  25633. // Specular
  25634. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25635. defines["SPECULARTERM"] = true;
  25636. }
  25637. // Shadows
  25638. if (scene.shadowsEnabled) {
  25639. var shadowGenerator = light.getShadowGenerator();
  25640. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25641. if (defines["SHADOW" + lightIndex] === undefined) {
  25642. needRebuild = true;
  25643. }
  25644. defines["SHADOW" + lightIndex] = true;
  25645. defines["SHADOWS"] = true;
  25646. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25647. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25648. needRebuild = true;
  25649. }
  25650. defines["SHADOWVSM" + lightIndex] = true;
  25651. }
  25652. if (shadowGenerator.usePoissonSampling) {
  25653. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25654. needRebuild = true;
  25655. }
  25656. defines["SHADOWPCF" + lightIndex] = true;
  25657. }
  25658. needShadows = true;
  25659. }
  25660. }
  25661. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25662. lightmapMode = true;
  25663. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25664. needRebuild = true;
  25665. }
  25666. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25667. needRebuild = true;
  25668. }
  25669. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25670. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25671. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25672. }
  25673. }
  25674. lightIndex++;
  25675. if (lightIndex === maxSimultaneousLights)
  25676. break;
  25677. }
  25678. var caps = scene.getEngine().getCaps();
  25679. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25680. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25681. needRebuild = true;
  25682. }
  25683. defines["SHADOWFULLFLOAT"] = true;
  25684. }
  25685. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25686. needRebuild = true;
  25687. }
  25688. if (lightmapMode) {
  25689. defines["LIGHTMAPEXCLUDED"] = true;
  25690. }
  25691. if (needRebuild) {
  25692. defines.rebuild();
  25693. }
  25694. return needNormals;
  25695. };
  25696. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25697. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25698. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25699. if (!defines["LIGHT" + lightIndex]) {
  25700. break;
  25701. }
  25702. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25703. samplersList.push("shadowSampler" + lightIndex);
  25704. }
  25705. };
  25706. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25707. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25708. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25709. if (!defines["LIGHT" + lightIndex]) {
  25710. break;
  25711. }
  25712. if (lightIndex > 0) {
  25713. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25714. }
  25715. if (defines["SHADOW" + lightIndex]) {
  25716. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25717. }
  25718. if (defines["SHADOWPCF" + lightIndex]) {
  25719. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25720. }
  25721. if (defines["SHADOWVSM" + lightIndex]) {
  25722. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25723. }
  25724. }
  25725. };
  25726. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25727. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25728. fallbacks.addCPUSkinningFallback(0, mesh);
  25729. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25730. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25731. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25734. }
  25735. }
  25736. };
  25737. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25738. if (defines["INSTANCES"]) {
  25739. attribs.push("world0");
  25740. attribs.push("world1");
  25741. attribs.push("world2");
  25742. attribs.push("world3");
  25743. }
  25744. };
  25745. // Bindings
  25746. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25747. var shadowGenerator = light.getShadowGenerator();
  25748. if (mesh.receiveShadows && shadowGenerator) {
  25749. if (!light.needCube()) {
  25750. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25751. }
  25752. else {
  25753. if (!depthValuesAlreadySet) {
  25754. depthValuesAlreadySet = true;
  25755. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25756. }
  25757. }
  25758. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25759. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25760. }
  25761. return depthValuesAlreadySet;
  25762. };
  25763. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25764. if (light instanceof BABYLON.PointLight) {
  25765. // Point Light
  25766. light.transferToEffect(effect, "vLightData" + lightIndex);
  25767. }
  25768. else if (light instanceof BABYLON.DirectionalLight) {
  25769. // Directional Light
  25770. light.transferToEffect(effect, "vLightData" + lightIndex);
  25771. }
  25772. else if (light instanceof BABYLON.SpotLight) {
  25773. // Spot Light
  25774. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25775. }
  25776. else if (light instanceof BABYLON.HemisphericLight) {
  25777. // Hemispheric Light
  25778. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25779. }
  25780. };
  25781. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25782. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25783. var lightIndex = 0;
  25784. var depthValuesAlreadySet = false;
  25785. for (var index = 0; index < scene.lights.length; index++) {
  25786. var light = scene.lights[index];
  25787. if (!light.isEnabled()) {
  25788. continue;
  25789. }
  25790. if (!light.canAffectMesh(mesh)) {
  25791. continue;
  25792. }
  25793. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25794. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25795. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25796. if (defines["SPECULARTERM"]) {
  25797. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25798. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25799. }
  25800. // Shadows
  25801. if (scene.shadowsEnabled) {
  25802. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25803. }
  25804. lightIndex++;
  25805. if (lightIndex === maxSimultaneousLights)
  25806. break;
  25807. }
  25808. };
  25809. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25810. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25811. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25812. effect.setColor3("vFogColor", scene.fogColor);
  25813. }
  25814. };
  25815. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25816. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25817. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25818. if (matrices) {
  25819. effect.setMatrices("mBones", matrices);
  25820. }
  25821. }
  25822. };
  25823. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25824. if (defines["LOGARITHMICDEPTH"]) {
  25825. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25826. }
  25827. };
  25828. MaterialHelper.BindClipPlane = function (effect, scene) {
  25829. if (scene.clipPlane) {
  25830. var clipPlane = scene.clipPlane;
  25831. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25832. }
  25833. };
  25834. return MaterialHelper;
  25835. }());
  25836. BABYLON.MaterialHelper = MaterialHelper;
  25837. })(BABYLON || (BABYLON = {}));
  25838. //# sourceMappingURL=babylon.materialHelper.js.map
  25839. var BABYLON;
  25840. (function (BABYLON) {
  25841. var FresnelParameters = (function () {
  25842. function FresnelParameters() {
  25843. this.isEnabled = true;
  25844. this.leftColor = BABYLON.Color3.White();
  25845. this.rightColor = BABYLON.Color3.Black();
  25846. this.bias = 0;
  25847. this.power = 1;
  25848. }
  25849. FresnelParameters.prototype.clone = function () {
  25850. var newFresnelParameters = new FresnelParameters();
  25851. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25852. return newFresnelParameters;
  25853. };
  25854. FresnelParameters.prototype.serialize = function () {
  25855. var serializationObject = {};
  25856. serializationObject.isEnabled = this.isEnabled;
  25857. serializationObject.leftColor = this.leftColor;
  25858. serializationObject.rightColor = this.rightColor;
  25859. serializationObject.bias = this.bias;
  25860. serializationObject.power = this.power;
  25861. return serializationObject;
  25862. };
  25863. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25864. var fresnelParameters = new FresnelParameters();
  25865. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25866. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25867. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25868. fresnelParameters.bias = parsedFresnelParameters.bias;
  25869. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25870. return fresnelParameters;
  25871. };
  25872. return FresnelParameters;
  25873. }());
  25874. BABYLON.FresnelParameters = FresnelParameters;
  25875. })(BABYLON || (BABYLON = {}));
  25876. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25877. var BABYLON;
  25878. (function (BABYLON) {
  25879. var MaterialDefines = (function () {
  25880. function MaterialDefines() {
  25881. }
  25882. MaterialDefines.prototype.rebuild = function () {
  25883. if (this._keys) {
  25884. delete this._keys;
  25885. }
  25886. this._keys = Object.keys(this);
  25887. };
  25888. MaterialDefines.prototype.isEqual = function (other) {
  25889. if (this._keys.length !== other._keys.length) {
  25890. return false;
  25891. }
  25892. for (var index = 0; index < this._keys.length; index++) {
  25893. var prop = this._keys[index];
  25894. if (this[prop] !== other[prop]) {
  25895. return false;
  25896. }
  25897. }
  25898. return true;
  25899. };
  25900. MaterialDefines.prototype.cloneTo = function (other) {
  25901. if (this._keys.length !== other._keys.length) {
  25902. other._keys = this._keys.slice(0);
  25903. }
  25904. for (var index = 0; index < this._keys.length; index++) {
  25905. var prop = this._keys[index];
  25906. other[prop] = this[prop];
  25907. }
  25908. };
  25909. MaterialDefines.prototype.reset = function () {
  25910. for (var index = 0; index < this._keys.length; index++) {
  25911. var prop = this._keys[index];
  25912. if (typeof (this[prop]) === "number") {
  25913. this[prop] = 0;
  25914. }
  25915. else {
  25916. this[prop] = false;
  25917. }
  25918. }
  25919. };
  25920. MaterialDefines.prototype.toString = function () {
  25921. var result = "";
  25922. for (var index = 0; index < this._keys.length; index++) {
  25923. var prop = this._keys[index];
  25924. if (typeof (this[prop]) === "number") {
  25925. result += "#define " + prop + " " + this[prop] + "\n";
  25926. }
  25927. else if (this[prop]) {
  25928. result += "#define " + prop + "\n";
  25929. }
  25930. }
  25931. return result;
  25932. };
  25933. return MaterialDefines;
  25934. }());
  25935. BABYLON.MaterialDefines = MaterialDefines;
  25936. var Material = (function () {
  25937. function Material(name, scene, doNotAdd) {
  25938. this.checkReadyOnEveryCall = false;
  25939. this.checkReadyOnlyOnce = false;
  25940. this.state = "";
  25941. this.alpha = 1.0;
  25942. this.backFaceCulling = true;
  25943. this.doNotSerialize = false;
  25944. /**
  25945. * An event triggered when the material is disposed.
  25946. * @type {BABYLON.Observable}
  25947. */
  25948. this.onDisposeObservable = new BABYLON.Observable();
  25949. /**
  25950. * An event triggered when the material is bound.
  25951. * @type {BABYLON.Observable}
  25952. */
  25953. this.onBindObservable = new BABYLON.Observable();
  25954. /**
  25955. * An event triggered when the material is unbound.
  25956. * @type {BABYLON.Observable}
  25957. */
  25958. this.onUnBindObservable = new BABYLON.Observable();
  25959. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25960. this.disableDepthWrite = false;
  25961. this.fogEnabled = true;
  25962. this.pointSize = 1.0;
  25963. this.zOffset = 0;
  25964. this._wasPreviouslyReady = false;
  25965. this._fillMode = Material.TriangleFillMode;
  25966. this.name = name;
  25967. this.id = name;
  25968. this._scene = scene;
  25969. if (scene.useRightHandedSystem) {
  25970. this.sideOrientation = Material.ClockWiseSideOrientation;
  25971. }
  25972. else {
  25973. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25974. }
  25975. if (!doNotAdd) {
  25976. scene.materials.push(this);
  25977. }
  25978. }
  25979. Object.defineProperty(Material, "TriangleFillMode", {
  25980. get: function () {
  25981. return Material._TriangleFillMode;
  25982. },
  25983. enumerable: true,
  25984. configurable: true
  25985. });
  25986. Object.defineProperty(Material, "WireFrameFillMode", {
  25987. get: function () {
  25988. return Material._WireFrameFillMode;
  25989. },
  25990. enumerable: true,
  25991. configurable: true
  25992. });
  25993. Object.defineProperty(Material, "PointFillMode", {
  25994. get: function () {
  25995. return Material._PointFillMode;
  25996. },
  25997. enumerable: true,
  25998. configurable: true
  25999. });
  26000. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26001. get: function () {
  26002. return Material._ClockWiseSideOrientation;
  26003. },
  26004. enumerable: true,
  26005. configurable: true
  26006. });
  26007. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26008. get: function () {
  26009. return Material._CounterClockWiseSideOrientation;
  26010. },
  26011. enumerable: true,
  26012. configurable: true
  26013. });
  26014. Object.defineProperty(Material.prototype, "onDispose", {
  26015. set: function (callback) {
  26016. if (this._onDisposeObserver) {
  26017. this.onDisposeObservable.remove(this._onDisposeObserver);
  26018. }
  26019. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26020. },
  26021. enumerable: true,
  26022. configurable: true
  26023. });
  26024. Object.defineProperty(Material.prototype, "onBind", {
  26025. set: function (callback) {
  26026. if (this._onBindObserver) {
  26027. this.onBindObservable.remove(this._onBindObserver);
  26028. }
  26029. this._onBindObserver = this.onBindObservable.add(callback);
  26030. },
  26031. enumerable: true,
  26032. configurable: true
  26033. });
  26034. Object.defineProperty(Material.prototype, "wireframe", {
  26035. get: function () {
  26036. return this._fillMode === Material.WireFrameFillMode;
  26037. },
  26038. set: function (value) {
  26039. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26040. },
  26041. enumerable: true,
  26042. configurable: true
  26043. });
  26044. Object.defineProperty(Material.prototype, "pointsCloud", {
  26045. get: function () {
  26046. return this._fillMode === Material.PointFillMode;
  26047. },
  26048. set: function (value) {
  26049. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26050. },
  26051. enumerable: true,
  26052. configurable: true
  26053. });
  26054. Object.defineProperty(Material.prototype, "fillMode", {
  26055. get: function () {
  26056. return this._fillMode;
  26057. },
  26058. set: function (value) {
  26059. this._fillMode = value;
  26060. },
  26061. enumerable: true,
  26062. configurable: true
  26063. });
  26064. /**
  26065. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26066. * subclasses should override adding information pertainent to themselves
  26067. */
  26068. Material.prototype.toString = function (fullDetails) {
  26069. var ret = "Name: " + this.name;
  26070. if (fullDetails) {
  26071. }
  26072. return ret;
  26073. };
  26074. Material.prototype.getClassName = function () {
  26075. return "Material";
  26076. };
  26077. Object.defineProperty(Material.prototype, "isFrozen", {
  26078. get: function () {
  26079. return this.checkReadyOnlyOnce;
  26080. },
  26081. enumerable: true,
  26082. configurable: true
  26083. });
  26084. Material.prototype.freeze = function () {
  26085. this.checkReadyOnlyOnce = true;
  26086. };
  26087. Material.prototype.unfreeze = function () {
  26088. this.checkReadyOnlyOnce = false;
  26089. };
  26090. Material.prototype.isReady = function (mesh, useInstances) {
  26091. return true;
  26092. };
  26093. Material.prototype.getEffect = function () {
  26094. return this._effect;
  26095. };
  26096. Material.prototype.getScene = function () {
  26097. return this._scene;
  26098. };
  26099. Material.prototype.needAlphaBlending = function () {
  26100. return (this.alpha < 1.0);
  26101. };
  26102. Material.prototype.needAlphaTesting = function () {
  26103. return false;
  26104. };
  26105. Material.prototype.getAlphaTestTexture = function () {
  26106. return null;
  26107. };
  26108. Material.prototype.markDirty = function () {
  26109. this._wasPreviouslyReady = false;
  26110. };
  26111. Material.prototype._preBind = function () {
  26112. var engine = this._scene.getEngine();
  26113. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26114. engine.enableEffect(this._effect);
  26115. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26116. };
  26117. Material.prototype.bind = function (world, mesh) {
  26118. this._scene._cachedMaterial = this;
  26119. this.onBindObservable.notifyObservers(mesh);
  26120. if (this.disableDepthWrite) {
  26121. var engine = this._scene.getEngine();
  26122. this._cachedDepthWriteState = engine.getDepthWrite();
  26123. engine.setDepthWrite(false);
  26124. }
  26125. };
  26126. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26127. };
  26128. Material.prototype.unbind = function () {
  26129. this.onUnBindObservable.notifyObservers(this);
  26130. if (this.disableDepthWrite) {
  26131. var engine = this._scene.getEngine();
  26132. engine.setDepthWrite(this._cachedDepthWriteState);
  26133. }
  26134. };
  26135. Material.prototype.clone = function (name) {
  26136. return null;
  26137. };
  26138. Material.prototype.getBindedMeshes = function () {
  26139. var result = new Array();
  26140. for (var index = 0; index < this._scene.meshes.length; index++) {
  26141. var mesh = this._scene.meshes[index];
  26142. if (mesh.material === this) {
  26143. result.push(mesh);
  26144. }
  26145. }
  26146. return result;
  26147. };
  26148. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26149. // Animations
  26150. this.getScene().stopAnimation(this);
  26151. // Remove from scene
  26152. var index = this._scene.materials.indexOf(this);
  26153. if (index >= 0) {
  26154. this._scene.materials.splice(index, 1);
  26155. }
  26156. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26157. if (forceDisposeEffect && this._effect) {
  26158. this._scene.getEngine()._releaseEffect(this._effect);
  26159. this._effect = null;
  26160. }
  26161. // Remove from meshes
  26162. for (index = 0; index < this._scene.meshes.length; index++) {
  26163. var mesh = this._scene.meshes[index];
  26164. if (mesh.material === this) {
  26165. mesh.material = null;
  26166. }
  26167. }
  26168. // Callback
  26169. this.onDisposeObservable.notifyObservers(this);
  26170. this.onDisposeObservable.clear();
  26171. this.onBindObservable.clear();
  26172. this.onUnBindObservable.clear();
  26173. };
  26174. Material.prototype.serialize = function () {
  26175. return BABYLON.SerializationHelper.Serialize(this);
  26176. };
  26177. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26178. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26179. multiMaterial.id = parsedMultiMaterial.id;
  26180. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26181. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26182. var subMatId = parsedMultiMaterial.materials[matIndex];
  26183. if (subMatId) {
  26184. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26185. }
  26186. else {
  26187. multiMaterial.subMaterials.push(null);
  26188. }
  26189. }
  26190. return multiMaterial;
  26191. };
  26192. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26193. if (!parsedMaterial.customType) {
  26194. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26195. }
  26196. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26197. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26198. ;
  26199. };
  26200. Material._TriangleFillMode = 0;
  26201. Material._WireFrameFillMode = 1;
  26202. Material._PointFillMode = 2;
  26203. Material._ClockWiseSideOrientation = 0;
  26204. Material._CounterClockWiseSideOrientation = 1;
  26205. __decorate([
  26206. BABYLON.serialize()
  26207. ], Material.prototype, "id", void 0);
  26208. __decorate([
  26209. BABYLON.serialize()
  26210. ], Material.prototype, "name", void 0);
  26211. __decorate([
  26212. BABYLON.serialize()
  26213. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26214. __decorate([
  26215. BABYLON.serialize()
  26216. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26217. __decorate([
  26218. BABYLON.serialize()
  26219. ], Material.prototype, "state", void 0);
  26220. __decorate([
  26221. BABYLON.serialize()
  26222. ], Material.prototype, "alpha", void 0);
  26223. __decorate([
  26224. BABYLON.serialize()
  26225. ], Material.prototype, "backFaceCulling", void 0);
  26226. __decorate([
  26227. BABYLON.serialize()
  26228. ], Material.prototype, "sideOrientation", void 0);
  26229. __decorate([
  26230. BABYLON.serialize()
  26231. ], Material.prototype, "alphaMode", void 0);
  26232. __decorate([
  26233. BABYLON.serialize()
  26234. ], Material.prototype, "disableDepthWrite", void 0);
  26235. __decorate([
  26236. BABYLON.serialize()
  26237. ], Material.prototype, "fogEnabled", void 0);
  26238. __decorate([
  26239. BABYLON.serialize()
  26240. ], Material.prototype, "pointSize", void 0);
  26241. __decorate([
  26242. BABYLON.serialize()
  26243. ], Material.prototype, "zOffset", void 0);
  26244. __decorate([
  26245. BABYLON.serialize()
  26246. ], Material.prototype, "wireframe", null);
  26247. __decorate([
  26248. BABYLON.serialize()
  26249. ], Material.prototype, "pointsCloud", null);
  26250. __decorate([
  26251. BABYLON.serialize()
  26252. ], Material.prototype, "fillMode", null);
  26253. return Material;
  26254. }());
  26255. BABYLON.Material = Material;
  26256. })(BABYLON || (BABYLON = {}));
  26257. //# sourceMappingURL=babylon.material.js.map
  26258. var BABYLON;
  26259. (function (BABYLON) {
  26260. var StandardMaterialDefines = (function (_super) {
  26261. __extends(StandardMaterialDefines, _super);
  26262. function StandardMaterialDefines() {
  26263. _super.call(this);
  26264. this.DIFFUSE = false;
  26265. this.AMBIENT = false;
  26266. this.OPACITY = false;
  26267. this.OPACITYRGB = false;
  26268. this.REFLECTION = false;
  26269. this.EMISSIVE = false;
  26270. this.SPECULAR = false;
  26271. this.BUMP = false;
  26272. this.PARALLAX = false;
  26273. this.PARALLAXOCCLUSION = false;
  26274. this.SPECULAROVERALPHA = false;
  26275. this.CLIPPLANE = false;
  26276. this.ALPHATEST = false;
  26277. this.ALPHAFROMDIFFUSE = false;
  26278. this.POINTSIZE = false;
  26279. this.FOG = false;
  26280. this.SPECULARTERM = false;
  26281. this.DIFFUSEFRESNEL = false;
  26282. this.OPACITYFRESNEL = false;
  26283. this.REFLECTIONFRESNEL = false;
  26284. this.REFRACTIONFRESNEL = false;
  26285. this.EMISSIVEFRESNEL = false;
  26286. this.FRESNEL = false;
  26287. this.NORMAL = false;
  26288. this.UV1 = false;
  26289. this.UV2 = false;
  26290. this.VERTEXCOLOR = false;
  26291. this.VERTEXALPHA = false;
  26292. this.NUM_BONE_INFLUENCERS = 0;
  26293. this.BonesPerMesh = 0;
  26294. this.INSTANCES = false;
  26295. this.GLOSSINESS = false;
  26296. this.ROUGHNESS = false;
  26297. this.EMISSIVEASILLUMINATION = false;
  26298. this.LINKEMISSIVEWITHDIFFUSE = false;
  26299. this.REFLECTIONFRESNELFROMSPECULAR = false;
  26300. this.LIGHTMAP = false;
  26301. this.USELIGHTMAPASSHADOWMAP = false;
  26302. this.REFLECTIONMAP_3D = false;
  26303. this.REFLECTIONMAP_SPHERICAL = false;
  26304. this.REFLECTIONMAP_PLANAR = false;
  26305. this.REFLECTIONMAP_CUBIC = false;
  26306. this.REFLECTIONMAP_PROJECTION = false;
  26307. this.REFLECTIONMAP_SKYBOX = false;
  26308. this.REFLECTIONMAP_EXPLICIT = false;
  26309. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26310. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26311. this.INVERTCUBICMAP = false;
  26312. this.LOGARITHMICDEPTH = false;
  26313. this.REFRACTION = false;
  26314. this.REFRACTIONMAP_3D = false;
  26315. this.REFLECTIONOVERALPHA = false;
  26316. this.INVERTNORMALMAPX = false;
  26317. this.INVERTNORMALMAPY = false;
  26318. this.SHADOWFULLFLOAT = false;
  26319. this.CAMERACOLORGRADING = false;
  26320. this.CAMERACOLORCURVES = false;
  26321. this.rebuild();
  26322. }
  26323. return StandardMaterialDefines;
  26324. }(BABYLON.MaterialDefines));
  26325. var StandardMaterial = (function (_super) {
  26326. __extends(StandardMaterial, _super);
  26327. function StandardMaterial(name, scene) {
  26328. var _this = this;
  26329. _super.call(this, name, scene);
  26330. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26331. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26332. this.specularColor = new BABYLON.Color3(1, 1, 1);
  26333. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26334. this.specularPower = 64;
  26335. this.useAlphaFromDiffuseTexture = false;
  26336. this.useEmissiveAsIllumination = false;
  26337. this.linkEmissiveWithDiffuse = false;
  26338. this.useReflectionFresnelFromSpecular = false;
  26339. this.useSpecularOverAlpha = false;
  26340. this.useReflectionOverAlpha = false;
  26341. this.disableLighting = false;
  26342. this.useParallax = false;
  26343. this.useParallaxOcclusion = false;
  26344. this.parallaxScaleBias = 0.05;
  26345. this.roughness = 0;
  26346. this.indexOfRefraction = 0.98;
  26347. this.invertRefractionY = true;
  26348. this.useLightmapAsShadowmap = false;
  26349. this.useGlossinessFromSpecularMapAlpha = false;
  26350. this.maxSimultaneousLights = 4;
  26351. /**
  26352. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26353. */
  26354. this.invertNormalMapX = false;
  26355. /**
  26356. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26357. */
  26358. this.invertNormalMapY = false;
  26359. /**
  26360. * Color Grading 2D Lookup Texture.
  26361. * This allows special effects like sepia, black and white to sixties rendering style.
  26362. */
  26363. this.cameraColorGradingTexture = null;
  26364. /**
  26365. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26366. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26367. * 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;
  26368. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26369. */
  26370. this.cameraColorCurves = null;
  26371. this._renderTargets = new BABYLON.SmartArray(16);
  26372. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26373. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26374. this._defines = new StandardMaterialDefines();
  26375. this._cachedDefines = new StandardMaterialDefines();
  26376. this._cachedDefines.BonesPerMesh = -1;
  26377. this.getRenderTargetTextures = function () {
  26378. _this._renderTargets.reset();
  26379. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26380. _this._renderTargets.push(_this.reflectionTexture);
  26381. }
  26382. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26383. _this._renderTargets.push(_this.refractionTexture);
  26384. }
  26385. return _this._renderTargets;
  26386. };
  26387. }
  26388. StandardMaterial.prototype.getClassName = function () {
  26389. return "StandardMaterial";
  26390. };
  26391. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26392. get: function () {
  26393. return this._useLogarithmicDepth;
  26394. },
  26395. set: function (value) {
  26396. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26397. },
  26398. enumerable: true,
  26399. configurable: true
  26400. });
  26401. StandardMaterial.prototype.needAlphaBlending = function () {
  26402. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26403. };
  26404. StandardMaterial.prototype.needAlphaTesting = function () {
  26405. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26406. };
  26407. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26408. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26409. };
  26410. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26411. return this.diffuseTexture;
  26412. };
  26413. // Methods
  26414. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26415. if (!mesh) {
  26416. return true;
  26417. }
  26418. if (this._defines.INSTANCES !== useInstances) {
  26419. return false;
  26420. }
  26421. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26422. return true;
  26423. }
  26424. return false;
  26425. };
  26426. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26427. if (this.isFrozen) {
  26428. if (this._wasPreviouslyReady) {
  26429. return true;
  26430. }
  26431. }
  26432. var scene = this.getScene();
  26433. var engine = scene.getEngine();
  26434. var needUVs = false;
  26435. var needNormals = false;
  26436. this._defines.reset();
  26437. // Lights
  26438. if (scene.lightsEnabled && !this.disableLighting) {
  26439. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26440. }
  26441. if (!this.checkReadyOnEveryCall) {
  26442. if (this._renderId === scene.getRenderId()) {
  26443. if (this._checkCache(scene, mesh, useInstances)) {
  26444. return true;
  26445. }
  26446. }
  26447. }
  26448. // Textures
  26449. if (scene.texturesEnabled) {
  26450. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26451. if (!this.diffuseTexture.isReady()) {
  26452. return false;
  26453. }
  26454. else {
  26455. needUVs = true;
  26456. this._defines.DIFFUSE = true;
  26457. }
  26458. }
  26459. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26460. if (!this.ambientTexture.isReady()) {
  26461. return false;
  26462. }
  26463. else {
  26464. needUVs = true;
  26465. this._defines.AMBIENT = true;
  26466. }
  26467. }
  26468. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26469. if (!this.opacityTexture.isReady()) {
  26470. return false;
  26471. }
  26472. else {
  26473. needUVs = true;
  26474. this._defines.OPACITY = true;
  26475. if (this.opacityTexture.getAlphaFromRGB) {
  26476. this._defines.OPACITYRGB = true;
  26477. }
  26478. }
  26479. }
  26480. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26481. if (!this.reflectionTexture.isReady()) {
  26482. return false;
  26483. }
  26484. else {
  26485. needNormals = true;
  26486. this._defines.REFLECTION = true;
  26487. if (this.roughness > 0) {
  26488. this._defines.ROUGHNESS = true;
  26489. }
  26490. if (this.useReflectionOverAlpha) {
  26491. this._defines.REFLECTIONOVERALPHA = true;
  26492. }
  26493. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26494. this._defines.INVERTCUBICMAP = true;
  26495. }
  26496. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26497. switch (this.reflectionTexture.coordinatesMode) {
  26498. case BABYLON.Texture.CUBIC_MODE:
  26499. case BABYLON.Texture.INVCUBIC_MODE:
  26500. this._defines.REFLECTIONMAP_CUBIC = true;
  26501. break;
  26502. case BABYLON.Texture.EXPLICIT_MODE:
  26503. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26504. break;
  26505. case BABYLON.Texture.PLANAR_MODE:
  26506. this._defines.REFLECTIONMAP_PLANAR = true;
  26507. break;
  26508. case BABYLON.Texture.PROJECTION_MODE:
  26509. this._defines.REFLECTIONMAP_PROJECTION = true;
  26510. break;
  26511. case BABYLON.Texture.SKYBOX_MODE:
  26512. this._defines.REFLECTIONMAP_SKYBOX = true;
  26513. break;
  26514. case BABYLON.Texture.SPHERICAL_MODE:
  26515. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26516. break;
  26517. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26518. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26519. break;
  26520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26521. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26522. break;
  26523. }
  26524. }
  26525. }
  26526. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26527. if (!this.emissiveTexture.isReady()) {
  26528. return false;
  26529. }
  26530. else {
  26531. needUVs = true;
  26532. this._defines.EMISSIVE = true;
  26533. }
  26534. }
  26535. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26536. if (!this.lightmapTexture.isReady()) {
  26537. return false;
  26538. }
  26539. else {
  26540. needUVs = true;
  26541. this._defines.LIGHTMAP = true;
  26542. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26543. }
  26544. }
  26545. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26546. if (!this.specularTexture.isReady()) {
  26547. return false;
  26548. }
  26549. else {
  26550. needUVs = true;
  26551. this._defines.SPECULAR = true;
  26552. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26553. }
  26554. }
  26555. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26556. if (!this.bumpTexture.isReady()) {
  26557. return false;
  26558. }
  26559. else {
  26560. needUVs = true;
  26561. this._defines.BUMP = true;
  26562. if (this.useParallax) {
  26563. this._defines.PARALLAX = true;
  26564. if (this.useParallaxOcclusion) {
  26565. this._defines.PARALLAXOCCLUSION = true;
  26566. }
  26567. }
  26568. if (this.invertNormalMapX) {
  26569. this._defines.INVERTNORMALMAPX = true;
  26570. }
  26571. if (this.invertNormalMapY) {
  26572. this._defines.INVERTNORMALMAPY = true;
  26573. }
  26574. }
  26575. }
  26576. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26577. if (!this.refractionTexture.isReady()) {
  26578. return false;
  26579. }
  26580. else {
  26581. needUVs = true;
  26582. this._defines.REFRACTION = true;
  26583. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26584. }
  26585. }
  26586. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26587. if (!this.cameraColorGradingTexture.isReady()) {
  26588. return false;
  26589. }
  26590. else {
  26591. this._defines.CAMERACOLORGRADING = true;
  26592. }
  26593. }
  26594. }
  26595. // Effect
  26596. if (scene.clipPlane) {
  26597. this._defines.CLIPPLANE = true;
  26598. }
  26599. if (engine.getAlphaTesting()) {
  26600. this._defines.ALPHATEST = true;
  26601. }
  26602. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26603. this._defines.ALPHAFROMDIFFUSE = true;
  26604. }
  26605. if (this.useEmissiveAsIllumination) {
  26606. this._defines.EMISSIVEASILLUMINATION = true;
  26607. }
  26608. if (this.linkEmissiveWithDiffuse) {
  26609. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26610. }
  26611. if (this.useLogarithmicDepth) {
  26612. this._defines.LOGARITHMICDEPTH = true;
  26613. }
  26614. if (this.cameraColorCurves) {
  26615. this._defines.CAMERACOLORCURVES = true;
  26616. }
  26617. // Point size
  26618. if (this.pointsCloud || scene.forcePointsCloud) {
  26619. this._defines.POINTSIZE = true;
  26620. }
  26621. // Fog
  26622. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26623. this._defines.FOG = true;
  26624. }
  26625. if (StandardMaterial.FresnelEnabled) {
  26626. // Fresnel
  26627. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26628. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26629. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26630. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26631. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26632. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26633. this._defines.DIFFUSEFRESNEL = true;
  26634. }
  26635. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26636. this._defines.OPACITYFRESNEL = true;
  26637. }
  26638. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26639. this._defines.REFLECTIONFRESNEL = true;
  26640. if (this.useReflectionFresnelFromSpecular) {
  26641. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26642. }
  26643. }
  26644. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26645. this._defines.REFRACTIONFRESNEL = true;
  26646. }
  26647. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26648. this._defines.EMISSIVEFRESNEL = true;
  26649. }
  26650. needNormals = true;
  26651. this._defines.FRESNEL = true;
  26652. }
  26653. }
  26654. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26655. this._defines.SPECULAROVERALPHA = true;
  26656. }
  26657. // Attribs
  26658. if (mesh) {
  26659. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26660. this._defines.NORMAL = true;
  26661. }
  26662. if (needUVs) {
  26663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26664. this._defines.UV1 = true;
  26665. }
  26666. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26667. this._defines.UV2 = true;
  26668. }
  26669. }
  26670. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26671. this._defines.VERTEXCOLOR = true;
  26672. if (mesh.hasVertexAlpha) {
  26673. this._defines.VERTEXALPHA = true;
  26674. }
  26675. }
  26676. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26677. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26678. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26679. }
  26680. // Instances
  26681. if (useInstances) {
  26682. this._defines.INSTANCES = true;
  26683. }
  26684. }
  26685. // Get correct effect
  26686. if (!this._defines.isEqual(this._cachedDefines)) {
  26687. this._defines.cloneTo(this._cachedDefines);
  26688. scene.resetCachedMaterial();
  26689. // Fallbacks
  26690. var fallbacks = new BABYLON.EffectFallbacks();
  26691. if (this._defines.REFLECTION) {
  26692. fallbacks.addFallback(0, "REFLECTION");
  26693. }
  26694. if (this._defines.SPECULAR) {
  26695. fallbacks.addFallback(0, "SPECULAR");
  26696. }
  26697. if (this._defines.BUMP) {
  26698. fallbacks.addFallback(0, "BUMP");
  26699. }
  26700. if (this._defines.PARALLAX) {
  26701. fallbacks.addFallback(1, "PARALLAX");
  26702. }
  26703. if (this._defines.PARALLAXOCCLUSION) {
  26704. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26705. }
  26706. if (this._defines.SPECULAROVERALPHA) {
  26707. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26708. }
  26709. if (this._defines.FOG) {
  26710. fallbacks.addFallback(1, "FOG");
  26711. }
  26712. if (this._defines.POINTSIZE) {
  26713. fallbacks.addFallback(0, "POINTSIZE");
  26714. }
  26715. if (this._defines.LOGARITHMICDEPTH) {
  26716. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26717. }
  26718. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26719. if (this._defines.SPECULARTERM) {
  26720. fallbacks.addFallback(0, "SPECULARTERM");
  26721. }
  26722. if (this._defines.DIFFUSEFRESNEL) {
  26723. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26724. }
  26725. if (this._defines.OPACITYFRESNEL) {
  26726. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26727. }
  26728. if (this._defines.REFLECTIONFRESNEL) {
  26729. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26730. }
  26731. if (this._defines.EMISSIVEFRESNEL) {
  26732. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26733. }
  26734. if (this._defines.FRESNEL) {
  26735. fallbacks.addFallback(4, "FRESNEL");
  26736. }
  26737. //Attributes
  26738. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26739. if (this._defines.NORMAL) {
  26740. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26741. }
  26742. if (this._defines.UV1) {
  26743. attribs.push(BABYLON.VertexBuffer.UVKind);
  26744. }
  26745. if (this._defines.UV2) {
  26746. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26747. }
  26748. if (this._defines.VERTEXCOLOR) {
  26749. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26750. }
  26751. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26752. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26753. var shaderName = "default";
  26754. var join = this._defines.toString();
  26755. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26756. "vFogInfos", "vFogColor", "pointSize",
  26757. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26758. "mBones",
  26759. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26760. "depthValues",
  26761. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26762. "logarithmicDepthConstant"
  26763. ];
  26764. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26765. if (this._defines.CAMERACOLORCURVES) {
  26766. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26767. }
  26768. if (this._defines.CAMERACOLORGRADING) {
  26769. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26770. }
  26771. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26772. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26773. }
  26774. if (!this._effect.isReady()) {
  26775. return false;
  26776. }
  26777. this._renderId = scene.getRenderId();
  26778. this._wasPreviouslyReady = true;
  26779. if (mesh) {
  26780. if (!mesh._materialDefines) {
  26781. mesh._materialDefines = new StandardMaterialDefines();
  26782. }
  26783. this._defines.cloneTo(mesh._materialDefines);
  26784. }
  26785. return true;
  26786. };
  26787. StandardMaterial.prototype.unbind = function () {
  26788. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26789. this._effect.setTexture("reflection2DSampler", null);
  26790. }
  26791. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26792. this._effect.setTexture("refraction2DSampler", null);
  26793. }
  26794. _super.prototype.unbind.call(this);
  26795. };
  26796. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26797. this._effect.setMatrix("world", world);
  26798. };
  26799. StandardMaterial.prototype.bind = function (world, mesh) {
  26800. var scene = this.getScene();
  26801. // Matrices
  26802. this.bindOnlyWorldMatrix(world);
  26803. // Bones
  26804. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26805. if (scene.getCachedMaterial() !== this) {
  26806. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26807. if (StandardMaterial.FresnelEnabled) {
  26808. // Fresnel
  26809. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26810. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26811. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26812. }
  26813. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26814. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26815. }
  26816. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26817. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26818. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26819. }
  26820. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26821. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26822. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26823. }
  26824. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26825. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26826. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26827. }
  26828. }
  26829. // Textures
  26830. if (scene.texturesEnabled) {
  26831. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26832. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26833. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26834. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26835. }
  26836. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26837. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26838. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26839. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26840. }
  26841. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26842. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26843. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26844. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26845. }
  26846. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26847. if (this.reflectionTexture.isCube) {
  26848. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26849. }
  26850. else {
  26851. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26852. }
  26853. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26854. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26855. }
  26856. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26857. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26858. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26859. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26860. }
  26861. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26862. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26863. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26864. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26865. }
  26866. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26867. this._effect.setTexture("specularSampler", this.specularTexture);
  26868. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26869. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26870. }
  26871. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26872. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26873. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26874. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26875. }
  26876. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26877. var depth = 1.0;
  26878. if (this.refractionTexture.isCube) {
  26879. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26880. }
  26881. else {
  26882. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26883. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26884. if (this.refractionTexture.depth) {
  26885. depth = this.refractionTexture.depth;
  26886. }
  26887. }
  26888. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26889. }
  26890. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26891. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26892. }
  26893. }
  26894. // Clip plane
  26895. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26896. // Point size
  26897. if (this.pointsCloud) {
  26898. this._effect.setFloat("pointSize", this.pointSize);
  26899. }
  26900. // Colors
  26901. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26902. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26903. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26904. if (this._defines.SPECULARTERM) {
  26905. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26906. }
  26907. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26908. }
  26909. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26910. // Diffuse
  26911. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26912. // Lights
  26913. if (scene.lightsEnabled && !this.disableLighting) {
  26914. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26915. }
  26916. // View
  26917. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26918. this._effect.setMatrix("view", scene.getViewMatrix());
  26919. }
  26920. // Fog
  26921. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26922. // Log. depth
  26923. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26924. // Color Curves
  26925. if (this.cameraColorCurves) {
  26926. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26927. }
  26928. }
  26929. _super.prototype.bind.call(this, world, mesh);
  26930. };
  26931. StandardMaterial.prototype.getAnimatables = function () {
  26932. var results = [];
  26933. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26934. results.push(this.diffuseTexture);
  26935. }
  26936. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26937. results.push(this.ambientTexture);
  26938. }
  26939. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26940. results.push(this.opacityTexture);
  26941. }
  26942. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26943. results.push(this.reflectionTexture);
  26944. }
  26945. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26946. results.push(this.emissiveTexture);
  26947. }
  26948. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26949. results.push(this.specularTexture);
  26950. }
  26951. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26952. results.push(this.bumpTexture);
  26953. }
  26954. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26955. results.push(this.lightmapTexture);
  26956. }
  26957. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26958. results.push(this.refractionTexture);
  26959. }
  26960. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26961. results.push(this.cameraColorGradingTexture);
  26962. }
  26963. return results;
  26964. };
  26965. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26966. if (forceDisposeTextures) {
  26967. if (this.diffuseTexture) {
  26968. this.diffuseTexture.dispose();
  26969. }
  26970. if (this.ambientTexture) {
  26971. this.ambientTexture.dispose();
  26972. }
  26973. if (this.opacityTexture) {
  26974. this.opacityTexture.dispose();
  26975. }
  26976. if (this.reflectionTexture) {
  26977. this.reflectionTexture.dispose();
  26978. }
  26979. if (this.emissiveTexture) {
  26980. this.emissiveTexture.dispose();
  26981. }
  26982. if (this.specularTexture) {
  26983. this.specularTexture.dispose();
  26984. }
  26985. if (this.bumpTexture) {
  26986. this.bumpTexture.dispose();
  26987. }
  26988. if (this.lightmapTexture) {
  26989. this.lightmapTexture.dispose();
  26990. }
  26991. if (this.refractionTexture) {
  26992. this.refractionTexture.dispose();
  26993. }
  26994. if (this.cameraColorGradingTexture) {
  26995. this.cameraColorGradingTexture.dispose();
  26996. }
  26997. }
  26998. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26999. };
  27000. StandardMaterial.prototype.clone = function (name) {
  27001. var _this = this;
  27002. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27003. };
  27004. StandardMaterial.prototype.serialize = function () {
  27005. return BABYLON.SerializationHelper.Serialize(this);
  27006. };
  27007. // Statics
  27008. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27009. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27010. };
  27011. // Flags used to enable or disable a type of texture for all Standard Materials
  27012. StandardMaterial.DiffuseTextureEnabled = true;
  27013. StandardMaterial.AmbientTextureEnabled = true;
  27014. StandardMaterial.OpacityTextureEnabled = true;
  27015. StandardMaterial.ReflectionTextureEnabled = true;
  27016. StandardMaterial.EmissiveTextureEnabled = true;
  27017. StandardMaterial.SpecularTextureEnabled = true;
  27018. StandardMaterial.BumpTextureEnabled = true;
  27019. StandardMaterial.FresnelEnabled = true;
  27020. StandardMaterial.LightmapTextureEnabled = true;
  27021. StandardMaterial.RefractionTextureEnabled = true;
  27022. StandardMaterial.ColorGradingTextureEnabled = true;
  27023. __decorate([
  27024. BABYLON.serializeAsTexture()
  27025. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27026. __decorate([
  27027. BABYLON.serializeAsTexture()
  27028. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27029. __decorate([
  27030. BABYLON.serializeAsTexture()
  27031. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27032. __decorate([
  27033. BABYLON.serializeAsTexture()
  27034. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27035. __decorate([
  27036. BABYLON.serializeAsTexture()
  27037. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27038. __decorate([
  27039. BABYLON.serializeAsTexture()
  27040. ], StandardMaterial.prototype, "specularTexture", void 0);
  27041. __decorate([
  27042. BABYLON.serializeAsTexture()
  27043. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27044. __decorate([
  27045. BABYLON.serializeAsTexture()
  27046. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27047. __decorate([
  27048. BABYLON.serializeAsTexture()
  27049. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27050. __decorate([
  27051. BABYLON.serializeAsColor3("ambient")
  27052. ], StandardMaterial.prototype, "ambientColor", void 0);
  27053. __decorate([
  27054. BABYLON.serializeAsColor3("diffuse")
  27055. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27056. __decorate([
  27057. BABYLON.serializeAsColor3("specular")
  27058. ], StandardMaterial.prototype, "specularColor", void 0);
  27059. __decorate([
  27060. BABYLON.serializeAsColor3("emissive")
  27061. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27062. __decorate([
  27063. BABYLON.serialize()
  27064. ], StandardMaterial.prototype, "specularPower", void 0);
  27065. __decorate([
  27066. BABYLON.serialize()
  27067. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27068. __decorate([
  27069. BABYLON.serialize()
  27070. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27071. __decorate([
  27072. BABYLON.serialize()
  27073. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27074. __decorate([
  27075. BABYLON.serialize()
  27076. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27077. __decorate([
  27078. BABYLON.serialize()
  27079. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27080. __decorate([
  27081. BABYLON.serialize()
  27082. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27083. __decorate([
  27084. BABYLON.serialize()
  27085. ], StandardMaterial.prototype, "disableLighting", void 0);
  27086. __decorate([
  27087. BABYLON.serialize()
  27088. ], StandardMaterial.prototype, "useParallax", void 0);
  27089. __decorate([
  27090. BABYLON.serialize()
  27091. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27092. __decorate([
  27093. BABYLON.serialize()
  27094. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27095. __decorate([
  27096. BABYLON.serialize()
  27097. ], StandardMaterial.prototype, "roughness", void 0);
  27098. __decorate([
  27099. BABYLON.serialize()
  27100. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27101. __decorate([
  27102. BABYLON.serialize()
  27103. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27104. __decorate([
  27105. BABYLON.serialize()
  27106. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27107. __decorate([
  27108. BABYLON.serializeAsFresnelParameters()
  27109. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27110. __decorate([
  27111. BABYLON.serializeAsFresnelParameters()
  27112. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27113. __decorate([
  27114. BABYLON.serializeAsFresnelParameters()
  27115. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27116. __decorate([
  27117. BABYLON.serializeAsFresnelParameters()
  27118. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27119. __decorate([
  27120. BABYLON.serializeAsFresnelParameters()
  27121. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27122. __decorate([
  27123. BABYLON.serialize()
  27124. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27125. __decorate([
  27126. BABYLON.serialize()
  27127. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27128. __decorate([
  27129. BABYLON.serialize()
  27130. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27131. __decorate([
  27132. BABYLON.serialize()
  27133. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27134. __decorate([
  27135. BABYLON.serializeAsTexture()
  27136. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27137. __decorate([
  27138. BABYLON.serializeAsColorCurves()
  27139. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27140. __decorate([
  27141. BABYLON.serialize()
  27142. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27143. return StandardMaterial;
  27144. }(BABYLON.Material));
  27145. BABYLON.StandardMaterial = StandardMaterial;
  27146. })(BABYLON || (BABYLON = {}));
  27147. //# sourceMappingURL=babylon.standardMaterial.js.map
  27148. var BABYLON;
  27149. (function (BABYLON) {
  27150. var MultiMaterial = (function (_super) {
  27151. __extends(MultiMaterial, _super);
  27152. function MultiMaterial(name, scene) {
  27153. _super.call(this, name, scene, true);
  27154. this.subMaterials = new Array();
  27155. scene.multiMaterials.push(this);
  27156. }
  27157. // Properties
  27158. MultiMaterial.prototype.getSubMaterial = function (index) {
  27159. if (index < 0 || index >= this.subMaterials.length) {
  27160. return this.getScene().defaultMaterial;
  27161. }
  27162. return this.subMaterials[index];
  27163. };
  27164. // Methods
  27165. MultiMaterial.prototype.getClassName = function () {
  27166. return "MultiMaterial";
  27167. };
  27168. MultiMaterial.prototype.isReady = function (mesh) {
  27169. for (var index = 0; index < this.subMaterials.length; index++) {
  27170. var subMaterial = this.subMaterials[index];
  27171. if (subMaterial) {
  27172. if (!this.subMaterials[index].isReady(mesh)) {
  27173. return false;
  27174. }
  27175. }
  27176. }
  27177. return true;
  27178. };
  27179. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27180. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27181. for (var index = 0; index < this.subMaterials.length; index++) {
  27182. var subMaterial = null;
  27183. if (cloneChildren) {
  27184. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27185. }
  27186. else {
  27187. subMaterial = this.subMaterials[index];
  27188. }
  27189. newMultiMaterial.subMaterials.push(subMaterial);
  27190. }
  27191. return newMultiMaterial;
  27192. };
  27193. MultiMaterial.prototype.serialize = function () {
  27194. var serializationObject = {};
  27195. serializationObject.name = this.name;
  27196. serializationObject.id = this.id;
  27197. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27198. serializationObject.materials = [];
  27199. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27200. var subMat = this.subMaterials[matIndex];
  27201. if (subMat) {
  27202. serializationObject.materials.push(subMat.id);
  27203. }
  27204. else {
  27205. serializationObject.materials.push(null);
  27206. }
  27207. }
  27208. return serializationObject;
  27209. };
  27210. return MultiMaterial;
  27211. }(BABYLON.Material));
  27212. BABYLON.MultiMaterial = MultiMaterial;
  27213. })(BABYLON || (BABYLON = {}));
  27214. //# sourceMappingURL=babylon.multiMaterial.js.map
  27215. var BABYLON;
  27216. (function (BABYLON) {
  27217. var SceneLoader = (function () {
  27218. function SceneLoader() {
  27219. }
  27220. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27221. get: function () {
  27222. return 0;
  27223. },
  27224. enumerable: true,
  27225. configurable: true
  27226. });
  27227. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27228. get: function () {
  27229. return 1;
  27230. },
  27231. enumerable: true,
  27232. configurable: true
  27233. });
  27234. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27235. get: function () {
  27236. return 2;
  27237. },
  27238. enumerable: true,
  27239. configurable: true
  27240. });
  27241. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27242. get: function () {
  27243. return 3;
  27244. },
  27245. enumerable: true,
  27246. configurable: true
  27247. });
  27248. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27249. get: function () {
  27250. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27251. },
  27252. set: function (value) {
  27253. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27254. },
  27255. enumerable: true,
  27256. configurable: true
  27257. });
  27258. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27259. get: function () {
  27260. return SceneLoader._ShowLoadingScreen;
  27261. },
  27262. set: function (value) {
  27263. SceneLoader._ShowLoadingScreen = value;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(SceneLoader, "loggingLevel", {
  27269. get: function () {
  27270. return SceneLoader._loggingLevel;
  27271. },
  27272. set: function (value) {
  27273. SceneLoader._loggingLevel = value;
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. SceneLoader._getDefaultPlugin = function () {
  27279. return SceneLoader._registeredPlugins[".babylon"];
  27280. };
  27281. SceneLoader._getPluginForExtension = function (extension) {
  27282. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27283. if (registeredPlugin) {
  27284. return registeredPlugin;
  27285. }
  27286. return SceneLoader._getDefaultPlugin();
  27287. };
  27288. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27289. if (sceneFilename.name) {
  27290. sceneFilename = sceneFilename.name;
  27291. }
  27292. var dotPosition = sceneFilename.lastIndexOf(".");
  27293. var queryStringPosition = sceneFilename.indexOf("?");
  27294. if (queryStringPosition === -1) {
  27295. queryStringPosition = sceneFilename.length;
  27296. }
  27297. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27298. return SceneLoader._getPluginForExtension(extension);
  27299. };
  27300. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27301. SceneLoader._getDirectLoad = function (sceneFilename) {
  27302. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27303. return sceneFilename.substr(5);
  27304. }
  27305. return null;
  27306. };
  27307. // Public functions
  27308. SceneLoader.GetPluginForExtension = function (extension) {
  27309. return SceneLoader._getPluginForExtension(extension).plugin;
  27310. };
  27311. SceneLoader.RegisterPlugin = function (plugin) {
  27312. if (typeof plugin.extensions === "string") {
  27313. var extension = plugin.extensions;
  27314. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27315. plugin: plugin,
  27316. isBinary: false
  27317. };
  27318. }
  27319. else {
  27320. var extensions = plugin.extensions;
  27321. Object.keys(extensions).forEach(function (extension) {
  27322. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27323. plugin: plugin,
  27324. isBinary: extensions[extension].isBinary
  27325. };
  27326. });
  27327. }
  27328. };
  27329. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27330. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27331. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27332. return;
  27333. }
  27334. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27335. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27336. return;
  27337. }
  27338. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27339. var loadingToken = {};
  27340. scene._addPendingData(loadingToken);
  27341. var manifestChecked = function (success) {
  27342. scene.database = database;
  27343. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27344. var plugin = registeredPlugin.plugin;
  27345. var useArrayBuffer = registeredPlugin.isBinary;
  27346. var importMeshFromData = function (data) {
  27347. var meshes = [];
  27348. var particleSystems = [];
  27349. var skeletons = [];
  27350. try {
  27351. if (plugin.importMesh) {
  27352. var syncedPlugin = plugin;
  27353. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27354. if (onerror) {
  27355. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27356. }
  27357. scene._removePendingData(loadingToken);
  27358. return;
  27359. }
  27360. if (onsuccess) {
  27361. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27362. onsuccess(meshes, particleSystems, skeletons);
  27363. scene._removePendingData(loadingToken);
  27364. }
  27365. }
  27366. else {
  27367. var asyncedPlugin = plugin;
  27368. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27369. if (onsuccess) {
  27370. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27371. onsuccess(meshes, particleSystems, skeletons);
  27372. scene._removePendingData(loadingToken);
  27373. }
  27374. }, function () {
  27375. if (onerror) {
  27376. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27377. }
  27378. scene._removePendingData(loadingToken);
  27379. });
  27380. }
  27381. }
  27382. catch (e) {
  27383. if (onerror) {
  27384. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27385. }
  27386. scene._removePendingData(loadingToken);
  27387. }
  27388. };
  27389. if (directLoad) {
  27390. importMeshFromData(directLoad);
  27391. return;
  27392. }
  27393. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27394. importMeshFromData(data);
  27395. }, progressCallBack, database, useArrayBuffer);
  27396. };
  27397. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27398. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27399. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27400. }
  27401. else {
  27402. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27403. manifestChecked(true);
  27404. }
  27405. };
  27406. /**
  27407. * Load a scene
  27408. * @param rootUrl a string that defines the root url for scene and resources
  27409. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27410. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27411. */
  27412. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27413. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27414. };
  27415. /**
  27416. * Append a scene
  27417. * @param rootUrl a string that defines the root url for scene and resources
  27418. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27419. * @param scene is the instance of BABYLON.Scene to append to
  27420. */
  27421. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27422. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27423. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27424. return;
  27425. }
  27426. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27427. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27428. var plugin = registeredPlugin.plugin;
  27429. var useArrayBuffer = registeredPlugin.isBinary;
  27430. var database;
  27431. var loadingToken = {};
  27432. scene._addPendingData(loadingToken);
  27433. if (SceneLoader.ShowLoadingScreen) {
  27434. scene.getEngine().displayLoadingUI();
  27435. }
  27436. var loadSceneFromData = function (data) {
  27437. scene.database = database;
  27438. if (plugin.load) {
  27439. var syncedPlugin = plugin;
  27440. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27441. if (onerror) {
  27442. onerror(scene);
  27443. }
  27444. scene._removePendingData(loadingToken);
  27445. scene.getEngine().hideLoadingUI();
  27446. return;
  27447. }
  27448. if (onsuccess) {
  27449. onsuccess(scene);
  27450. }
  27451. scene._removePendingData(loadingToken);
  27452. }
  27453. else {
  27454. var asyncedPlugin = plugin;
  27455. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27456. if (onsuccess) {
  27457. onsuccess(scene);
  27458. }
  27459. scene._removePendingData(loadingToken);
  27460. }, function () {
  27461. if (onerror) {
  27462. onerror(scene);
  27463. }
  27464. scene._removePendingData(loadingToken);
  27465. scene.getEngine().hideLoadingUI();
  27466. });
  27467. }
  27468. if (SceneLoader.ShowLoadingScreen) {
  27469. scene.executeWhenReady(function () {
  27470. scene.getEngine().hideLoadingUI();
  27471. });
  27472. }
  27473. };
  27474. var manifestChecked = function (success) {
  27475. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27476. };
  27477. if (directLoad) {
  27478. loadSceneFromData(directLoad);
  27479. return;
  27480. }
  27481. if (rootUrl.indexOf("file:") === -1) {
  27482. if (scene.getEngine().enableOfflineSupport) {
  27483. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27484. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27485. }
  27486. else {
  27487. manifestChecked(true);
  27488. }
  27489. }
  27490. else {
  27491. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27492. }
  27493. };
  27494. // Flags
  27495. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27496. SceneLoader._ShowLoadingScreen = true;
  27497. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27498. // Members
  27499. SceneLoader._registeredPlugins = {};
  27500. return SceneLoader;
  27501. }());
  27502. BABYLON.SceneLoader = SceneLoader;
  27503. ;
  27504. })(BABYLON || (BABYLON = {}));
  27505. //# sourceMappingURL=babylon.sceneLoader.js.map
  27506. var BABYLON;
  27507. (function (BABYLON) {
  27508. var Internals;
  27509. (function (Internals) {
  27510. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27511. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27512. var parsedMaterial = parsedData.materials[index];
  27513. if (parsedMaterial.id === id) {
  27514. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27515. }
  27516. }
  27517. return null;
  27518. };
  27519. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27520. names = (names instanceof Array) ? names : [names];
  27521. for (var i in names) {
  27522. if (mesh.name === names[i]) {
  27523. hierarchyIds.push(mesh.id);
  27524. return true;
  27525. }
  27526. }
  27527. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27528. hierarchyIds.push(mesh.id);
  27529. return true;
  27530. }
  27531. return false;
  27532. };
  27533. var logOperation = function (operation, producer) {
  27534. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27535. };
  27536. BABYLON.SceneLoader.RegisterPlugin({
  27537. extensions: ".babylon",
  27538. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27539. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27540. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27541. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27542. // and avoid problems with multiple concurrent .babylon loads.
  27543. var log = "importMesh has failed JSON parse";
  27544. try {
  27545. var parsedData = JSON.parse(data);
  27546. log = "";
  27547. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27548. var loadedSkeletonsIds = [];
  27549. var loadedMaterialsIds = [];
  27550. var hierarchyIds = [];
  27551. var index;
  27552. var cache;
  27553. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27554. var parsedMesh = parsedData.meshes[index];
  27555. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27556. if (meshesNames instanceof Array) {
  27557. // Remove found mesh name from list.
  27558. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27559. }
  27560. //Geometry?
  27561. if (parsedMesh.geometryId) {
  27562. //does the file contain geometries?
  27563. if (parsedData.geometries) {
  27564. //find the correct geometry and add it to the scene
  27565. var found = false;
  27566. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27567. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27568. return;
  27569. }
  27570. else {
  27571. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27572. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27573. switch (geometryType) {
  27574. case "boxes":
  27575. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27576. break;
  27577. case "spheres":
  27578. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27579. break;
  27580. case "cylinders":
  27581. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27582. break;
  27583. case "toruses":
  27584. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27585. break;
  27586. case "grounds":
  27587. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27588. break;
  27589. case "planes":
  27590. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27591. break;
  27592. case "torusKnots":
  27593. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27594. break;
  27595. case "vertexData":
  27596. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27597. break;
  27598. }
  27599. found = true;
  27600. }
  27601. });
  27602. }
  27603. });
  27604. if (!found) {
  27605. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27606. }
  27607. }
  27608. }
  27609. // Material ?
  27610. if (parsedMesh.materialId) {
  27611. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27612. if (!materialFound && parsedData.multiMaterials) {
  27613. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27614. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27615. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27616. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27617. var subMatId = parsedMultiMaterial.materials[matIndex];
  27618. loadedMaterialsIds.push(subMatId);
  27619. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27620. log += "\n\tMaterial " + mat.toString(fullDetails);
  27621. }
  27622. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27623. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27624. materialFound = true;
  27625. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27626. break;
  27627. }
  27628. }
  27629. }
  27630. if (!materialFound) {
  27631. loadedMaterialsIds.push(parsedMesh.materialId);
  27632. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27633. if (!mat) {
  27634. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27635. }
  27636. else {
  27637. log += "\n\tMaterial " + mat.toString(fullDetails);
  27638. }
  27639. }
  27640. }
  27641. // Skeleton ?
  27642. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27643. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27644. if (!skeletonAlreadyLoaded) {
  27645. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27646. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27647. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27648. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27649. skeletons.push(skeleton);
  27650. loadedSkeletonsIds.push(parsedSkeleton.id);
  27651. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27652. }
  27653. }
  27654. }
  27655. }
  27656. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27657. meshes.push(mesh);
  27658. log += "\n\tMesh " + mesh.toString(fullDetails);
  27659. }
  27660. }
  27661. // Connecting parents
  27662. var currentMesh;
  27663. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27664. currentMesh = scene.meshes[index];
  27665. if (currentMesh._waitingParentId) {
  27666. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27667. currentMesh._waitingParentId = undefined;
  27668. }
  27669. }
  27670. // freeze and compute world matrix application
  27671. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27672. currentMesh = scene.meshes[index];
  27673. if (currentMesh._waitingFreezeWorldMatrix) {
  27674. currentMesh.freezeWorldMatrix();
  27675. currentMesh._waitingFreezeWorldMatrix = undefined;
  27676. }
  27677. else {
  27678. currentMesh.computeWorldMatrix(true);
  27679. }
  27680. }
  27681. // Particles
  27682. if (parsedData.particleSystems) {
  27683. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27684. var parsedParticleSystem = parsedData.particleSystems[index];
  27685. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27686. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27687. }
  27688. }
  27689. }
  27690. return true;
  27691. }
  27692. catch (err) {
  27693. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27694. log = null;
  27695. throw err;
  27696. }
  27697. finally {
  27698. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27699. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27700. }
  27701. }
  27702. },
  27703. load: function (scene, data, rootUrl) {
  27704. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27705. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27706. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27707. // and avoid problems with multiple concurrent .babylon loads.
  27708. var log = "importScene has failed JSON parse";
  27709. try {
  27710. var parsedData = JSON.parse(data);
  27711. log = "";
  27712. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27713. // Scene
  27714. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27715. scene.autoClear = parsedData.autoClear;
  27716. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27717. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27718. if (parsedData.gravity) {
  27719. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27720. }
  27721. // Fog
  27722. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27723. scene.fogMode = parsedData.fogMode;
  27724. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27725. scene.fogStart = parsedData.fogStart;
  27726. scene.fogEnd = parsedData.fogEnd;
  27727. scene.fogDensity = parsedData.fogDensity;
  27728. log += "\tFog mode for scene: ";
  27729. switch (scene.fogMode) {
  27730. // getters not compiling, so using hardcoded
  27731. case 1:
  27732. log += "exp\n";
  27733. break;
  27734. case 2:
  27735. log += "exp2\n";
  27736. break;
  27737. case 3:
  27738. log += "linear\n";
  27739. break;
  27740. }
  27741. }
  27742. //Physics
  27743. if (parsedData.physicsEnabled) {
  27744. var physicsPlugin;
  27745. if (parsedData.physicsEngine === "cannon") {
  27746. physicsPlugin = new BABYLON.CannonJSPlugin();
  27747. }
  27748. else if (parsedData.physicsEngine === "oimo") {
  27749. physicsPlugin = new BABYLON.OimoJSPlugin();
  27750. }
  27751. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27752. //else - default engine, which is currently oimo
  27753. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27754. scene.enablePhysics(physicsGravity, physicsPlugin);
  27755. }
  27756. // Metadata
  27757. if (parsedData.metadata !== undefined) {
  27758. scene.metadata = parsedData.metadata;
  27759. }
  27760. //collisions, if defined. otherwise, default is true
  27761. if (parsedData.collisionsEnabled != undefined) {
  27762. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27763. }
  27764. scene.workerCollisions = !!parsedData.workerCollisions;
  27765. var index;
  27766. var cache;
  27767. // Lights
  27768. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27769. var parsedLight = parsedData.lights[index];
  27770. var light = BABYLON.Light.Parse(parsedLight, scene);
  27771. log += (index === 0 ? "\n\tLights:" : "");
  27772. log += "\n\t\t" + light.toString(fullDetails);
  27773. }
  27774. // Animations
  27775. if (parsedData.animations) {
  27776. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27777. var parsedAnimation = parsedData.animations[index];
  27778. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27779. scene.animations.push(animation);
  27780. log += (index === 0 ? "\n\tAnimations:" : "");
  27781. log += "\n\t\t" + animation.toString(fullDetails);
  27782. }
  27783. }
  27784. if (parsedData.autoAnimate) {
  27785. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27786. }
  27787. // Materials
  27788. if (parsedData.materials) {
  27789. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27790. var parsedMaterial = parsedData.materials[index];
  27791. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27792. log += (index === 0 ? "\n\tMaterials:" : "");
  27793. log += "\n\t\t" + mat.toString(fullDetails);
  27794. }
  27795. }
  27796. if (parsedData.multiMaterials) {
  27797. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27798. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27799. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27800. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27801. log += "\n\t\t" + mmat.toString(fullDetails);
  27802. }
  27803. }
  27804. // Skeletons
  27805. if (parsedData.skeletons) {
  27806. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27807. var parsedSkeleton = parsedData.skeletons[index];
  27808. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27809. log += (index === 0 ? "\n\tSkeletons:" : "");
  27810. log += "\n\t\t" + skeleton.toString(fullDetails);
  27811. }
  27812. }
  27813. // Geometries
  27814. var geometries = parsedData.geometries;
  27815. if (geometries) {
  27816. // Boxes
  27817. var boxes = geometries.boxes;
  27818. if (boxes) {
  27819. for (index = 0, cache = boxes.length; index < cache; index++) {
  27820. var parsedBox = boxes[index];
  27821. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27822. }
  27823. }
  27824. // Spheres
  27825. var spheres = geometries.spheres;
  27826. if (spheres) {
  27827. for (index = 0, cache = spheres.length; index < cache; index++) {
  27828. var parsedSphere = spheres[index];
  27829. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27830. }
  27831. }
  27832. // Cylinders
  27833. var cylinders = geometries.cylinders;
  27834. if (cylinders) {
  27835. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27836. var parsedCylinder = cylinders[index];
  27837. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27838. }
  27839. }
  27840. // Toruses
  27841. var toruses = geometries.toruses;
  27842. if (toruses) {
  27843. for (index = 0, cache = toruses.length; index < cache; index++) {
  27844. var parsedTorus = toruses[index];
  27845. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27846. }
  27847. }
  27848. // Grounds
  27849. var grounds = geometries.grounds;
  27850. if (grounds) {
  27851. for (index = 0, cache = grounds.length; index < cache; index++) {
  27852. var parsedGround = grounds[index];
  27853. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27854. }
  27855. }
  27856. // Planes
  27857. var planes = geometries.planes;
  27858. if (planes) {
  27859. for (index = 0, cache = planes.length; index < cache; index++) {
  27860. var parsedPlane = planes[index];
  27861. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27862. }
  27863. }
  27864. // TorusKnots
  27865. var torusKnots = geometries.torusKnots;
  27866. if (torusKnots) {
  27867. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27868. var parsedTorusKnot = torusKnots[index];
  27869. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27870. }
  27871. }
  27872. // VertexData
  27873. var vertexData = geometries.vertexData;
  27874. if (vertexData) {
  27875. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27876. var parsedVertexData = vertexData[index];
  27877. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27878. }
  27879. }
  27880. }
  27881. // Meshes
  27882. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27883. var parsedMesh = parsedData.meshes[index];
  27884. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27885. log += (index === 0 ? "\n\tMeshes:" : "");
  27886. log += "\n\t\t" + mesh.toString(fullDetails);
  27887. }
  27888. // Cameras
  27889. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27890. var parsedCamera = parsedData.cameras[index];
  27891. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27892. log += (index === 0 ? "\n\tCameras:" : "");
  27893. log += "\n\t\t" + camera.toString(fullDetails);
  27894. }
  27895. if (parsedData.activeCameraID) {
  27896. scene.setActiveCameraByID(parsedData.activeCameraID);
  27897. }
  27898. // Browsing all the graph to connect the dots
  27899. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27900. var camera = scene.cameras[index];
  27901. if (camera._waitingParentId) {
  27902. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27903. camera._waitingParentId = undefined;
  27904. }
  27905. }
  27906. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27907. var light = scene.lights[index];
  27908. if (light._waitingParentId) {
  27909. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27910. light._waitingParentId = undefined;
  27911. }
  27912. }
  27913. // Sounds
  27914. var loadedSounds = [];
  27915. var loadedSound;
  27916. if (BABYLON.AudioEngine && parsedData.sounds) {
  27917. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27918. var parsedSound = parsedData.sounds[index];
  27919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27920. if (!parsedSound.url)
  27921. parsedSound.url = parsedSound.name;
  27922. if (!loadedSounds[parsedSound.url]) {
  27923. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27924. loadedSounds[parsedSound.url] = loadedSound;
  27925. }
  27926. else {
  27927. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27928. }
  27929. }
  27930. else {
  27931. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27932. }
  27933. }
  27934. }
  27935. loadedSounds = [];
  27936. // Connect parents & children and parse actions
  27937. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27938. var mesh = scene.meshes[index];
  27939. if (mesh._waitingParentId) {
  27940. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27941. mesh._waitingParentId = undefined;
  27942. }
  27943. if (mesh._waitingActions) {
  27944. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27945. mesh._waitingActions = undefined;
  27946. }
  27947. }
  27948. // freeze world matrix application
  27949. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27950. var currentMesh = scene.meshes[index];
  27951. if (currentMesh._waitingFreezeWorldMatrix) {
  27952. currentMesh.freezeWorldMatrix();
  27953. currentMesh._waitingFreezeWorldMatrix = undefined;
  27954. }
  27955. else {
  27956. currentMesh.computeWorldMatrix(true);
  27957. }
  27958. }
  27959. // Particles Systems
  27960. if (parsedData.particleSystems) {
  27961. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27962. var parsedParticleSystem = parsedData.particleSystems[index];
  27963. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27964. }
  27965. }
  27966. // Lens flares
  27967. if (parsedData.lensFlareSystems) {
  27968. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27969. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27970. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27971. }
  27972. }
  27973. // Shadows
  27974. if (parsedData.shadowGenerators) {
  27975. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27976. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27977. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27978. }
  27979. }
  27980. // Actions (scene)
  27981. if (parsedData.actions) {
  27982. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27983. }
  27984. // Finish
  27985. return true;
  27986. }
  27987. catch (err) {
  27988. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27989. log = null;
  27990. throw err;
  27991. }
  27992. finally {
  27993. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27994. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27995. }
  27996. }
  27997. }
  27998. });
  27999. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28000. })(BABYLON || (BABYLON = {}));
  28001. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28002. var BABYLON;
  28003. (function (BABYLON) {
  28004. var SpriteManager = (function () {
  28005. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28006. if (epsilon === void 0) { epsilon = 0.01; }
  28007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28008. this.name = name;
  28009. this.sprites = new Array();
  28010. this.renderingGroupId = 0;
  28011. this.layerMask = 0x0FFFFFFF;
  28012. this.fogEnabled = true;
  28013. this.isPickable = false;
  28014. /**
  28015. * An event triggered when the manager is disposed.
  28016. * @type {BABYLON.Observable}
  28017. */
  28018. this.onDisposeObservable = new BABYLON.Observable();
  28019. this._vertexBuffers = {};
  28020. this._capacity = capacity;
  28021. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28022. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28023. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28024. if (cellSize.width && cellSize.height) {
  28025. this.cellWidth = cellSize.width;
  28026. this.cellHeight = cellSize.height;
  28027. }
  28028. else if (cellSize !== undefined) {
  28029. this.cellWidth = cellSize;
  28030. this.cellHeight = cellSize;
  28031. }
  28032. else {
  28033. return;
  28034. }
  28035. this._epsilon = epsilon;
  28036. this._scene = scene;
  28037. this._scene.spriteManagers.push(this);
  28038. var indices = [];
  28039. var index = 0;
  28040. for (var count = 0; count < capacity; count++) {
  28041. indices.push(index);
  28042. indices.push(index + 1);
  28043. indices.push(index + 2);
  28044. indices.push(index);
  28045. indices.push(index + 2);
  28046. indices.push(index + 3);
  28047. index += 4;
  28048. }
  28049. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28050. // VBO
  28051. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28052. this._vertexData = new Float32Array(capacity * 16 * 4);
  28053. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28054. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28055. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28056. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28057. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28058. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28059. this._vertexBuffers["options"] = options;
  28060. this._vertexBuffers["cellInfo"] = cellInfo;
  28061. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28062. // Effects
  28063. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28064. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28065. }
  28066. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28067. set: function (callback) {
  28068. if (this._onDisposeObserver) {
  28069. this.onDisposeObservable.remove(this._onDisposeObserver);
  28070. }
  28071. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28072. },
  28073. enumerable: true,
  28074. configurable: true
  28075. });
  28076. Object.defineProperty(SpriteManager.prototype, "texture", {
  28077. get: function () {
  28078. return this._spriteTexture;
  28079. },
  28080. set: function (value) {
  28081. this._spriteTexture = value;
  28082. },
  28083. enumerable: true,
  28084. configurable: true
  28085. });
  28086. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28087. var arrayOffset = index * 16;
  28088. if (offsetX === 0)
  28089. offsetX = this._epsilon;
  28090. else if (offsetX === 1)
  28091. offsetX = 1 - this._epsilon;
  28092. if (offsetY === 0)
  28093. offsetY = this._epsilon;
  28094. else if (offsetY === 1)
  28095. offsetY = 1 - this._epsilon;
  28096. this._vertexData[arrayOffset] = sprite.position.x;
  28097. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28098. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28099. this._vertexData[arrayOffset + 3] = sprite.angle;
  28100. this._vertexData[arrayOffset + 4] = sprite.width;
  28101. this._vertexData[arrayOffset + 5] = sprite.height;
  28102. this._vertexData[arrayOffset + 6] = offsetX;
  28103. this._vertexData[arrayOffset + 7] = offsetY;
  28104. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28105. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28106. var offset = (sprite.cellIndex / rowSize) >> 0;
  28107. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28108. this._vertexData[arrayOffset + 11] = offset;
  28109. // Color
  28110. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28111. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28112. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28113. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28114. };
  28115. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28116. var count = Math.min(this._capacity, this.sprites.length);
  28117. var min = BABYLON.Vector3.Zero();
  28118. var max = BABYLON.Vector3.Zero();
  28119. var distance = Number.MAX_VALUE;
  28120. var currentSprite;
  28121. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28122. var cameraView = camera.getViewMatrix();
  28123. for (var index = 0; index < count; index++) {
  28124. var sprite = this.sprites[index];
  28125. if (!sprite) {
  28126. continue;
  28127. }
  28128. if (predicate) {
  28129. if (!predicate(sprite)) {
  28130. continue;
  28131. }
  28132. }
  28133. else if (!sprite.isPickable) {
  28134. continue;
  28135. }
  28136. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28137. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28138. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28139. if (ray.intersectsBoxMinMax(min, max)) {
  28140. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28141. if (distance > currentDistance) {
  28142. distance = currentDistance;
  28143. currentSprite = sprite;
  28144. if (fastCheck) {
  28145. break;
  28146. }
  28147. }
  28148. }
  28149. }
  28150. if (currentSprite) {
  28151. var result = new BABYLON.PickingInfo();
  28152. result.hit = true;
  28153. result.pickedSprite = currentSprite;
  28154. result.distance = distance;
  28155. return result;
  28156. }
  28157. return null;
  28158. };
  28159. SpriteManager.prototype.render = function () {
  28160. // Check
  28161. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28162. return;
  28163. var engine = this._scene.getEngine();
  28164. var baseSize = this._spriteTexture.getBaseSize();
  28165. // Sprites
  28166. var deltaTime = engine.getDeltaTime();
  28167. var max = Math.min(this._capacity, this.sprites.length);
  28168. var rowSize = baseSize.width / this.cellWidth;
  28169. var offset = 0;
  28170. for (var index = 0; index < max; index++) {
  28171. var sprite = this.sprites[index];
  28172. if (!sprite) {
  28173. continue;
  28174. }
  28175. sprite._animate(deltaTime);
  28176. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28177. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28178. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28179. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28180. }
  28181. this._buffer.update(this._vertexData);
  28182. // Render
  28183. var effect = this._effectBase;
  28184. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28185. effect = this._effectFog;
  28186. }
  28187. engine.enableEffect(effect);
  28188. var viewMatrix = this._scene.getViewMatrix();
  28189. effect.setTexture("diffuseSampler", this._spriteTexture);
  28190. effect.setMatrix("view", viewMatrix);
  28191. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28192. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28193. // Fog
  28194. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28195. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28196. effect.setColor3("vFogColor", this._scene.fogColor);
  28197. }
  28198. // VBOs
  28199. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28200. // Draw order
  28201. engine.setDepthFunctionToLessOrEqual();
  28202. effect.setBool("alphaTest", true);
  28203. engine.setColorWrite(false);
  28204. engine.draw(true, 0, max * 6);
  28205. engine.setColorWrite(true);
  28206. effect.setBool("alphaTest", false);
  28207. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28208. engine.draw(true, 0, max * 6);
  28209. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28210. };
  28211. SpriteManager.prototype.dispose = function () {
  28212. if (this._buffer) {
  28213. this._buffer.dispose();
  28214. this._buffer = null;
  28215. }
  28216. if (this._indexBuffer) {
  28217. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28218. this._indexBuffer = null;
  28219. }
  28220. if (this._spriteTexture) {
  28221. this._spriteTexture.dispose();
  28222. this._spriteTexture = null;
  28223. }
  28224. // Remove from scene
  28225. var index = this._scene.spriteManagers.indexOf(this);
  28226. this._scene.spriteManagers.splice(index, 1);
  28227. // Callback
  28228. this.onDisposeObservable.notifyObservers(this);
  28229. this.onDisposeObservable.clear();
  28230. };
  28231. return SpriteManager;
  28232. }());
  28233. BABYLON.SpriteManager = SpriteManager;
  28234. })(BABYLON || (BABYLON = {}));
  28235. //# sourceMappingURL=babylon.spriteManager.js.map
  28236. var BABYLON;
  28237. (function (BABYLON) {
  28238. var Sprite = (function () {
  28239. function Sprite(name, manager) {
  28240. this.name = name;
  28241. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28242. this.width = 1.0;
  28243. this.height = 1.0;
  28244. this.angle = 0;
  28245. this.cellIndex = 0;
  28246. this.invertU = 0;
  28247. this.invertV = 0;
  28248. this.animations = new Array();
  28249. this.isPickable = false;
  28250. this._animationStarted = false;
  28251. this._loopAnimation = false;
  28252. this._fromIndex = 0;
  28253. this._toIndex = 0;
  28254. this._delay = 0;
  28255. this._direction = 1;
  28256. this._frameCount = 0;
  28257. this._time = 0;
  28258. this._manager = manager;
  28259. this._manager.sprites.push(this);
  28260. this.position = BABYLON.Vector3.Zero();
  28261. }
  28262. Object.defineProperty(Sprite.prototype, "size", {
  28263. get: function () {
  28264. return this.width;
  28265. },
  28266. set: function (value) {
  28267. this.width = value;
  28268. this.height = value;
  28269. },
  28270. enumerable: true,
  28271. configurable: true
  28272. });
  28273. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28274. this._fromIndex = from;
  28275. this._toIndex = to;
  28276. this._loopAnimation = loop;
  28277. this._delay = delay;
  28278. this._animationStarted = true;
  28279. this._direction = from < to ? 1 : -1;
  28280. this.cellIndex = from;
  28281. this._time = 0;
  28282. this._onAnimationEnd = onAnimationEnd;
  28283. };
  28284. Sprite.prototype.stopAnimation = function () {
  28285. this._animationStarted = false;
  28286. };
  28287. Sprite.prototype._animate = function (deltaTime) {
  28288. if (!this._animationStarted)
  28289. return;
  28290. this._time += deltaTime;
  28291. if (this._time > this._delay) {
  28292. this._time = this._time % this._delay;
  28293. this.cellIndex += this._direction;
  28294. if (this.cellIndex === this._toIndex) {
  28295. if (this._loopAnimation) {
  28296. this.cellIndex = this._fromIndex;
  28297. }
  28298. else {
  28299. this._animationStarted = false;
  28300. if (this._onAnimationEnd) {
  28301. this._onAnimationEnd();
  28302. }
  28303. if (this.disposeWhenFinishedAnimating) {
  28304. this.dispose();
  28305. }
  28306. }
  28307. }
  28308. }
  28309. };
  28310. Sprite.prototype.dispose = function () {
  28311. for (var i = 0; i < this._manager.sprites.length; i++) {
  28312. if (this._manager.sprites[i] == this) {
  28313. this._manager.sprites.splice(i, 1);
  28314. }
  28315. }
  28316. };
  28317. return Sprite;
  28318. }());
  28319. BABYLON.Sprite = Sprite;
  28320. })(BABYLON || (BABYLON = {}));
  28321. //# sourceMappingURL=babylon.sprite.js.map
  28322. var BABYLON;
  28323. (function (BABYLON) {
  28324. var Layer = (function () {
  28325. function Layer(name, imgUrl, scene, isBackground, color) {
  28326. this.name = name;
  28327. this.scale = new BABYLON.Vector2(1, 1);
  28328. this.offset = new BABYLON.Vector2(0, 0);
  28329. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28330. this._vertexBuffers = {};
  28331. // Events
  28332. /**
  28333. * An event triggered when the layer is disposed.
  28334. * @type {BABYLON.Observable}
  28335. */
  28336. this.onDisposeObservable = new BABYLON.Observable();
  28337. /**
  28338. * An event triggered before rendering the scene
  28339. * @type {BABYLON.Observable}
  28340. */
  28341. this.onBeforeRenderObservable = new BABYLON.Observable();
  28342. /**
  28343. * An event triggered after rendering the scene
  28344. * @type {BABYLON.Observable}
  28345. */
  28346. this.onAfterRenderObservable = new BABYLON.Observable();
  28347. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28348. this.isBackground = isBackground === undefined ? true : isBackground;
  28349. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28350. this._scene = scene;
  28351. this._scene.layers.push(this);
  28352. var engine = scene.getEngine();
  28353. // VBO
  28354. var vertices = [];
  28355. vertices.push(1, 1);
  28356. vertices.push(-1, 1);
  28357. vertices.push(-1, -1);
  28358. vertices.push(1, -1);
  28359. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28361. // Indices
  28362. var indices = [];
  28363. indices.push(0);
  28364. indices.push(1);
  28365. indices.push(2);
  28366. indices.push(0);
  28367. indices.push(2);
  28368. indices.push(3);
  28369. this._indexBuffer = engine.createIndexBuffer(indices);
  28370. // Effects
  28371. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28372. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28373. }
  28374. Object.defineProperty(Layer.prototype, "onDispose", {
  28375. set: function (callback) {
  28376. if (this._onDisposeObserver) {
  28377. this.onDisposeObservable.remove(this._onDisposeObserver);
  28378. }
  28379. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28380. },
  28381. enumerable: true,
  28382. configurable: true
  28383. });
  28384. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28385. set: function (callback) {
  28386. if (this._onBeforeRenderObserver) {
  28387. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28388. }
  28389. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28390. },
  28391. enumerable: true,
  28392. configurable: true
  28393. });
  28394. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28395. set: function (callback) {
  28396. if (this._onAfterRenderObserver) {
  28397. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28398. }
  28399. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28400. },
  28401. enumerable: true,
  28402. configurable: true
  28403. });
  28404. Layer.prototype.render = function () {
  28405. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28406. // Check
  28407. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28408. return;
  28409. var engine = this._scene.getEngine();
  28410. this.onBeforeRenderObservable.notifyObservers(this);
  28411. // Render
  28412. engine.enableEffect(currentEffect);
  28413. engine.setState(false);
  28414. // Texture
  28415. currentEffect.setTexture("textureSampler", this.texture);
  28416. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28417. // Color
  28418. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28419. // Scale / offset
  28420. currentEffect.setVector2("offset", this.offset);
  28421. currentEffect.setVector2("scale", this.scale);
  28422. // VBOs
  28423. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28424. // Draw order
  28425. if (!this.alphaTest) {
  28426. engine.setAlphaMode(this.alphaBlendingMode);
  28427. engine.draw(true, 0, 6);
  28428. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28429. }
  28430. else {
  28431. engine.draw(true, 0, 6);
  28432. }
  28433. this.onAfterRenderObservable.notifyObservers(this);
  28434. };
  28435. Layer.prototype.dispose = function () {
  28436. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28437. if (vertexBuffer) {
  28438. vertexBuffer.dispose();
  28439. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28440. }
  28441. if (this._indexBuffer) {
  28442. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28443. this._indexBuffer = null;
  28444. }
  28445. if (this.texture) {
  28446. this.texture.dispose();
  28447. this.texture = null;
  28448. }
  28449. // Remove from scene
  28450. var index = this._scene.layers.indexOf(this);
  28451. this._scene.layers.splice(index, 1);
  28452. // Callback
  28453. this.onDisposeObservable.notifyObservers(this);
  28454. this.onDisposeObservable.clear();
  28455. this.onAfterRenderObservable.clear();
  28456. this.onBeforeRenderObservable.clear();
  28457. };
  28458. return Layer;
  28459. }());
  28460. BABYLON.Layer = Layer;
  28461. })(BABYLON || (BABYLON = {}));
  28462. //# sourceMappingURL=babylon.layer.js.map
  28463. var BABYLON;
  28464. (function (BABYLON) {
  28465. var Particle = (function () {
  28466. function Particle() {
  28467. this.position = BABYLON.Vector3.Zero();
  28468. this.direction = BABYLON.Vector3.Zero();
  28469. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28470. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28471. this.lifeTime = 1.0;
  28472. this.age = 0;
  28473. this.size = 0;
  28474. this.angle = 0;
  28475. this.angularSpeed = 0;
  28476. }
  28477. Particle.prototype.copyTo = function (other) {
  28478. other.position.copyFrom(this.position);
  28479. other.direction.copyFrom(this.direction);
  28480. other.color.copyFrom(this.color);
  28481. other.colorStep.copyFrom(this.colorStep);
  28482. other.lifeTime = this.lifeTime;
  28483. other.age = this.age;
  28484. other.size = this.size;
  28485. other.angle = this.angle;
  28486. other.angularSpeed = this.angularSpeed;
  28487. };
  28488. return Particle;
  28489. }());
  28490. BABYLON.Particle = Particle;
  28491. })(BABYLON || (BABYLON = {}));
  28492. //# sourceMappingURL=babylon.particle.js.map
  28493. var BABYLON;
  28494. (function (BABYLON) {
  28495. var randomNumber = function (min, max) {
  28496. if (min === max) {
  28497. return (min);
  28498. }
  28499. var random = Math.random();
  28500. return ((random * (max - min)) + min);
  28501. };
  28502. var ParticleSystem = (function () {
  28503. function ParticleSystem(name, capacity, scene, customEffect) {
  28504. var _this = this;
  28505. this.name = name;
  28506. // Members
  28507. this.animations = [];
  28508. this.renderingGroupId = 0;
  28509. this.emitter = null;
  28510. this.emitRate = 10;
  28511. this.manualEmitCount = -1;
  28512. this.updateSpeed = 0.01;
  28513. this.targetStopDuration = 0;
  28514. this.disposeOnStop = false;
  28515. this.minEmitPower = 1;
  28516. this.maxEmitPower = 1;
  28517. this.minLifeTime = 1;
  28518. this.maxLifeTime = 1;
  28519. this.minSize = 1;
  28520. this.maxSize = 1;
  28521. this.minAngularSpeed = 0;
  28522. this.maxAngularSpeed = 0;
  28523. this.layerMask = 0x0FFFFFFF;
  28524. /**
  28525. * An event triggered when the system is disposed.
  28526. * @type {BABYLON.Observable}
  28527. */
  28528. this.onDisposeObservable = new BABYLON.Observable();
  28529. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28530. this.forceDepthWrite = false;
  28531. this.gravity = BABYLON.Vector3.Zero();
  28532. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28533. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28534. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28535. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28536. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28537. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28538. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28539. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28540. this.particles = new Array();
  28541. this._stockParticles = new Array();
  28542. this._newPartsExcess = 0;
  28543. this._vertexBuffers = {};
  28544. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28545. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28546. this._scaledDirection = BABYLON.Vector3.Zero();
  28547. this._scaledGravity = BABYLON.Vector3.Zero();
  28548. this._currentRenderId = -1;
  28549. this._started = false;
  28550. this._stopped = false;
  28551. this._actualFrame = 0;
  28552. this.id = name;
  28553. this._capacity = capacity;
  28554. this._scene = scene;
  28555. this._customEffect = customEffect;
  28556. scene.particleSystems.push(this);
  28557. var indices = [];
  28558. var index = 0;
  28559. for (var count = 0; count < capacity; count++) {
  28560. indices.push(index);
  28561. indices.push(index + 1);
  28562. indices.push(index + 2);
  28563. indices.push(index);
  28564. indices.push(index + 2);
  28565. indices.push(index + 3);
  28566. index += 4;
  28567. }
  28568. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28569. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28570. this._vertexData = new Float32Array(capacity * 11 * 4);
  28571. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28572. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28573. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28574. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28576. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28577. this._vertexBuffers["options"] = options;
  28578. // Default behaviors
  28579. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28580. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28581. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28582. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28583. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28584. };
  28585. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28586. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28587. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28588. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28589. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28590. };
  28591. this.updateFunction = function (particles) {
  28592. for (var index = 0; index < particles.length; index++) {
  28593. var particle = particles[index];
  28594. particle.age += _this._scaledUpdateSpeed;
  28595. if (particle.age >= particle.lifeTime) {
  28596. _this.recycleParticle(particle);
  28597. index--;
  28598. continue;
  28599. }
  28600. else {
  28601. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28602. particle.color.addInPlace(_this._scaledColorStep);
  28603. if (particle.color.a < 0)
  28604. particle.color.a = 0;
  28605. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28606. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28607. particle.position.addInPlace(_this._scaledDirection);
  28608. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28609. particle.direction.addInPlace(_this._scaledGravity);
  28610. }
  28611. }
  28612. };
  28613. }
  28614. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28615. set: function (callback) {
  28616. if (this._onDisposeObserver) {
  28617. this.onDisposeObservable.remove(this._onDisposeObserver);
  28618. }
  28619. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28620. },
  28621. enumerable: true,
  28622. configurable: true
  28623. });
  28624. ParticleSystem.prototype.recycleParticle = function (particle) {
  28625. var lastParticle = this.particles.pop();
  28626. if (lastParticle !== particle) {
  28627. lastParticle.copyTo(particle);
  28628. this._stockParticles.push(lastParticle);
  28629. }
  28630. };
  28631. ParticleSystem.prototype.getCapacity = function () {
  28632. return this._capacity;
  28633. };
  28634. ParticleSystem.prototype.isAlive = function () {
  28635. return this._alive;
  28636. };
  28637. ParticleSystem.prototype.isStarted = function () {
  28638. return this._started;
  28639. };
  28640. ParticleSystem.prototype.start = function () {
  28641. this._started = true;
  28642. this._stopped = false;
  28643. this._actualFrame = 0;
  28644. };
  28645. ParticleSystem.prototype.stop = function () {
  28646. this._stopped = true;
  28647. };
  28648. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28649. var offset = index * 11;
  28650. this._vertexData[offset] = particle.position.x;
  28651. this._vertexData[offset + 1] = particle.position.y;
  28652. this._vertexData[offset + 2] = particle.position.z;
  28653. this._vertexData[offset + 3] = particle.color.r;
  28654. this._vertexData[offset + 4] = particle.color.g;
  28655. this._vertexData[offset + 5] = particle.color.b;
  28656. this._vertexData[offset + 6] = particle.color.a;
  28657. this._vertexData[offset + 7] = particle.angle;
  28658. this._vertexData[offset + 8] = particle.size;
  28659. this._vertexData[offset + 9] = offsetX;
  28660. this._vertexData[offset + 10] = offsetY;
  28661. };
  28662. ParticleSystem.prototype._update = function (newParticles) {
  28663. // Update current
  28664. this._alive = this.particles.length > 0;
  28665. this.updateFunction(this.particles);
  28666. // Add new ones
  28667. var worldMatrix;
  28668. if (this.emitter.position) {
  28669. worldMatrix = this.emitter.getWorldMatrix();
  28670. }
  28671. else {
  28672. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28673. }
  28674. var particle;
  28675. for (var index = 0; index < newParticles; index++) {
  28676. if (this.particles.length === this._capacity) {
  28677. break;
  28678. }
  28679. if (this._stockParticles.length !== 0) {
  28680. particle = this._stockParticles.pop();
  28681. particle.age = 0;
  28682. }
  28683. else {
  28684. particle = new BABYLON.Particle();
  28685. }
  28686. this.particles.push(particle);
  28687. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28688. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28689. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28690. particle.size = randomNumber(this.minSize, this.maxSize);
  28691. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28692. this.startPositionFunction(worldMatrix, particle.position, particle);
  28693. var step = randomNumber(0, 1.0);
  28694. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28695. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28696. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28697. }
  28698. };
  28699. ParticleSystem.prototype._getEffect = function () {
  28700. if (this._customEffect) {
  28701. return this._customEffect;
  28702. }
  28703. ;
  28704. var defines = [];
  28705. if (this._scene.clipPlane) {
  28706. defines.push("#define CLIPPLANE");
  28707. }
  28708. // Effect
  28709. var join = defines.join("\n");
  28710. if (this._cachedDefines !== join) {
  28711. this._cachedDefines = join;
  28712. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28713. }
  28714. return this._effect;
  28715. };
  28716. ParticleSystem.prototype.animate = function () {
  28717. if (!this._started)
  28718. return;
  28719. var effect = this._getEffect();
  28720. // Check
  28721. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28722. return;
  28723. if (this._currentRenderId === this._scene.getRenderId()) {
  28724. return;
  28725. }
  28726. this._currentRenderId = this._scene.getRenderId();
  28727. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28728. // determine the number of particles we need to create
  28729. var newParticles;
  28730. if (this.manualEmitCount > -1) {
  28731. newParticles = this.manualEmitCount;
  28732. this._newPartsExcess = 0;
  28733. this.manualEmitCount = 0;
  28734. }
  28735. else {
  28736. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28737. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28738. }
  28739. if (this._newPartsExcess > 1.0) {
  28740. newParticles += this._newPartsExcess >> 0;
  28741. this._newPartsExcess -= this._newPartsExcess >> 0;
  28742. }
  28743. this._alive = false;
  28744. if (!this._stopped) {
  28745. this._actualFrame += this._scaledUpdateSpeed;
  28746. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28747. this.stop();
  28748. }
  28749. else {
  28750. newParticles = 0;
  28751. }
  28752. this._update(newParticles);
  28753. // Stopped?
  28754. if (this._stopped) {
  28755. if (!this._alive) {
  28756. this._started = false;
  28757. if (this.disposeOnStop) {
  28758. this._scene._toBeDisposed.push(this);
  28759. }
  28760. }
  28761. }
  28762. // Update VBO
  28763. var offset = 0;
  28764. for (var index = 0; index < this.particles.length; index++) {
  28765. var particle = this.particles[index];
  28766. this._appendParticleVertex(offset++, particle, 0, 0);
  28767. this._appendParticleVertex(offset++, particle, 1, 0);
  28768. this._appendParticleVertex(offset++, particle, 1, 1);
  28769. this._appendParticleVertex(offset++, particle, 0, 1);
  28770. }
  28771. this._vertexBuffer.update(this._vertexData);
  28772. };
  28773. ParticleSystem.prototype.render = function () {
  28774. var effect = this._getEffect();
  28775. // Check
  28776. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28777. return 0;
  28778. var engine = this._scene.getEngine();
  28779. // Render
  28780. engine.enableEffect(effect);
  28781. engine.setState(false);
  28782. var viewMatrix = this._scene.getViewMatrix();
  28783. effect.setTexture("diffuseSampler", this.particleTexture);
  28784. effect.setMatrix("view", viewMatrix);
  28785. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28786. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28787. if (this._scene.clipPlane) {
  28788. var clipPlane = this._scene.clipPlane;
  28789. var invView = viewMatrix.clone();
  28790. invView.invert();
  28791. effect.setMatrix("invView", invView);
  28792. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28793. }
  28794. // VBOs
  28795. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28796. // Draw order
  28797. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28798. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28799. }
  28800. else {
  28801. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28802. }
  28803. if (this.forceDepthWrite) {
  28804. engine.setDepthWrite(true);
  28805. }
  28806. engine.draw(true, 0, this.particles.length * 6);
  28807. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28808. return this.particles.length;
  28809. };
  28810. ParticleSystem.prototype.dispose = function () {
  28811. if (this._vertexBuffer) {
  28812. this._vertexBuffer.dispose();
  28813. this._vertexBuffer = null;
  28814. }
  28815. if (this._indexBuffer) {
  28816. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28817. this._indexBuffer = null;
  28818. }
  28819. if (this.particleTexture) {
  28820. this.particleTexture.dispose();
  28821. this.particleTexture = null;
  28822. }
  28823. // Remove from scene
  28824. var index = this._scene.particleSystems.indexOf(this);
  28825. this._scene.particleSystems.splice(index, 1);
  28826. // Callback
  28827. this.onDisposeObservable.notifyObservers(this);
  28828. this.onDisposeObservable.clear();
  28829. };
  28830. // Clone
  28831. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28832. var result = new ParticleSystem(name, this._capacity, this._scene);
  28833. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28834. if (newEmitter === undefined) {
  28835. newEmitter = this.emitter;
  28836. }
  28837. result.emitter = newEmitter;
  28838. if (this.particleTexture) {
  28839. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28840. }
  28841. result.start();
  28842. return result;
  28843. };
  28844. ParticleSystem.prototype.serialize = function () {
  28845. var serializationObject = {};
  28846. serializationObject.name = this.name;
  28847. serializationObject.id = this.id;
  28848. // Emitter
  28849. if (this.emitter.position) {
  28850. serializationObject.emitterId = this.emitter.id;
  28851. }
  28852. else {
  28853. serializationObject.emitter = this.emitter.asArray();
  28854. }
  28855. serializationObject.capacity = this.getCapacity();
  28856. if (this.particleTexture) {
  28857. serializationObject.textureName = this.particleTexture.name;
  28858. }
  28859. // Animations
  28860. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28861. // Particle system
  28862. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28863. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28864. serializationObject.minSize = this.minSize;
  28865. serializationObject.maxSize = this.maxSize;
  28866. serializationObject.minEmitPower = this.minEmitPower;
  28867. serializationObject.maxEmitPower = this.maxEmitPower;
  28868. serializationObject.minLifeTime = this.minLifeTime;
  28869. serializationObject.maxLifeTime = this.maxLifeTime;
  28870. serializationObject.emitRate = this.emitRate;
  28871. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28872. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28873. serializationObject.gravity = this.gravity.asArray();
  28874. serializationObject.direction1 = this.direction1.asArray();
  28875. serializationObject.direction2 = this.direction2.asArray();
  28876. serializationObject.color1 = this.color1.asArray();
  28877. serializationObject.color2 = this.color2.asArray();
  28878. serializationObject.colorDead = this.colorDead.asArray();
  28879. serializationObject.updateSpeed = this.updateSpeed;
  28880. serializationObject.targetStopDuration = this.targetStopDuration;
  28881. serializationObject.textureMask = this.textureMask.asArray();
  28882. serializationObject.blendMode = this.blendMode;
  28883. return serializationObject;
  28884. };
  28885. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28886. var name = parsedParticleSystem.name;
  28887. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28888. if (parsedParticleSystem.id) {
  28889. particleSystem.id = parsedParticleSystem.id;
  28890. }
  28891. // Texture
  28892. if (parsedParticleSystem.textureName) {
  28893. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28894. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28895. }
  28896. // Emitter
  28897. if (parsedParticleSystem.emitterId) {
  28898. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28899. }
  28900. else {
  28901. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28902. }
  28903. // Animations
  28904. if (parsedParticleSystem.animations) {
  28905. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28906. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28907. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28908. }
  28909. }
  28910. if (parsedParticleSystem.autoAnimate) {
  28911. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28912. }
  28913. // Particle system
  28914. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28915. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28916. particleSystem.minSize = parsedParticleSystem.minSize;
  28917. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28918. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28919. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28920. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28921. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28922. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28923. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28924. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28925. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28926. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28927. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28928. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28929. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28930. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28931. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28932. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28933. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28934. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28935. if (!parsedParticleSystem.preventAutoStart) {
  28936. particleSystem.start();
  28937. }
  28938. return particleSystem;
  28939. };
  28940. // Statics
  28941. ParticleSystem.BLENDMODE_ONEONE = 0;
  28942. ParticleSystem.BLENDMODE_STANDARD = 1;
  28943. return ParticleSystem;
  28944. }());
  28945. BABYLON.ParticleSystem = ParticleSystem;
  28946. })(BABYLON || (BABYLON = {}));
  28947. //# sourceMappingURL=babylon.particleSystem.js.map
  28948. var BABYLON;
  28949. (function (BABYLON) {
  28950. var AnimationRange = (function () {
  28951. function AnimationRange(name, from, to) {
  28952. this.name = name;
  28953. this.from = from;
  28954. this.to = to;
  28955. }
  28956. AnimationRange.prototype.clone = function () {
  28957. return new AnimationRange(this.name, this.from, this.to);
  28958. };
  28959. return AnimationRange;
  28960. }());
  28961. BABYLON.AnimationRange = AnimationRange;
  28962. /**
  28963. * Composed of a frame, and an action function
  28964. */
  28965. var AnimationEvent = (function () {
  28966. function AnimationEvent(frame, action, onlyOnce) {
  28967. this.frame = frame;
  28968. this.action = action;
  28969. this.onlyOnce = onlyOnce;
  28970. this.isDone = false;
  28971. }
  28972. return AnimationEvent;
  28973. }());
  28974. BABYLON.AnimationEvent = AnimationEvent;
  28975. var PathCursor = (function () {
  28976. function PathCursor(path) {
  28977. this.path = path;
  28978. this._onchange = new Array();
  28979. this.value = 0;
  28980. this.animations = new Array();
  28981. }
  28982. PathCursor.prototype.getPoint = function () {
  28983. var point = this.path.getPointAtLengthPosition(this.value);
  28984. return new BABYLON.Vector3(point.x, 0, point.y);
  28985. };
  28986. PathCursor.prototype.moveAhead = function (step) {
  28987. if (step === void 0) { step = 0.002; }
  28988. this.move(step);
  28989. return this;
  28990. };
  28991. PathCursor.prototype.moveBack = function (step) {
  28992. if (step === void 0) { step = 0.002; }
  28993. this.move(-step);
  28994. return this;
  28995. };
  28996. PathCursor.prototype.move = function (step) {
  28997. if (Math.abs(step) > 1) {
  28998. throw "step size should be less than 1.";
  28999. }
  29000. this.value += step;
  29001. this.ensureLimits();
  29002. this.raiseOnChange();
  29003. return this;
  29004. };
  29005. PathCursor.prototype.ensureLimits = function () {
  29006. while (this.value > 1) {
  29007. this.value -= 1;
  29008. }
  29009. while (this.value < 0) {
  29010. this.value += 1;
  29011. }
  29012. return this;
  29013. };
  29014. // used by animation engine
  29015. PathCursor.prototype.markAsDirty = function (propertyName) {
  29016. this.ensureLimits();
  29017. this.raiseOnChange();
  29018. return this;
  29019. };
  29020. PathCursor.prototype.raiseOnChange = function () {
  29021. var _this = this;
  29022. this._onchange.forEach(function (f) { return f(_this); });
  29023. return this;
  29024. };
  29025. PathCursor.prototype.onchange = function (f) {
  29026. this._onchange.push(f);
  29027. return this;
  29028. };
  29029. return PathCursor;
  29030. }());
  29031. BABYLON.PathCursor = PathCursor;
  29032. var Animation = (function () {
  29033. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29034. this.name = name;
  29035. this.targetProperty = targetProperty;
  29036. this.framePerSecond = framePerSecond;
  29037. this.dataType = dataType;
  29038. this.loopMode = loopMode;
  29039. this.enableBlending = enableBlending;
  29040. this._offsetsCache = {};
  29041. this._highLimitsCache = {};
  29042. this._stopped = false;
  29043. this._blendingFactor = 0;
  29044. // The set of event that will be linked to this animation
  29045. this._events = new Array();
  29046. this.allowMatricesInterpolation = false;
  29047. this.blendingSpeed = 0.01;
  29048. this._ranges = {};
  29049. this.targetPropertyPath = targetProperty.split(".");
  29050. this.dataType = dataType;
  29051. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29052. }
  29053. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29054. var dataType = undefined;
  29055. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29056. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29057. }
  29058. else if (from instanceof BABYLON.Quaternion) {
  29059. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29060. }
  29061. else if (from instanceof BABYLON.Vector3) {
  29062. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29063. }
  29064. else if (from instanceof BABYLON.Vector2) {
  29065. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29066. }
  29067. else if (from instanceof BABYLON.Color3) {
  29068. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29069. }
  29070. else if (from instanceof BABYLON.Size) {
  29071. dataType = Animation.ANIMATIONTYPE_SIZE;
  29072. }
  29073. if (dataType == undefined) {
  29074. return null;
  29075. }
  29076. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29077. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29078. animation.setKeys(keys);
  29079. if (easingFunction !== undefined) {
  29080. animation.setEasingFunction(easingFunction);
  29081. }
  29082. return animation;
  29083. };
  29084. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29085. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29086. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29087. };
  29088. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29089. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29090. node.animations.push(animation);
  29091. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29092. };
  29093. // Methods
  29094. /**
  29095. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29096. */
  29097. Animation.prototype.toString = function (fullDetails) {
  29098. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29099. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29100. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29101. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29102. if (fullDetails) {
  29103. ret += ", Ranges: {";
  29104. var first = true;
  29105. for (var name in this._ranges) {
  29106. if (first) {
  29107. ret += ", ";
  29108. first = false;
  29109. }
  29110. ret += name;
  29111. }
  29112. ret += "}";
  29113. }
  29114. return ret;
  29115. };
  29116. /**
  29117. * Add an event to this animation.
  29118. */
  29119. Animation.prototype.addEvent = function (event) {
  29120. this._events.push(event);
  29121. };
  29122. /**
  29123. * Remove all events found at the given frame
  29124. * @param frame
  29125. */
  29126. Animation.prototype.removeEvents = function (frame) {
  29127. for (var index = 0; index < this._events.length; index++) {
  29128. if (this._events[index].frame === frame) {
  29129. this._events.splice(index, 1);
  29130. index--;
  29131. }
  29132. }
  29133. };
  29134. Animation.prototype.createRange = function (name, from, to) {
  29135. // check name not already in use; could happen for bones after serialized
  29136. if (!this._ranges[name]) {
  29137. this._ranges[name] = new AnimationRange(name, from, to);
  29138. }
  29139. };
  29140. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29141. if (deleteFrames === void 0) { deleteFrames = true; }
  29142. if (this._ranges[name]) {
  29143. if (deleteFrames) {
  29144. var from = this._ranges[name].from;
  29145. var to = this._ranges[name].to;
  29146. // this loop MUST go high to low for multiple splices to work
  29147. for (var key = this._keys.length - 1; key >= 0; key--) {
  29148. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29149. this._keys.splice(key, 1);
  29150. }
  29151. }
  29152. }
  29153. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29154. }
  29155. };
  29156. Animation.prototype.getRange = function (name) {
  29157. return this._ranges[name];
  29158. };
  29159. Animation.prototype.reset = function () {
  29160. this._offsetsCache = {};
  29161. this._highLimitsCache = {};
  29162. this.currentFrame = 0;
  29163. this._blendingFactor = 0;
  29164. this._originalBlendValue = null;
  29165. };
  29166. Animation.prototype.isStopped = function () {
  29167. return this._stopped;
  29168. };
  29169. Animation.prototype.getKeys = function () {
  29170. return this._keys;
  29171. };
  29172. Animation.prototype.getHighestFrame = function () {
  29173. var ret = 0;
  29174. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29175. if (ret < this._keys[key].frame) {
  29176. ret = this._keys[key].frame;
  29177. }
  29178. }
  29179. return ret;
  29180. };
  29181. Animation.prototype.getEasingFunction = function () {
  29182. return this._easingFunction;
  29183. };
  29184. Animation.prototype.setEasingFunction = function (easingFunction) {
  29185. this._easingFunction = easingFunction;
  29186. };
  29187. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29188. return startValue + (endValue - startValue) * gradient;
  29189. };
  29190. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29191. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29192. };
  29193. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29194. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29195. };
  29196. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29197. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29198. };
  29199. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29200. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29201. };
  29202. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29203. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29204. };
  29205. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29206. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29207. };
  29208. Animation.prototype.clone = function () {
  29209. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29210. if (this._keys) {
  29211. clone.setKeys(this._keys);
  29212. }
  29213. if (this._ranges) {
  29214. clone._ranges = {};
  29215. for (var name in this._ranges) {
  29216. clone._ranges[name] = this._ranges[name].clone();
  29217. }
  29218. }
  29219. return clone;
  29220. };
  29221. Animation.prototype.setKeys = function (values) {
  29222. this._keys = values.slice(0);
  29223. this._offsetsCache = {};
  29224. this._highLimitsCache = {};
  29225. };
  29226. Animation.prototype._getKeyValue = function (value) {
  29227. if (typeof value === "function") {
  29228. return value();
  29229. }
  29230. return value;
  29231. };
  29232. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29233. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29234. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29235. }
  29236. this.currentFrame = currentFrame;
  29237. // Try to get a hash to find the right key
  29238. 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));
  29239. if (this._keys[startKey].frame >= currentFrame) {
  29240. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29241. startKey--;
  29242. }
  29243. }
  29244. for (var key = startKey; key < this._keys.length; key++) {
  29245. if (this._keys[key + 1].frame >= currentFrame) {
  29246. var startValue = this._getKeyValue(this._keys[key].value);
  29247. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29248. // gradient : percent of currentFrame between the frame inf and the frame sup
  29249. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29250. // check for easingFunction and correction of gradient
  29251. if (this._easingFunction != null) {
  29252. gradient = this._easingFunction.ease(gradient);
  29253. }
  29254. switch (this.dataType) {
  29255. // Float
  29256. case Animation.ANIMATIONTYPE_FLOAT:
  29257. switch (loopMode) {
  29258. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29259. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29260. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29261. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29262. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29263. }
  29264. break;
  29265. // Quaternion
  29266. case Animation.ANIMATIONTYPE_QUATERNION:
  29267. var quaternion = null;
  29268. switch (loopMode) {
  29269. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29270. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29271. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29272. break;
  29273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29274. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29275. break;
  29276. }
  29277. return quaternion;
  29278. // Vector3
  29279. case Animation.ANIMATIONTYPE_VECTOR3:
  29280. switch (loopMode) {
  29281. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29282. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29283. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29284. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29285. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29286. }
  29287. // Vector2
  29288. case Animation.ANIMATIONTYPE_VECTOR2:
  29289. switch (loopMode) {
  29290. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29291. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29292. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29293. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29294. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29295. }
  29296. // Size
  29297. case Animation.ANIMATIONTYPE_SIZE:
  29298. switch (loopMode) {
  29299. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29300. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29301. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29302. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29303. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29304. }
  29305. // Color3
  29306. case Animation.ANIMATIONTYPE_COLOR3:
  29307. switch (loopMode) {
  29308. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29309. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29310. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29311. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29312. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29313. }
  29314. // Matrix
  29315. case Animation.ANIMATIONTYPE_MATRIX:
  29316. switch (loopMode) {
  29317. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29318. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29319. if (this.allowMatricesInterpolation) {
  29320. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29321. }
  29322. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29323. return startValue;
  29324. }
  29325. default:
  29326. break;
  29327. }
  29328. break;
  29329. }
  29330. }
  29331. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29332. };
  29333. Animation.prototype.setValue = function (currentValue, blend) {
  29334. if (blend === void 0) { blend = false; }
  29335. // Set value
  29336. var path;
  29337. var destination;
  29338. if (this.targetPropertyPath.length > 1) {
  29339. var property = this._target[this.targetPropertyPath[0]];
  29340. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29341. property = property[this.targetPropertyPath[index]];
  29342. }
  29343. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29344. destination = property;
  29345. }
  29346. else {
  29347. path = this.targetPropertyPath[0];
  29348. destination = this._target;
  29349. }
  29350. // Blending
  29351. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29352. if (!this._originalBlendValue) {
  29353. if (destination[path].clone) {
  29354. this._originalBlendValue = destination[path].clone();
  29355. }
  29356. else {
  29357. this._originalBlendValue = destination[path];
  29358. }
  29359. }
  29360. if (this._originalBlendValue.prototype) {
  29361. if (this._originalBlendValue.prototype.Lerp) {
  29362. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29363. }
  29364. else {
  29365. destination[path] = currentValue;
  29366. }
  29367. }
  29368. else if (this._originalBlendValue.m) {
  29369. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29370. }
  29371. else {
  29372. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29373. }
  29374. this._blendingFactor += this.blendingSpeed;
  29375. }
  29376. else {
  29377. destination[path] = currentValue;
  29378. }
  29379. if (this._target.markAsDirty) {
  29380. this._target.markAsDirty(this.targetProperty);
  29381. }
  29382. };
  29383. Animation.prototype.goToFrame = function (frame) {
  29384. if (frame < this._keys[0].frame) {
  29385. frame = this._keys[0].frame;
  29386. }
  29387. else if (frame > this._keys[this._keys.length - 1].frame) {
  29388. frame = this._keys[this._keys.length - 1].frame;
  29389. }
  29390. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29391. this.setValue(currentValue);
  29392. };
  29393. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29394. if (blend === void 0) { blend = false; }
  29395. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29396. this._stopped = true;
  29397. return false;
  29398. }
  29399. var returnValue = true;
  29400. // Adding a start key at frame 0 if missing
  29401. if (this._keys[0].frame !== 0) {
  29402. var newKey = { frame: 0, value: this._keys[0].value };
  29403. this._keys.splice(0, 0, newKey);
  29404. }
  29405. // Check limits
  29406. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29407. from = this._keys[0].frame;
  29408. }
  29409. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29410. to = this._keys[this._keys.length - 1].frame;
  29411. }
  29412. //to and from cannot be the same key
  29413. if (from === to) {
  29414. from++;
  29415. }
  29416. // Compute ratio
  29417. var range = to - from;
  29418. var offsetValue;
  29419. // ratio represents the frame delta between from and to
  29420. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29421. var highLimitValue = 0;
  29422. if (ratio > range && !loop) {
  29423. returnValue = false;
  29424. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29425. }
  29426. else {
  29427. // Get max value if required
  29428. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29429. var keyOffset = to.toString() + from.toString();
  29430. if (!this._offsetsCache[keyOffset]) {
  29431. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29432. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29433. switch (this.dataType) {
  29434. // Float
  29435. case Animation.ANIMATIONTYPE_FLOAT:
  29436. this._offsetsCache[keyOffset] = toValue - fromValue;
  29437. break;
  29438. // Quaternion
  29439. case Animation.ANIMATIONTYPE_QUATERNION:
  29440. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29441. break;
  29442. // Vector3
  29443. case Animation.ANIMATIONTYPE_VECTOR3:
  29444. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29445. // Vector2
  29446. case Animation.ANIMATIONTYPE_VECTOR2:
  29447. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29448. // Size
  29449. case Animation.ANIMATIONTYPE_SIZE:
  29450. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29451. // Color3
  29452. case Animation.ANIMATIONTYPE_COLOR3:
  29453. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29454. default:
  29455. break;
  29456. }
  29457. this._highLimitsCache[keyOffset] = toValue;
  29458. }
  29459. highLimitValue = this._highLimitsCache[keyOffset];
  29460. offsetValue = this._offsetsCache[keyOffset];
  29461. }
  29462. }
  29463. if (offsetValue === undefined) {
  29464. switch (this.dataType) {
  29465. // Float
  29466. case Animation.ANIMATIONTYPE_FLOAT:
  29467. offsetValue = 0;
  29468. break;
  29469. // Quaternion
  29470. case Animation.ANIMATIONTYPE_QUATERNION:
  29471. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29472. break;
  29473. // Vector3
  29474. case Animation.ANIMATIONTYPE_VECTOR3:
  29475. offsetValue = BABYLON.Vector3.Zero();
  29476. break;
  29477. // Vector2
  29478. case Animation.ANIMATIONTYPE_VECTOR2:
  29479. offsetValue = BABYLON.Vector2.Zero();
  29480. break;
  29481. // Size
  29482. case Animation.ANIMATIONTYPE_SIZE:
  29483. offsetValue = BABYLON.Size.Zero();
  29484. break;
  29485. // Color3
  29486. case Animation.ANIMATIONTYPE_COLOR3:
  29487. offsetValue = BABYLON.Color3.Black();
  29488. }
  29489. }
  29490. // Compute value
  29491. var repeatCount = (ratio / range) >> 0;
  29492. var currentFrame = returnValue ? from + ratio % range : to;
  29493. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29494. // Set value
  29495. this.setValue(currentValue);
  29496. // Check events
  29497. for (var index = 0; index < this._events.length; index++) {
  29498. if (currentFrame >= this._events[index].frame) {
  29499. var event = this._events[index];
  29500. if (!event.isDone) {
  29501. // If event should be done only once, remove it.
  29502. if (event.onlyOnce) {
  29503. this._events.splice(index, 1);
  29504. index--;
  29505. }
  29506. event.isDone = true;
  29507. event.action();
  29508. } // Don't do anything if the event has already be done.
  29509. }
  29510. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29511. // reset event, the animation is looping
  29512. this._events[index].isDone = false;
  29513. }
  29514. }
  29515. if (!returnValue) {
  29516. this._stopped = true;
  29517. }
  29518. return returnValue;
  29519. };
  29520. Animation.prototype.serialize = function () {
  29521. var serializationObject = {};
  29522. serializationObject.name = this.name;
  29523. serializationObject.property = this.targetProperty;
  29524. serializationObject.framePerSecond = this.framePerSecond;
  29525. serializationObject.dataType = this.dataType;
  29526. serializationObject.loopBehavior = this.loopMode;
  29527. var dataType = this.dataType;
  29528. serializationObject.keys = [];
  29529. var keys = this.getKeys();
  29530. for (var index = 0; index < keys.length; index++) {
  29531. var animationKey = keys[index];
  29532. var key = {};
  29533. key.frame = animationKey.frame;
  29534. switch (dataType) {
  29535. case Animation.ANIMATIONTYPE_FLOAT:
  29536. key.values = [animationKey.value];
  29537. break;
  29538. case Animation.ANIMATIONTYPE_QUATERNION:
  29539. case Animation.ANIMATIONTYPE_MATRIX:
  29540. case Animation.ANIMATIONTYPE_VECTOR3:
  29541. case Animation.ANIMATIONTYPE_COLOR3:
  29542. key.values = animationKey.value.asArray();
  29543. break;
  29544. }
  29545. serializationObject.keys.push(key);
  29546. }
  29547. serializationObject.ranges = [];
  29548. for (var name in this._ranges) {
  29549. var range = {};
  29550. range.name = name;
  29551. range.from = this._ranges[name].from;
  29552. range.to = this._ranges[name].to;
  29553. serializationObject.ranges.push(range);
  29554. }
  29555. return serializationObject;
  29556. };
  29557. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29558. get: function () {
  29559. return Animation._ANIMATIONTYPE_FLOAT;
  29560. },
  29561. enumerable: true,
  29562. configurable: true
  29563. });
  29564. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29565. get: function () {
  29566. return Animation._ANIMATIONTYPE_VECTOR3;
  29567. },
  29568. enumerable: true,
  29569. configurable: true
  29570. });
  29571. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29572. get: function () {
  29573. return Animation._ANIMATIONTYPE_VECTOR2;
  29574. },
  29575. enumerable: true,
  29576. configurable: true
  29577. });
  29578. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29579. get: function () {
  29580. return Animation._ANIMATIONTYPE_SIZE;
  29581. },
  29582. enumerable: true,
  29583. configurable: true
  29584. });
  29585. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29586. get: function () {
  29587. return Animation._ANIMATIONTYPE_QUATERNION;
  29588. },
  29589. enumerable: true,
  29590. configurable: true
  29591. });
  29592. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29593. get: function () {
  29594. return Animation._ANIMATIONTYPE_MATRIX;
  29595. },
  29596. enumerable: true,
  29597. configurable: true
  29598. });
  29599. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29600. get: function () {
  29601. return Animation._ANIMATIONTYPE_COLOR3;
  29602. },
  29603. enumerable: true,
  29604. configurable: true
  29605. });
  29606. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29607. get: function () {
  29608. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29609. },
  29610. enumerable: true,
  29611. configurable: true
  29612. });
  29613. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29614. get: function () {
  29615. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29616. },
  29617. enumerable: true,
  29618. configurable: true
  29619. });
  29620. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29621. get: function () {
  29622. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29623. },
  29624. enumerable: true,
  29625. configurable: true
  29626. });
  29627. Animation.Parse = function (parsedAnimation) {
  29628. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29629. var dataType = parsedAnimation.dataType;
  29630. var keys = [];
  29631. var data;
  29632. var index;
  29633. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29634. var key = parsedAnimation.keys[index];
  29635. switch (dataType) {
  29636. case Animation.ANIMATIONTYPE_FLOAT:
  29637. data = key.values[0];
  29638. break;
  29639. case Animation.ANIMATIONTYPE_QUATERNION:
  29640. data = BABYLON.Quaternion.FromArray(key.values);
  29641. break;
  29642. case Animation.ANIMATIONTYPE_MATRIX:
  29643. data = BABYLON.Matrix.FromArray(key.values);
  29644. break;
  29645. case Animation.ANIMATIONTYPE_COLOR3:
  29646. data = BABYLON.Color3.FromArray(key.values);
  29647. break;
  29648. case Animation.ANIMATIONTYPE_VECTOR3:
  29649. default:
  29650. data = BABYLON.Vector3.FromArray(key.values);
  29651. break;
  29652. }
  29653. keys.push({
  29654. frame: key.frame,
  29655. value: data
  29656. });
  29657. }
  29658. animation.setKeys(keys);
  29659. if (parsedAnimation.ranges) {
  29660. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29661. data = parsedAnimation.ranges[index];
  29662. animation.createRange(data.name, data.from, data.to);
  29663. }
  29664. }
  29665. return animation;
  29666. };
  29667. Animation.AppendSerializedAnimations = function (source, destination) {
  29668. if (source.animations) {
  29669. destination.animations = [];
  29670. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29671. var animation = source.animations[animationIndex];
  29672. destination.animations.push(animation.serialize());
  29673. }
  29674. }
  29675. };
  29676. // Statics
  29677. Animation._ANIMATIONTYPE_FLOAT = 0;
  29678. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29679. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29680. Animation._ANIMATIONTYPE_MATRIX = 3;
  29681. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29682. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29683. Animation._ANIMATIONTYPE_SIZE = 6;
  29684. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29685. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29686. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29687. return Animation;
  29688. }());
  29689. BABYLON.Animation = Animation;
  29690. })(BABYLON || (BABYLON = {}));
  29691. //# sourceMappingURL=babylon.animation.js.map
  29692. var BABYLON;
  29693. (function (BABYLON) {
  29694. var Animatable = (function () {
  29695. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29696. if (fromFrame === void 0) { fromFrame = 0; }
  29697. if (toFrame === void 0) { toFrame = 100; }
  29698. if (loopAnimation === void 0) { loopAnimation = false; }
  29699. if (speedRatio === void 0) { speedRatio = 1.0; }
  29700. this.target = target;
  29701. this.fromFrame = fromFrame;
  29702. this.toFrame = toFrame;
  29703. this.loopAnimation = loopAnimation;
  29704. this.speedRatio = speedRatio;
  29705. this.onAnimationEnd = onAnimationEnd;
  29706. this._animations = new Array();
  29707. this._paused = false;
  29708. this.animationStarted = false;
  29709. if (animations) {
  29710. this.appendAnimations(target, animations);
  29711. }
  29712. this._scene = scene;
  29713. scene._activeAnimatables.push(this);
  29714. }
  29715. // Methods
  29716. Animatable.prototype.getAnimations = function () {
  29717. return this._animations;
  29718. };
  29719. Animatable.prototype.appendAnimations = function (target, animations) {
  29720. for (var index = 0; index < animations.length; index++) {
  29721. var animation = animations[index];
  29722. animation._target = target;
  29723. this._animations.push(animation);
  29724. }
  29725. };
  29726. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29727. var animations = this._animations;
  29728. for (var index = 0; index < animations.length; index++) {
  29729. if (animations[index].targetProperty === property) {
  29730. return animations[index];
  29731. }
  29732. }
  29733. return null;
  29734. };
  29735. Animatable.prototype.reset = function () {
  29736. var animations = this._animations;
  29737. for (var index = 0; index < animations.length; index++) {
  29738. animations[index].reset();
  29739. }
  29740. this._localDelayOffset = null;
  29741. this._pausedDelay = null;
  29742. };
  29743. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29744. var animations = this._animations;
  29745. for (var index = 0; index < animations.length; index++) {
  29746. animations[index].enableBlending = true;
  29747. animations[index].blendingSpeed = blendingSpeed;
  29748. }
  29749. };
  29750. Animatable.prototype.disableBlending = function () {
  29751. var animations = this._animations;
  29752. for (var index = 0; index < animations.length; index++) {
  29753. animations[index].enableBlending = false;
  29754. }
  29755. };
  29756. Animatable.prototype.goToFrame = function (frame) {
  29757. var animations = this._animations;
  29758. if (animations[0]) {
  29759. var fps = animations[0].framePerSecond;
  29760. var currentFrame = animations[0].currentFrame;
  29761. var adjustTime = frame - currentFrame;
  29762. var delay = adjustTime * 1000 / fps;
  29763. this._localDelayOffset -= delay;
  29764. }
  29765. for (var index = 0; index < animations.length; index++) {
  29766. animations[index].goToFrame(frame);
  29767. }
  29768. };
  29769. Animatable.prototype.pause = function () {
  29770. if (this._paused) {
  29771. return;
  29772. }
  29773. this._paused = true;
  29774. };
  29775. Animatable.prototype.restart = function () {
  29776. this._paused = false;
  29777. };
  29778. Animatable.prototype.stop = function (animationName) {
  29779. var index = this._scene._activeAnimatables.indexOf(this);
  29780. if (index > -1) {
  29781. var animations = this._animations;
  29782. var numberOfAnimationsStopped = 0;
  29783. for (var index = animations.length - 1; index >= 0; index--) {
  29784. if (typeof animationName === "string" && animations[index].name != animationName) {
  29785. continue;
  29786. }
  29787. animations[index].reset();
  29788. animations.splice(index, 1);
  29789. numberOfAnimationsStopped++;
  29790. }
  29791. if (animations.length == numberOfAnimationsStopped) {
  29792. this._scene._activeAnimatables.splice(index, 1);
  29793. if (this.onAnimationEnd) {
  29794. this.onAnimationEnd();
  29795. }
  29796. }
  29797. }
  29798. };
  29799. Animatable.prototype._animate = function (delay) {
  29800. if (this._paused) {
  29801. this.animationStarted = false;
  29802. if (!this._pausedDelay) {
  29803. this._pausedDelay = delay;
  29804. }
  29805. return true;
  29806. }
  29807. if (!this._localDelayOffset) {
  29808. this._localDelayOffset = delay;
  29809. }
  29810. else if (this._pausedDelay) {
  29811. this._localDelayOffset += delay - this._pausedDelay;
  29812. this._pausedDelay = null;
  29813. }
  29814. // Animating
  29815. var running = false;
  29816. var animations = this._animations;
  29817. var index;
  29818. for (index = 0; index < animations.length; index++) {
  29819. var animation = animations[index];
  29820. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29821. running = running || isRunning;
  29822. }
  29823. this.animationStarted = running;
  29824. if (!running) {
  29825. // Remove from active animatables
  29826. index = this._scene._activeAnimatables.indexOf(this);
  29827. this._scene._activeAnimatables.splice(index, 1);
  29828. }
  29829. if (!running && this.onAnimationEnd) {
  29830. this.onAnimationEnd();
  29831. this.onAnimationEnd = null;
  29832. }
  29833. return running;
  29834. };
  29835. return Animatable;
  29836. }());
  29837. BABYLON.Animatable = Animatable;
  29838. })(BABYLON || (BABYLON = {}));
  29839. //# sourceMappingURL=babylon.animatable.js.map
  29840. var BABYLON;
  29841. (function (BABYLON) {
  29842. var EasingFunction = (function () {
  29843. function EasingFunction() {
  29844. // Properties
  29845. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29846. }
  29847. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29848. get: function () {
  29849. return EasingFunction._EASINGMODE_EASEIN;
  29850. },
  29851. enumerable: true,
  29852. configurable: true
  29853. });
  29854. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29855. get: function () {
  29856. return EasingFunction._EASINGMODE_EASEOUT;
  29857. },
  29858. enumerable: true,
  29859. configurable: true
  29860. });
  29861. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29862. get: function () {
  29863. return EasingFunction._EASINGMODE_EASEINOUT;
  29864. },
  29865. enumerable: true,
  29866. configurable: true
  29867. });
  29868. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29869. var n = Math.min(Math.max(easingMode, 0), 2);
  29870. this._easingMode = n;
  29871. };
  29872. EasingFunction.prototype.getEasingMode = function () {
  29873. return this._easingMode;
  29874. };
  29875. EasingFunction.prototype.easeInCore = function (gradient) {
  29876. throw new Error('You must implement this method');
  29877. };
  29878. EasingFunction.prototype.ease = function (gradient) {
  29879. switch (this._easingMode) {
  29880. case EasingFunction.EASINGMODE_EASEIN:
  29881. return this.easeInCore(gradient);
  29882. case EasingFunction.EASINGMODE_EASEOUT:
  29883. return (1 - this.easeInCore(1 - gradient));
  29884. }
  29885. if (gradient >= 0.5) {
  29886. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29887. }
  29888. return (this.easeInCore(gradient * 2) * 0.5);
  29889. };
  29890. //Statics
  29891. EasingFunction._EASINGMODE_EASEIN = 0;
  29892. EasingFunction._EASINGMODE_EASEOUT = 1;
  29893. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29894. return EasingFunction;
  29895. }());
  29896. BABYLON.EasingFunction = EasingFunction;
  29897. var CircleEase = (function (_super) {
  29898. __extends(CircleEase, _super);
  29899. function CircleEase() {
  29900. _super.apply(this, arguments);
  29901. }
  29902. CircleEase.prototype.easeInCore = function (gradient) {
  29903. gradient = Math.max(0, Math.min(1, gradient));
  29904. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29905. };
  29906. return CircleEase;
  29907. }(EasingFunction));
  29908. BABYLON.CircleEase = CircleEase;
  29909. var BackEase = (function (_super) {
  29910. __extends(BackEase, _super);
  29911. function BackEase(amplitude) {
  29912. if (amplitude === void 0) { amplitude = 1; }
  29913. _super.call(this);
  29914. this.amplitude = amplitude;
  29915. }
  29916. BackEase.prototype.easeInCore = function (gradient) {
  29917. var num = Math.max(0, this.amplitude);
  29918. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29919. };
  29920. return BackEase;
  29921. }(EasingFunction));
  29922. BABYLON.BackEase = BackEase;
  29923. var BounceEase = (function (_super) {
  29924. __extends(BounceEase, _super);
  29925. function BounceEase(bounces, bounciness) {
  29926. if (bounces === void 0) { bounces = 3; }
  29927. if (bounciness === void 0) { bounciness = 2; }
  29928. _super.call(this);
  29929. this.bounces = bounces;
  29930. this.bounciness = bounciness;
  29931. }
  29932. BounceEase.prototype.easeInCore = function (gradient) {
  29933. var y = Math.max(0.0, this.bounces);
  29934. var bounciness = this.bounciness;
  29935. if (bounciness <= 1.0) {
  29936. bounciness = 1.001;
  29937. }
  29938. var num9 = Math.pow(bounciness, y);
  29939. var num5 = 1.0 - bounciness;
  29940. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29941. var num15 = gradient * num4;
  29942. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29943. var num3 = Math.floor(num65);
  29944. var num13 = num3 + 1.0;
  29945. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29946. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29947. var num7 = (num8 + num12) * 0.5;
  29948. var num6 = gradient - num7;
  29949. var num2 = num7 - num8;
  29950. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29951. };
  29952. return BounceEase;
  29953. }(EasingFunction));
  29954. BABYLON.BounceEase = BounceEase;
  29955. var CubicEase = (function (_super) {
  29956. __extends(CubicEase, _super);
  29957. function CubicEase() {
  29958. _super.apply(this, arguments);
  29959. }
  29960. CubicEase.prototype.easeInCore = function (gradient) {
  29961. return (gradient * gradient * gradient);
  29962. };
  29963. return CubicEase;
  29964. }(EasingFunction));
  29965. BABYLON.CubicEase = CubicEase;
  29966. var ElasticEase = (function (_super) {
  29967. __extends(ElasticEase, _super);
  29968. function ElasticEase(oscillations, springiness) {
  29969. if (oscillations === void 0) { oscillations = 3; }
  29970. if (springiness === void 0) { springiness = 3; }
  29971. _super.call(this);
  29972. this.oscillations = oscillations;
  29973. this.springiness = springiness;
  29974. }
  29975. ElasticEase.prototype.easeInCore = function (gradient) {
  29976. var num2;
  29977. var num3 = Math.max(0.0, this.oscillations);
  29978. var num = Math.max(0.0, this.springiness);
  29979. if (num == 0) {
  29980. num2 = gradient;
  29981. }
  29982. else {
  29983. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29984. }
  29985. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29986. };
  29987. return ElasticEase;
  29988. }(EasingFunction));
  29989. BABYLON.ElasticEase = ElasticEase;
  29990. var ExponentialEase = (function (_super) {
  29991. __extends(ExponentialEase, _super);
  29992. function ExponentialEase(exponent) {
  29993. if (exponent === void 0) { exponent = 2; }
  29994. _super.call(this);
  29995. this.exponent = exponent;
  29996. }
  29997. ExponentialEase.prototype.easeInCore = function (gradient) {
  29998. if (this.exponent <= 0) {
  29999. return gradient;
  30000. }
  30001. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30002. };
  30003. return ExponentialEase;
  30004. }(EasingFunction));
  30005. BABYLON.ExponentialEase = ExponentialEase;
  30006. var PowerEase = (function (_super) {
  30007. __extends(PowerEase, _super);
  30008. function PowerEase(power) {
  30009. if (power === void 0) { power = 2; }
  30010. _super.call(this);
  30011. this.power = power;
  30012. }
  30013. PowerEase.prototype.easeInCore = function (gradient) {
  30014. var y = Math.max(0.0, this.power);
  30015. return Math.pow(gradient, y);
  30016. };
  30017. return PowerEase;
  30018. }(EasingFunction));
  30019. BABYLON.PowerEase = PowerEase;
  30020. var QuadraticEase = (function (_super) {
  30021. __extends(QuadraticEase, _super);
  30022. function QuadraticEase() {
  30023. _super.apply(this, arguments);
  30024. }
  30025. QuadraticEase.prototype.easeInCore = function (gradient) {
  30026. return (gradient * gradient);
  30027. };
  30028. return QuadraticEase;
  30029. }(EasingFunction));
  30030. BABYLON.QuadraticEase = QuadraticEase;
  30031. var QuarticEase = (function (_super) {
  30032. __extends(QuarticEase, _super);
  30033. function QuarticEase() {
  30034. _super.apply(this, arguments);
  30035. }
  30036. QuarticEase.prototype.easeInCore = function (gradient) {
  30037. return (gradient * gradient * gradient * gradient);
  30038. };
  30039. return QuarticEase;
  30040. }(EasingFunction));
  30041. BABYLON.QuarticEase = QuarticEase;
  30042. var QuinticEase = (function (_super) {
  30043. __extends(QuinticEase, _super);
  30044. function QuinticEase() {
  30045. _super.apply(this, arguments);
  30046. }
  30047. QuinticEase.prototype.easeInCore = function (gradient) {
  30048. return (gradient * gradient * gradient * gradient * gradient);
  30049. };
  30050. return QuinticEase;
  30051. }(EasingFunction));
  30052. BABYLON.QuinticEase = QuinticEase;
  30053. var SineEase = (function (_super) {
  30054. __extends(SineEase, _super);
  30055. function SineEase() {
  30056. _super.apply(this, arguments);
  30057. }
  30058. SineEase.prototype.easeInCore = function (gradient) {
  30059. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30060. };
  30061. return SineEase;
  30062. }(EasingFunction));
  30063. BABYLON.SineEase = SineEase;
  30064. var BezierCurveEase = (function (_super) {
  30065. __extends(BezierCurveEase, _super);
  30066. function BezierCurveEase(x1, y1, x2, y2) {
  30067. if (x1 === void 0) { x1 = 0; }
  30068. if (y1 === void 0) { y1 = 0; }
  30069. if (x2 === void 0) { x2 = 1; }
  30070. if (y2 === void 0) { y2 = 1; }
  30071. _super.call(this);
  30072. this.x1 = x1;
  30073. this.y1 = y1;
  30074. this.x2 = x2;
  30075. this.y2 = y2;
  30076. }
  30077. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30078. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30079. };
  30080. return BezierCurveEase;
  30081. }(EasingFunction));
  30082. BABYLON.BezierCurveEase = BezierCurveEase;
  30083. })(BABYLON || (BABYLON = {}));
  30084. //# sourceMappingURL=babylon.easing.js.map
  30085. var BABYLON;
  30086. (function (BABYLON) {
  30087. var Bone = (function (_super) {
  30088. __extends(Bone, _super);
  30089. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30090. _super.call(this, name, skeleton.getScene());
  30091. this.name = name;
  30092. this.children = new Array();
  30093. this.animations = new Array();
  30094. this._worldTransform = new BABYLON.Matrix();
  30095. this._absoluteTransform = new BABYLON.Matrix();
  30096. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30097. this._scaleMatrix = BABYLON.Matrix.Identity();
  30098. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30099. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30100. this._scalingDeterminant = 1;
  30101. this._syncScaleVector = function () {
  30102. var lm = this.getLocalMatrix();
  30103. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30104. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30105. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30106. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30107. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30108. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30109. this._scaleVector.x = xs * Math.sqrt(xsq);
  30110. this._scaleVector.y = ys * Math.sqrt(ysq);
  30111. this._scaleVector.z = zs * Math.sqrt(zsq);
  30112. if (this._parent) {
  30113. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30114. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30115. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30116. }
  30117. 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);
  30118. };
  30119. this._skeleton = skeleton;
  30120. this._matrix = matrix;
  30121. this._baseMatrix = matrix;
  30122. this._restPose = restPose ? restPose : matrix.clone();
  30123. skeleton.bones.push(this);
  30124. if (parentBone) {
  30125. this._parent = parentBone;
  30126. parentBone.children.push(this);
  30127. }
  30128. else {
  30129. this._parent = null;
  30130. }
  30131. this._updateDifferenceMatrix();
  30132. if (this.getAbsoluteTransform().determinant() < 0) {
  30133. this._scalingDeterminant *= -1;
  30134. }
  30135. }
  30136. // Members
  30137. Bone.prototype.getParent = function () {
  30138. return this._parent;
  30139. };
  30140. Bone.prototype.getLocalMatrix = function () {
  30141. return this._matrix;
  30142. };
  30143. Bone.prototype.getBaseMatrix = function () {
  30144. return this._baseMatrix;
  30145. };
  30146. Bone.prototype.getRestPose = function () {
  30147. return this._restPose;
  30148. };
  30149. Bone.prototype.returnToRest = function () {
  30150. this.updateMatrix(this._restPose.clone());
  30151. };
  30152. Bone.prototype.getWorldMatrix = function () {
  30153. return this._worldTransform;
  30154. };
  30155. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30156. return this._invertedAbsoluteTransform;
  30157. };
  30158. Bone.prototype.getAbsoluteTransform = function () {
  30159. return this._absoluteTransform;
  30160. };
  30161. // Methods
  30162. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30163. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30164. this._baseMatrix = matrix.clone();
  30165. this._matrix = matrix.clone();
  30166. this._skeleton._markAsDirty();
  30167. if (updateDifferenceMatrix) {
  30168. this._updateDifferenceMatrix();
  30169. }
  30170. };
  30171. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30172. if (!rootMatrix) {
  30173. rootMatrix = this._baseMatrix;
  30174. }
  30175. if (this._parent) {
  30176. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30177. }
  30178. else {
  30179. this._absoluteTransform.copyFrom(rootMatrix);
  30180. }
  30181. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30182. for (var index = 0; index < this.children.length; index++) {
  30183. this.children[index]._updateDifferenceMatrix();
  30184. }
  30185. };
  30186. Bone.prototype.markAsDirty = function () {
  30187. this._currentRenderId++;
  30188. this._skeleton._markAsDirty();
  30189. };
  30190. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30191. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30192. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30193. // all animation may be coming from a library skeleton, so may need to create animation
  30194. if (this.animations.length === 0) {
  30195. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30196. this.animations[0].setKeys([]);
  30197. }
  30198. // get animation info / verify there is such a range from the source bone
  30199. var sourceRange = source.animations[0].getRange(rangeName);
  30200. if (!sourceRange) {
  30201. return false;
  30202. }
  30203. var from = sourceRange.from;
  30204. var to = sourceRange.to;
  30205. var sourceKeys = source.animations[0].getKeys();
  30206. // rescaling prep
  30207. var sourceBoneLength = source.length;
  30208. var sourceParent = source.getParent();
  30209. var parent = this.getParent();
  30210. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30211. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30212. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30213. var destKeys = this.animations[0].getKeys();
  30214. // loop vars declaration
  30215. var orig;
  30216. var origTranslation;
  30217. var mat;
  30218. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30219. orig = sourceKeys[key];
  30220. if (orig.frame >= from && orig.frame <= to) {
  30221. if (rescaleAsRequired) {
  30222. mat = orig.value.clone();
  30223. // scale based on parent ratio, when bone has parent
  30224. if (parentScalingReqd) {
  30225. origTranslation = mat.getTranslation();
  30226. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30227. }
  30228. else if (dimensionsScalingReqd) {
  30229. origTranslation = mat.getTranslation();
  30230. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30231. }
  30232. else {
  30233. mat = orig.value;
  30234. }
  30235. }
  30236. else {
  30237. mat = orig.value;
  30238. }
  30239. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30240. }
  30241. }
  30242. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30243. return true;
  30244. };
  30245. Bone.prototype.translate = function (vec, space, mesh) {
  30246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30247. var lm = this.getLocalMatrix();
  30248. if (space == BABYLON.Space.LOCAL) {
  30249. lm.m[12] += vec.x;
  30250. lm.m[13] += vec.y;
  30251. lm.m[14] += vec.z;
  30252. }
  30253. else {
  30254. this._skeleton.computeAbsoluteTransforms();
  30255. var tmat = BABYLON.Tmp.Matrix[0];
  30256. var tvec = BABYLON.Tmp.Vector3[0];
  30257. if (mesh) {
  30258. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30259. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30260. }
  30261. else {
  30262. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30263. }
  30264. tmat.m[12] = 0;
  30265. tmat.m[13] = 0;
  30266. tmat.m[14] = 0;
  30267. tmat.invert();
  30268. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30269. lm.m[12] += tvec.x;
  30270. lm.m[13] += tvec.y;
  30271. lm.m[14] += tvec.z;
  30272. }
  30273. this.markAsDirty();
  30274. };
  30275. Bone.prototype.setPosition = function (position, space, mesh) {
  30276. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30277. var lm = this.getLocalMatrix();
  30278. if (space == BABYLON.Space.LOCAL) {
  30279. lm.m[12] = position.x;
  30280. lm.m[13] = position.y;
  30281. lm.m[14] = position.z;
  30282. }
  30283. else {
  30284. this._skeleton.computeAbsoluteTransforms();
  30285. var tmat = BABYLON.Tmp.Matrix[0];
  30286. var vec = BABYLON.Tmp.Vector3[0];
  30287. if (mesh) {
  30288. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30289. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30290. }
  30291. else {
  30292. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30293. }
  30294. tmat.invert();
  30295. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30296. lm.m[12] = vec.x;
  30297. lm.m[13] = vec.y;
  30298. lm.m[14] = vec.z;
  30299. }
  30300. this.markAsDirty();
  30301. };
  30302. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30303. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30304. };
  30305. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30306. if (scaleChildren === void 0) { scaleChildren = false; }
  30307. if (this.animations[0] && !this.animations[0].isStopped()) {
  30308. if (!scaleChildren) {
  30309. this._negateScaleChildren.x = 1 / x;
  30310. this._negateScaleChildren.y = 1 / y;
  30311. this._negateScaleChildren.z = 1 / z;
  30312. }
  30313. this._syncScaleVector();
  30314. }
  30315. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30316. };
  30317. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30318. if (scaleChildren === void 0) { scaleChildren = false; }
  30319. var locMat = this.getLocalMatrix();
  30320. var origLocMat = BABYLON.Tmp.Matrix[0];
  30321. origLocMat.copyFrom(locMat);
  30322. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30323. origLocMatInv.copyFrom(origLocMat);
  30324. origLocMatInv.invert();
  30325. var scaleMat = BABYLON.Tmp.Matrix[2];
  30326. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30327. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30328. this._scaleVector.x *= x;
  30329. this._scaleVector.y *= y;
  30330. this._scaleVector.z *= z;
  30331. locMat.multiplyToRef(origLocMatInv, locMat);
  30332. locMat.multiplyToRef(scaleMat, locMat);
  30333. locMat.multiplyToRef(origLocMat, locMat);
  30334. var parent = this.getParent();
  30335. if (parent) {
  30336. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30337. }
  30338. else {
  30339. this.getAbsoluteTransform().copyFrom(locMat);
  30340. }
  30341. var len = this.children.length;
  30342. scaleMat.invert();
  30343. for (var i = 0; i < len; i++) {
  30344. var child = this.children[i];
  30345. var cm = child.getLocalMatrix();
  30346. cm.multiplyToRef(scaleMat, cm);
  30347. var lm = child.getLocalMatrix();
  30348. lm.m[12] *= x;
  30349. lm.m[13] *= y;
  30350. lm.m[14] *= z;
  30351. }
  30352. this.computeAbsoluteTransforms();
  30353. if (scaleChildren) {
  30354. for (var i = 0; i < len; i++) {
  30355. this.children[i].scale(x, y, z, scaleChildren);
  30356. }
  30357. }
  30358. this.markAsDirty();
  30359. };
  30360. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30362. var rotMat = BABYLON.Tmp.Matrix[0];
  30363. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30364. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30365. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30366. rotMatInv.multiplyToRef(rotMat, rotMat);
  30367. this._rotateWithMatrix(rotMat, space, mesh);
  30368. };
  30369. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30370. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30371. var rmat = BABYLON.Tmp.Matrix[0];
  30372. rmat.m[12] = 0;
  30373. rmat.m[13] = 0;
  30374. rmat.m[14] = 0;
  30375. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30376. this._rotateWithMatrix(rmat, space, mesh);
  30377. };
  30378. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30380. var rotMat = BABYLON.Tmp.Matrix[0];
  30381. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30382. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30383. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30384. rotMatInv.multiplyToRef(rotMat, rotMat);
  30385. this._rotateWithMatrix(rotMat, space, mesh);
  30386. };
  30387. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30388. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30389. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30390. };
  30391. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30393. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30394. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30395. var rotMat = BABYLON.Tmp.Matrix[1];
  30396. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30397. rotMatInv.multiplyToRef(rotMat, rotMat);
  30398. this._rotateWithMatrix(rotMat, space, mesh);
  30399. };
  30400. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30401. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30402. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30403. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30404. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30405. rotMat2.copyFrom(rotMat);
  30406. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30407. this._rotateWithMatrix(rotMat2, space, mesh);
  30408. };
  30409. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30411. var lmat = this.getLocalMatrix();
  30412. var lx = lmat.m[12];
  30413. var ly = lmat.m[13];
  30414. var lz = lmat.m[14];
  30415. var parent = this.getParent();
  30416. var parentScale = BABYLON.Tmp.Matrix[3];
  30417. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30418. if (parent) {
  30419. if (space == BABYLON.Space.WORLD) {
  30420. if (mesh) {
  30421. parentScale.copyFrom(mesh.getWorldMatrix());
  30422. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30423. }
  30424. else {
  30425. parentScale.copyFrom(parent.getAbsoluteTransform());
  30426. }
  30427. }
  30428. else {
  30429. parentScale = parent._scaleMatrix;
  30430. }
  30431. parentScaleInv.copyFrom(parentScale);
  30432. parentScaleInv.invert();
  30433. lmat.multiplyToRef(parentScale, lmat);
  30434. lmat.multiplyToRef(rmat, lmat);
  30435. lmat.multiplyToRef(parentScaleInv, lmat);
  30436. }
  30437. else {
  30438. if (space == BABYLON.Space.WORLD && mesh) {
  30439. parentScale.copyFrom(mesh.getWorldMatrix());
  30440. parentScaleInv.copyFrom(parentScale);
  30441. parentScaleInv.invert();
  30442. lmat.multiplyToRef(parentScale, lmat);
  30443. lmat.multiplyToRef(rmat, lmat);
  30444. lmat.multiplyToRef(parentScaleInv, lmat);
  30445. }
  30446. else {
  30447. lmat.multiplyToRef(rmat, lmat);
  30448. }
  30449. }
  30450. lmat.m[12] = lx;
  30451. lmat.m[13] = ly;
  30452. lmat.m[14] = lz;
  30453. this.computeAbsoluteTransforms();
  30454. this.markAsDirty();
  30455. };
  30456. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30457. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30458. if (space == BABYLON.Space.WORLD) {
  30459. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30460. scaleMatrix.copyFrom(this._scaleMatrix);
  30461. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30462. if (mesh) {
  30463. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30464. var meshScale = BABYLON.Tmp.Matrix[3];
  30465. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30466. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30467. }
  30468. rotMatInv.invert();
  30469. scaleMatrix.m[0] *= this._scalingDeterminant;
  30470. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30471. }
  30472. else {
  30473. rotMatInv.copyFrom(this.getLocalMatrix());
  30474. rotMatInv.invert();
  30475. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30476. scaleMatrix.copyFrom(this._scaleMatrix);
  30477. if (this._parent) {
  30478. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30479. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30480. pscaleMatrix.invert();
  30481. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30482. }
  30483. else {
  30484. scaleMatrix.m[0] *= this._scalingDeterminant;
  30485. }
  30486. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30487. }
  30488. };
  30489. Bone.prototype.getScale = function () {
  30490. return this._scaleVector.clone();
  30491. };
  30492. Bone.prototype.getScaleToRef = function (result) {
  30493. result.copyFrom(this._scaleVector);
  30494. };
  30495. Bone.prototype.getPosition = function (space, mesh) {
  30496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30497. var pos = BABYLON.Vector3.Zero();
  30498. this.getPositionToRef(space, mesh, pos);
  30499. return pos;
  30500. };
  30501. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30503. if (space == BABYLON.Space.LOCAL) {
  30504. var lm = this.getLocalMatrix();
  30505. result.x = lm.m[12];
  30506. result.y = lm.m[13];
  30507. result.z = lm.m[14];
  30508. }
  30509. else {
  30510. this._skeleton.computeAbsoluteTransforms();
  30511. var tmat = BABYLON.Tmp.Matrix[0];
  30512. if (mesh) {
  30513. tmat.copyFrom(this.getAbsoluteTransform());
  30514. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30515. }
  30516. else {
  30517. tmat = this.getAbsoluteTransform();
  30518. }
  30519. result.x = tmat.m[12];
  30520. result.y = tmat.m[13];
  30521. result.z = tmat.m[14];
  30522. }
  30523. };
  30524. Bone.prototype.getAbsolutePosition = function (mesh) {
  30525. var pos = BABYLON.Vector3.Zero();
  30526. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30527. return pos;
  30528. };
  30529. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30530. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30531. };
  30532. Bone.prototype.computeAbsoluteTransforms = function () {
  30533. if (this._parent) {
  30534. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30535. }
  30536. else {
  30537. this._absoluteTransform.copyFrom(this._matrix);
  30538. var poseMatrix = this._skeleton.getPoseMatrix();
  30539. if (poseMatrix) {
  30540. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30541. }
  30542. }
  30543. var children = this.children;
  30544. var len = children.length;
  30545. for (var i = 0; i < len; i++) {
  30546. children[i].computeAbsoluteTransforms();
  30547. }
  30548. };
  30549. Bone.prototype.getDirection = function (localAxis, mesh) {
  30550. var result = BABYLON.Vector3.Zero();
  30551. this.getDirectionToRef(localAxis, mesh, result);
  30552. return result;
  30553. };
  30554. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30555. this._skeleton.computeAbsoluteTransforms();
  30556. var mat = BABYLON.Tmp.Matrix[0];
  30557. mat.copyFrom(this.getAbsoluteTransform());
  30558. if (mesh) {
  30559. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30560. }
  30561. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30562. result.normalize();
  30563. };
  30564. Bone.prototype.getRotation = function (space, mesh) {
  30565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30566. var result = BABYLON.Vector3.Zero();
  30567. this.getRotationToRef(space, mesh, result);
  30568. return result;
  30569. };
  30570. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30572. var quat = BABYLON.Tmp.Quaternion[0];
  30573. this.getRotationQuaternionToRef(space, mesh, quat);
  30574. quat.toEulerAnglesToRef(result);
  30575. };
  30576. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30577. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30578. var result = BABYLON.Quaternion.Identity();
  30579. this.getRotationQuaternionToRef(space, mesh, result);
  30580. return result;
  30581. };
  30582. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30584. if (space == BABYLON.Space.LOCAL) {
  30585. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30586. }
  30587. else {
  30588. var mat = BABYLON.Tmp.Matrix[0];
  30589. var amat = this.getAbsoluteTransform();
  30590. if (mesh) {
  30591. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30592. }
  30593. else {
  30594. mat.copyFrom(amat);
  30595. }
  30596. mat.m[0] *= this._scalingDeterminant;
  30597. mat.m[1] *= this._scalingDeterminant;
  30598. mat.m[2] *= this._scalingDeterminant;
  30599. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30600. }
  30601. };
  30602. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30604. var result = BABYLON.Matrix.Identity();
  30605. this.getRotationMatrixToRef(space, mesh, result);
  30606. return result;
  30607. };
  30608. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30610. if (space == BABYLON.Space.LOCAL) {
  30611. this.getLocalMatrix().getRotationMatrixToRef(result);
  30612. }
  30613. else {
  30614. var mat = BABYLON.Tmp.Matrix[0];
  30615. var amat = this.getAbsoluteTransform();
  30616. if (mesh) {
  30617. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30618. }
  30619. else {
  30620. mat.copyFrom(amat);
  30621. }
  30622. mat.m[0] *= this._scalingDeterminant;
  30623. mat.m[1] *= this._scalingDeterminant;
  30624. mat.m[2] *= this._scalingDeterminant;
  30625. mat.getRotationMatrixToRef(result);
  30626. }
  30627. };
  30628. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30629. var result = BABYLON.Vector3.Zero();
  30630. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30631. return result;
  30632. };
  30633. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30634. this._skeleton.computeAbsoluteTransforms();
  30635. var tmat = BABYLON.Tmp.Matrix[0];
  30636. if (mesh) {
  30637. tmat.copyFrom(this.getAbsoluteTransform());
  30638. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30639. }
  30640. else {
  30641. tmat = this.getAbsoluteTransform();
  30642. }
  30643. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30644. };
  30645. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30646. var result = BABYLON.Vector3.Zero();
  30647. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30648. return result;
  30649. };
  30650. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30651. this._skeleton.computeAbsoluteTransforms();
  30652. var tmat = BABYLON.Tmp.Matrix[0];
  30653. tmat.copyFrom(this.getAbsoluteTransform());
  30654. if (mesh) {
  30655. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30656. }
  30657. tmat.invert();
  30658. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30659. };
  30660. return Bone;
  30661. }(BABYLON.Node));
  30662. BABYLON.Bone = Bone;
  30663. })(BABYLON || (BABYLON = {}));
  30664. //# sourceMappingURL=babylon.bone.js.map
  30665. var BABYLON;
  30666. (function (BABYLON) {
  30667. var BoneIKController = (function () {
  30668. function BoneIKController(mesh, bone, options) {
  30669. this.targetPosition = BABYLON.Vector3.Zero();
  30670. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30671. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30672. this.poleAngle = 0;
  30673. this.slerpAmount = 1;
  30674. this._bone1Quat = BABYLON.Quaternion.Identity();
  30675. this._bone1Mat = BABYLON.Matrix.Identity();
  30676. this._bone2Ang = Math.PI;
  30677. this._maxAngle = Math.PI;
  30678. this._tmpVec1 = BABYLON.Vector3.Zero();
  30679. this._tmpVec2 = BABYLON.Vector3.Zero();
  30680. this._tmpVec3 = BABYLON.Vector3.Zero();
  30681. this._tmpVec4 = BABYLON.Vector3.Zero();
  30682. this._tmpVec5 = BABYLON.Vector3.Zero();
  30683. this._tmpMat1 = BABYLON.Matrix.Identity();
  30684. this._tmpMat2 = BABYLON.Matrix.Identity();
  30685. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30686. this._rightHandedSystem = false;
  30687. this._bendAxis = BABYLON.Vector3.Right();
  30688. this._slerping = false;
  30689. this._bone2 = bone;
  30690. this._bone1 = bone.getParent();
  30691. this.mesh = mesh;
  30692. if (bone.getAbsoluteTransform().determinant() > 0) {
  30693. this._rightHandedSystem = true;
  30694. this._bendAxis.x = 0;
  30695. this._bendAxis.y = 0;
  30696. this._bendAxis.z = 1;
  30697. }
  30698. if (this._bone1.length) {
  30699. var boneScale1 = this._bone1.getScale();
  30700. var boneScale2 = this._bone2.getScale();
  30701. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30702. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30703. }
  30704. else if (this._bone1.children[0]) {
  30705. mesh.computeWorldMatrix(true);
  30706. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30707. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30708. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30709. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30710. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30711. }
  30712. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30713. this.maxAngle = Math.PI;
  30714. if (options) {
  30715. if (options.targetMesh) {
  30716. this.targetMesh = options.targetMesh;
  30717. this.targetMesh.computeWorldMatrix(true);
  30718. }
  30719. if (options.poleTargetMesh) {
  30720. this.poleTargetMesh = options.poleTargetMesh;
  30721. this.poleTargetMesh.computeWorldMatrix(true);
  30722. }
  30723. else if (options.poleTargetBone) {
  30724. this.poleTargetBone = options.poleTargetBone;
  30725. }
  30726. else if (this._bone1.getParent()) {
  30727. this.poleTargetBone = this._bone1.getParent();
  30728. }
  30729. if (options.poleTargetLocalOffset) {
  30730. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30731. }
  30732. if (options.poleAngle) {
  30733. this.poleAngle = options.poleAngle;
  30734. }
  30735. if (options.bendAxis) {
  30736. this._bendAxis.copyFrom(options.bendAxis);
  30737. }
  30738. if (options.maxAngle) {
  30739. this.maxAngle = options.maxAngle;
  30740. }
  30741. if (options.slerpAmount) {
  30742. this.slerpAmount = options.slerpAmount;
  30743. }
  30744. }
  30745. }
  30746. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30747. get: function () {
  30748. return this._maxAngle;
  30749. },
  30750. set: function (value) {
  30751. this._setMaxAngle(value);
  30752. },
  30753. enumerable: true,
  30754. configurable: true
  30755. });
  30756. BoneIKController.prototype._setMaxAngle = function (ang) {
  30757. if (ang < 0) {
  30758. ang = 0;
  30759. }
  30760. if (ang > Math.PI || ang == undefined) {
  30761. ang = Math.PI;
  30762. }
  30763. this._maxAngle = ang;
  30764. var a = this._bone1Length;
  30765. var b = this._bone2Length;
  30766. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30767. };
  30768. BoneIKController.prototype.update = function () {
  30769. var bone1 = this._bone1;
  30770. var target = this.targetPosition;
  30771. var poleTarget = this.poleTargetPosition;
  30772. var mat1 = this._tmpMat1;
  30773. var mat2 = this._tmpMat2;
  30774. if (this.targetMesh) {
  30775. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30776. }
  30777. if (this.poleTargetBone) {
  30778. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30779. }
  30780. else if (this.poleTargetMesh) {
  30781. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30782. }
  30783. var bonePos = this._tmpVec1;
  30784. var zaxis = this._tmpVec2;
  30785. var xaxis = this._tmpVec3;
  30786. var yaxis = this._tmpVec4;
  30787. var upAxis = this._tmpVec5;
  30788. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30789. poleTarget.subtractToRef(bonePos, upAxis);
  30790. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30791. upAxis.y = 1;
  30792. }
  30793. else {
  30794. upAxis.normalize();
  30795. }
  30796. target.subtractToRef(bonePos, yaxis);
  30797. yaxis.normalize();
  30798. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30799. zaxis.normalize();
  30800. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30801. xaxis.normalize();
  30802. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30803. var a = this._bone1Length;
  30804. var b = this._bone2Length;
  30805. var c = BABYLON.Vector3.Distance(bonePos, target);
  30806. if (this._maxReach > 0) {
  30807. c = Math.min(this._maxReach, c);
  30808. }
  30809. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30810. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30811. if (acosa > 1) {
  30812. acosa = 1;
  30813. }
  30814. if (acosb > 1) {
  30815. acosb = 1;
  30816. }
  30817. if (acosa < -1) {
  30818. acosa = -1;
  30819. }
  30820. if (acosb < -1) {
  30821. acosb = -1;
  30822. }
  30823. var angA = Math.acos(acosa);
  30824. var angB = Math.acos(acosb);
  30825. var angC = -angA - angB;
  30826. if (this._rightHandedSystem) {
  30827. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30828. mat2.multiplyToRef(mat1, mat1);
  30829. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30830. mat2.multiplyToRef(mat1, mat1);
  30831. }
  30832. else {
  30833. this._tmpVec1.copyFrom(this._bendAxis);
  30834. this._tmpVec1.x *= -1;
  30835. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30836. mat2.multiplyToRef(mat1, mat1);
  30837. }
  30838. if (this.poleAngle) {
  30839. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30840. mat1.multiplyToRef(mat2, mat1);
  30841. }
  30842. if (this.slerpAmount < 1) {
  30843. if (!this._slerping) {
  30844. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30845. }
  30846. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30847. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30848. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30849. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30850. this._slerping = true;
  30851. }
  30852. else {
  30853. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30854. this._bone1Mat.copyFrom(mat1);
  30855. this._slerping = false;
  30856. }
  30857. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30858. this._bone2Ang = angC;
  30859. };
  30860. return BoneIKController;
  30861. }());
  30862. BABYLON.BoneIKController = BoneIKController;
  30863. })(BABYLON || (BABYLON = {}));
  30864. //# sourceMappingURL=babylon.boneIKController.js.map
  30865. var BABYLON;
  30866. (function (BABYLON) {
  30867. var BoneLookController = (function () {
  30868. function BoneLookController(mesh, bone, target, options) {
  30869. this.upAxis = BABYLON.Vector3.Up();
  30870. this.adjustYaw = 0;
  30871. this.adjustPitch = 0;
  30872. this.adjustRoll = 0;
  30873. this._tmpVec1 = BABYLON.Vector3.Zero();
  30874. this._tmpVec2 = BABYLON.Vector3.Zero();
  30875. this._tmpVec3 = BABYLON.Vector3.Zero();
  30876. this._tmpVec4 = BABYLON.Vector3.Zero();
  30877. this._tmpMat1 = BABYLON.Matrix.Identity();
  30878. this._tmpMat2 = BABYLON.Matrix.Identity();
  30879. this.mesh = mesh;
  30880. this.bone = bone;
  30881. this.target = target;
  30882. if (options) {
  30883. if (options.adjustYaw) {
  30884. this.adjustYaw = options.adjustYaw;
  30885. }
  30886. if (options.adjustPitch) {
  30887. this.adjustPitch = options.adjustPitch;
  30888. }
  30889. if (options.adjustRoll) {
  30890. this.adjustRoll = options.adjustRoll;
  30891. }
  30892. }
  30893. }
  30894. BoneLookController.prototype.update = function () {
  30895. var bone = this.bone;
  30896. var target = this.target;
  30897. var bonePos = this._tmpVec1;
  30898. var zaxis = this._tmpVec2;
  30899. var xaxis = this._tmpVec3;
  30900. var yaxis = this._tmpVec4;
  30901. var mat1 = this._tmpMat1;
  30902. var mat2 = this._tmpMat2;
  30903. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30904. target.subtractToRef(bonePos, zaxis);
  30905. zaxis.normalize();
  30906. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30907. xaxis.normalize();
  30908. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30909. yaxis.normalize();
  30910. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30911. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30912. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30913. mat2.multiplyToRef(mat1, mat1);
  30914. }
  30915. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30916. };
  30917. return BoneLookController;
  30918. }());
  30919. BABYLON.BoneLookController = BoneLookController;
  30920. })(BABYLON || (BABYLON = {}));
  30921. //# sourceMappingURL=babylon.boneLookController.js.map
  30922. var BABYLON;
  30923. (function (BABYLON) {
  30924. var Skeleton = (function () {
  30925. function Skeleton(name, id, scene) {
  30926. this.name = name;
  30927. this.id = id;
  30928. this.bones = new Array();
  30929. this.needInitialSkinMatrix = false;
  30930. this._isDirty = true;
  30931. this._meshesWithPoseMatrix = new Array();
  30932. this._identity = BABYLON.Matrix.Identity();
  30933. this._ranges = {};
  30934. this._lastAbsoluteTransformsUpdateId = -1;
  30935. this.bones = [];
  30936. this._scene = scene;
  30937. scene.skeletons.push(this);
  30938. //make sure it will recalculate the matrix next time prepare is called.
  30939. this._isDirty = true;
  30940. }
  30941. // Members
  30942. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30943. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30944. return mesh._bonesTransformMatrices;
  30945. }
  30946. if (!this._transformMatrices) {
  30947. this.prepare();
  30948. }
  30949. return this._transformMatrices;
  30950. };
  30951. Skeleton.prototype.getScene = function () {
  30952. return this._scene;
  30953. };
  30954. // Methods
  30955. /**
  30956. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30957. */
  30958. Skeleton.prototype.toString = function (fullDetails) {
  30959. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  30960. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30961. if (fullDetails) {
  30962. ret += ", Ranges: {";
  30963. var first = true;
  30964. for (var name_1 in this._ranges) {
  30965. if (first) {
  30966. ret += ", ";
  30967. first = false;
  30968. }
  30969. ret += name_1;
  30970. }
  30971. ret += "}";
  30972. }
  30973. return ret;
  30974. };
  30975. /**
  30976. * Get bone's index searching by name
  30977. * @param {string} name is bone's name to search for
  30978. * @return {number} Indice of the bone. Returns -1 if not found
  30979. */
  30980. Skeleton.prototype.getBoneIndexByName = function (name) {
  30981. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  30982. if (this.bones[boneIndex].name === name) {
  30983. return boneIndex;
  30984. }
  30985. }
  30986. return -1;
  30987. };
  30988. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  30989. // check name not already in use
  30990. if (!this._ranges[name]) {
  30991. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  30992. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30993. if (this.bones[i].animations[0]) {
  30994. this.bones[i].animations[0].createRange(name, from, to);
  30995. }
  30996. }
  30997. }
  30998. };
  30999. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31000. if (deleteFrames === void 0) { deleteFrames = true; }
  31001. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31002. if (this.bones[i].animations[0]) {
  31003. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31004. }
  31005. }
  31006. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31007. };
  31008. Skeleton.prototype.getAnimationRange = function (name) {
  31009. return this._ranges[name];
  31010. };
  31011. /**
  31012. * Returns as an Array, all AnimationRanges defined on this skeleton
  31013. */
  31014. Skeleton.prototype.getAnimationRanges = function () {
  31015. var animationRanges = [];
  31016. var name;
  31017. var i = 0;
  31018. for (name in this._ranges) {
  31019. animationRanges[i] = this._ranges[name];
  31020. i++;
  31021. }
  31022. return animationRanges;
  31023. };
  31024. /**
  31025. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31026. */
  31027. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31028. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31029. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31030. return false;
  31031. }
  31032. var ret = true;
  31033. var frameOffset = this._getHighestAnimationFrame() + 1;
  31034. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31035. var boneDict = {};
  31036. var sourceBones = source.bones;
  31037. var nBones;
  31038. var i;
  31039. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31040. boneDict[sourceBones[i].name] = sourceBones[i];
  31041. }
  31042. if (this.bones.length !== sourceBones.length) {
  31043. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31044. ret = false;
  31045. }
  31046. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31047. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31048. var boneName = this.bones[i].name;
  31049. var sourceBone = boneDict[boneName];
  31050. if (sourceBone) {
  31051. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31052. }
  31053. else {
  31054. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31055. ret = false;
  31056. }
  31057. }
  31058. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31059. var range = source.getAnimationRange(name);
  31060. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31061. return ret;
  31062. };
  31063. Skeleton.prototype.returnToRest = function () {
  31064. for (var index = 0; index < this.bones.length; index++) {
  31065. this.bones[index].returnToRest();
  31066. }
  31067. };
  31068. Skeleton.prototype._getHighestAnimationFrame = function () {
  31069. var ret = 0;
  31070. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31071. if (this.bones[i].animations[0]) {
  31072. var highest = this.bones[i].animations[0].getHighestFrame();
  31073. if (ret < highest) {
  31074. ret = highest;
  31075. }
  31076. }
  31077. }
  31078. return ret;
  31079. };
  31080. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31081. var range = this.getAnimationRange(name);
  31082. if (!range) {
  31083. return null;
  31084. }
  31085. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31086. };
  31087. Skeleton.prototype._markAsDirty = function () {
  31088. this._isDirty = true;
  31089. };
  31090. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31091. this._meshesWithPoseMatrix.push(mesh);
  31092. };
  31093. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31094. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31095. if (index > -1) {
  31096. this._meshesWithPoseMatrix.splice(index, 1);
  31097. }
  31098. };
  31099. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31100. for (var index = 0; index < this.bones.length; index++) {
  31101. var bone = this.bones[index];
  31102. var parentBone = bone.getParent();
  31103. if (parentBone) {
  31104. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31105. }
  31106. else {
  31107. if (initialSkinMatrix) {
  31108. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31109. }
  31110. else {
  31111. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31112. }
  31113. }
  31114. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31115. }
  31116. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31117. };
  31118. Skeleton.prototype.prepare = function () {
  31119. if (!this._isDirty) {
  31120. return;
  31121. }
  31122. if (this.needInitialSkinMatrix) {
  31123. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31124. var mesh = this._meshesWithPoseMatrix[index];
  31125. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31126. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31127. }
  31128. var poseMatrix = mesh.getPoseMatrix();
  31129. // Prepare bones
  31130. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31131. var bone = this.bones[boneIndex];
  31132. if (!bone.getParent()) {
  31133. var matrix = bone.getBaseMatrix();
  31134. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31135. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31136. }
  31137. }
  31138. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31139. }
  31140. }
  31141. else {
  31142. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31143. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31144. }
  31145. this._computeTransformMatrices(this._transformMatrices, null);
  31146. }
  31147. this._isDirty = false;
  31148. this._scene._activeBones.addCount(this.bones.length, false);
  31149. };
  31150. Skeleton.prototype.getAnimatables = function () {
  31151. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31152. this._animatables = [];
  31153. for (var index = 0; index < this.bones.length; index++) {
  31154. this._animatables.push(this.bones[index]);
  31155. }
  31156. }
  31157. return this._animatables;
  31158. };
  31159. Skeleton.prototype.clone = function (name, id) {
  31160. var result = new Skeleton(name, id || name, this._scene);
  31161. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31162. for (var index = 0; index < this.bones.length; index++) {
  31163. var source = this.bones[index];
  31164. var parentBone = null;
  31165. if (source.getParent()) {
  31166. var parentIndex = this.bones.indexOf(source.getParent());
  31167. parentBone = result.bones[parentIndex];
  31168. }
  31169. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31170. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31171. }
  31172. if (this._ranges) {
  31173. result._ranges = {};
  31174. for (var rangeName in this._ranges) {
  31175. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31176. }
  31177. }
  31178. this._isDirty = true;
  31179. return result;
  31180. };
  31181. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31182. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31183. this.bones.forEach(function (bone) {
  31184. bone.animations.forEach(function (animation) {
  31185. animation.enableBlending = true;
  31186. animation.blendingSpeed = blendingSpeed;
  31187. });
  31188. });
  31189. };
  31190. Skeleton.prototype.dispose = function () {
  31191. this._meshesWithPoseMatrix = [];
  31192. // Animations
  31193. this.getScene().stopAnimation(this);
  31194. // Remove from scene
  31195. this.getScene().removeSkeleton(this);
  31196. };
  31197. Skeleton.prototype.serialize = function () {
  31198. var serializationObject = {};
  31199. serializationObject.name = this.name;
  31200. serializationObject.id = this.id;
  31201. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31202. serializationObject.bones = [];
  31203. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31204. for (var index = 0; index < this.bones.length; index++) {
  31205. var bone = this.bones[index];
  31206. var serializedBone = {
  31207. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31208. name: bone.name,
  31209. matrix: bone.getLocalMatrix().toArray(),
  31210. rest: bone.getRestPose().toArray()
  31211. };
  31212. serializationObject.bones.push(serializedBone);
  31213. if (bone.length) {
  31214. serializedBone.length = bone.length;
  31215. }
  31216. if (bone.animations && bone.animations.length > 0) {
  31217. serializedBone.animation = bone.animations[0].serialize();
  31218. }
  31219. serializationObject.ranges = [];
  31220. for (var name in this._ranges) {
  31221. var range = {};
  31222. range.name = name;
  31223. range.from = this._ranges[name].from;
  31224. range.to = this._ranges[name].to;
  31225. serializationObject.ranges.push(range);
  31226. }
  31227. }
  31228. return serializationObject;
  31229. };
  31230. Skeleton.Parse = function (parsedSkeleton, scene) {
  31231. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31232. if (parsedSkeleton.dimensionsAtRest) {
  31233. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31234. }
  31235. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31236. var index;
  31237. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31238. var parsedBone = parsedSkeleton.bones[index];
  31239. var parentBone = null;
  31240. if (parsedBone.parentBoneIndex > -1) {
  31241. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31242. }
  31243. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31244. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31245. if (parsedBone.length) {
  31246. bone.length = parsedBone.length;
  31247. }
  31248. if (parsedBone.animation) {
  31249. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31250. }
  31251. }
  31252. // placed after bones, so createAnimationRange can cascade down
  31253. if (parsedSkeleton.ranges) {
  31254. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31255. var data = parsedSkeleton.ranges[index];
  31256. skeleton.createAnimationRange(data.name, data.from, data.to);
  31257. }
  31258. }
  31259. return skeleton;
  31260. };
  31261. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31262. if (forceUpdate === void 0) { forceUpdate = false; }
  31263. var renderId = this._scene.getRenderId();
  31264. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31265. this.bones[0].computeAbsoluteTransforms();
  31266. this._lastAbsoluteTransformsUpdateId = renderId;
  31267. }
  31268. };
  31269. Skeleton.prototype.getPoseMatrix = function () {
  31270. var poseMatrix;
  31271. if (this._meshesWithPoseMatrix.length > 0) {
  31272. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31273. }
  31274. return poseMatrix;
  31275. };
  31276. return Skeleton;
  31277. }());
  31278. BABYLON.Skeleton = Skeleton;
  31279. })(BABYLON || (BABYLON = {}));
  31280. //# sourceMappingURL=babylon.skeleton.js.map
  31281. var BABYLON;
  31282. (function (BABYLON) {
  31283. var PostProcess = (function () {
  31284. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31287. this.name = name;
  31288. this.width = -1;
  31289. this.height = -1;
  31290. /*
  31291. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31292. Can only be used on a single postprocess or on the last one of a chain.
  31293. */
  31294. this.enablePixelPerfectMode = false;
  31295. this._reusable = false;
  31296. this._textures = new BABYLON.SmartArray(2);
  31297. this._currentRenderTextureInd = 0;
  31298. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31299. // Events
  31300. /**
  31301. * An event triggered when the postprocess is activated.
  31302. * @type {BABYLON.Observable}
  31303. */
  31304. this.onActivateObservable = new BABYLON.Observable();
  31305. /**
  31306. * An event triggered when the postprocess changes its size.
  31307. * @type {BABYLON.Observable}
  31308. */
  31309. this.onSizeChangedObservable = new BABYLON.Observable();
  31310. /**
  31311. * An event triggered when the postprocess applies its effect.
  31312. * @type {BABYLON.Observable}
  31313. */
  31314. this.onApplyObservable = new BABYLON.Observable();
  31315. /**
  31316. * An event triggered before rendering the postprocess
  31317. * @type {BABYLON.Observable}
  31318. */
  31319. this.onBeforeRenderObservable = new BABYLON.Observable();
  31320. /**
  31321. * An event triggered after rendering the postprocess
  31322. * @type {BABYLON.Observable}
  31323. */
  31324. this.onAfterRenderObservable = new BABYLON.Observable();
  31325. if (camera != null) {
  31326. this._camera = camera;
  31327. this._scene = camera.getScene();
  31328. camera.attachPostProcess(this);
  31329. this._engine = this._scene.getEngine();
  31330. }
  31331. else {
  31332. this._engine = engine;
  31333. }
  31334. this._options = options;
  31335. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31336. this._reusable = reusable || false;
  31337. this._textureType = textureType;
  31338. this._samplers = samplers || [];
  31339. this._samplers.push("textureSampler");
  31340. this._fragmentUrl = fragmentUrl;
  31341. this._parameters = parameters || [];
  31342. this._parameters.push("scale");
  31343. this.updateEffect(defines);
  31344. }
  31345. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31346. set: function (callback) {
  31347. if (this._onActivateObserver) {
  31348. this.onActivateObservable.remove(this._onActivateObserver);
  31349. }
  31350. this._onActivateObserver = this.onActivateObservable.add(callback);
  31351. },
  31352. enumerable: true,
  31353. configurable: true
  31354. });
  31355. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31356. set: function (callback) {
  31357. if (this._onSizeChangedObserver) {
  31358. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31359. }
  31360. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31361. },
  31362. enumerable: true,
  31363. configurable: true
  31364. });
  31365. Object.defineProperty(PostProcess.prototype, "onApply", {
  31366. set: function (callback) {
  31367. if (this._onApplyObserver) {
  31368. this.onApplyObservable.remove(this._onApplyObserver);
  31369. }
  31370. this._onApplyObserver = this.onApplyObservable.add(callback);
  31371. },
  31372. enumerable: true,
  31373. configurable: true
  31374. });
  31375. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31376. set: function (callback) {
  31377. if (this._onBeforeRenderObserver) {
  31378. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31379. }
  31380. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31381. },
  31382. enumerable: true,
  31383. configurable: true
  31384. });
  31385. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31386. set: function (callback) {
  31387. if (this._onAfterRenderObserver) {
  31388. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31389. }
  31390. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31391. },
  31392. enumerable: true,
  31393. configurable: true
  31394. });
  31395. PostProcess.prototype.updateEffect = function (defines) {
  31396. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31397. };
  31398. PostProcess.prototype.isReusable = function () {
  31399. return this._reusable;
  31400. };
  31401. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31402. PostProcess.prototype.markTextureDirty = function () {
  31403. this.width = -1;
  31404. };
  31405. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31406. camera = camera || this._camera;
  31407. var scene = camera.getScene();
  31408. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31409. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31410. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31411. var desiredWidth = this._options.width || requiredWidth;
  31412. var desiredHeight = this._options.height || requiredHeight;
  31413. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31414. if (!this._options.width) {
  31415. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31416. }
  31417. if (!this._options.height) {
  31418. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31419. }
  31420. }
  31421. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31422. if (this._textures.length > 0) {
  31423. for (var i = 0; i < this._textures.length; i++) {
  31424. this._engine._releaseTexture(this._textures.data[i]);
  31425. }
  31426. this._textures.reset();
  31427. }
  31428. this.width = desiredWidth;
  31429. this.height = desiredHeight;
  31430. var textureSize = { width: this.width, height: this.height };
  31431. var textureOptions = {
  31432. generateMipMaps: false,
  31433. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31434. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31435. samplingMode: this.renderTargetSamplingMode,
  31436. type: this._textureType
  31437. };
  31438. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31439. if (this._reusable) {
  31440. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31441. }
  31442. this.onSizeChangedObservable.notifyObservers(this);
  31443. }
  31444. if (this.enablePixelPerfectMode) {
  31445. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31446. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31447. }
  31448. else {
  31449. this._scaleRatio.copyFromFloats(1, 1);
  31450. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31451. }
  31452. this.onActivateObservable.notifyObservers(camera);
  31453. // Clear
  31454. if (this.clearColor) {
  31455. this._engine.clear(this.clearColor, true, true, true);
  31456. }
  31457. else {
  31458. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31459. }
  31460. if (this._reusable) {
  31461. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31462. }
  31463. };
  31464. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31465. get: function () {
  31466. return this._effect.isSupported;
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. PostProcess.prototype.apply = function () {
  31472. // Check
  31473. if (!this._effect.isReady())
  31474. return null;
  31475. // States
  31476. this._engine.enableEffect(this._effect);
  31477. this._engine.setState(false);
  31478. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31479. this._engine.setDepthBuffer(false);
  31480. this._engine.setDepthWrite(false);
  31481. // Texture
  31482. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31483. // Parameters
  31484. this._effect.setVector2("scale", this._scaleRatio);
  31485. this.onApplyObservable.notifyObservers(this._effect);
  31486. return this._effect;
  31487. };
  31488. PostProcess.prototype.dispose = function (camera) {
  31489. camera = camera || this._camera;
  31490. if (this._textures.length > 0) {
  31491. for (var i = 0; i < this._textures.length; i++) {
  31492. this._engine._releaseTexture(this._textures.data[i]);
  31493. }
  31494. this._textures.reset();
  31495. }
  31496. if (!camera) {
  31497. return;
  31498. }
  31499. camera.detachPostProcess(this);
  31500. var index = camera._postProcesses.indexOf(this);
  31501. if (index === 0 && camera._postProcesses.length > 0) {
  31502. this._camera._postProcesses[0].markTextureDirty();
  31503. }
  31504. this.onActivateObservable.clear();
  31505. this.onAfterRenderObservable.clear();
  31506. this.onApplyObservable.clear();
  31507. this.onBeforeRenderObservable.clear();
  31508. this.onSizeChangedObservable.clear();
  31509. };
  31510. return PostProcess;
  31511. }());
  31512. BABYLON.PostProcess = PostProcess;
  31513. })(BABYLON || (BABYLON = {}));
  31514. //# sourceMappingURL=babylon.postProcess.js.map
  31515. var BABYLON;
  31516. (function (BABYLON) {
  31517. var PostProcessManager = (function () {
  31518. function PostProcessManager(scene) {
  31519. this._vertexBuffers = {};
  31520. this._scene = scene;
  31521. }
  31522. PostProcessManager.prototype._prepareBuffers = function () {
  31523. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31524. return;
  31525. }
  31526. // VBO
  31527. var vertices = [];
  31528. vertices.push(1, 1);
  31529. vertices.push(-1, 1);
  31530. vertices.push(-1, -1);
  31531. vertices.push(1, -1);
  31532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31533. // Indices
  31534. var indices = [];
  31535. indices.push(0);
  31536. indices.push(1);
  31537. indices.push(2);
  31538. indices.push(0);
  31539. indices.push(2);
  31540. indices.push(3);
  31541. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31542. };
  31543. // Methods
  31544. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31545. var postProcesses = this._scene.activeCamera._postProcesses;
  31546. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31547. return false;
  31548. }
  31549. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31550. return true;
  31551. };
  31552. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31553. var engine = this._scene.getEngine();
  31554. for (var index = 0; index < postProcesses.length; index++) {
  31555. if (index < postProcesses.length - 1) {
  31556. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31557. }
  31558. else {
  31559. if (targetTexture) {
  31560. engine.bindFramebuffer(targetTexture);
  31561. }
  31562. else {
  31563. engine.restoreDefaultFramebuffer();
  31564. }
  31565. }
  31566. var pp = postProcesses[index];
  31567. var effect = pp.apply();
  31568. if (effect) {
  31569. pp.onBeforeRenderObservable.notifyObservers(effect);
  31570. // VBOs
  31571. this._prepareBuffers();
  31572. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31573. // Draw order
  31574. engine.draw(true, 0, 6);
  31575. pp.onAfterRenderObservable.notifyObservers(effect);
  31576. }
  31577. }
  31578. // Restore depth buffer
  31579. engine.setDepthBuffer(true);
  31580. engine.setDepthWrite(true);
  31581. };
  31582. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31583. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31584. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31585. return;
  31586. }
  31587. var engine = this._scene.getEngine();
  31588. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31589. if (index < len - 1) {
  31590. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31591. }
  31592. else {
  31593. if (targetTexture) {
  31594. engine.bindFramebuffer(targetTexture, faceIndex);
  31595. }
  31596. else {
  31597. engine.restoreDefaultFramebuffer();
  31598. }
  31599. }
  31600. if (doNotPresent) {
  31601. break;
  31602. }
  31603. var pp = postProcesses[index];
  31604. var effect = pp.apply();
  31605. if (effect) {
  31606. pp.onBeforeRenderObservable.notifyObservers(effect);
  31607. // VBOs
  31608. this._prepareBuffers();
  31609. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31610. // Draw order
  31611. engine.draw(true, 0, 6);
  31612. pp.onAfterRenderObservable.notifyObservers(effect);
  31613. }
  31614. }
  31615. // Restore depth buffer
  31616. engine.setDepthBuffer(true);
  31617. engine.setDepthWrite(true);
  31618. };
  31619. PostProcessManager.prototype.dispose = function () {
  31620. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31621. if (buffer) {
  31622. buffer.dispose();
  31623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31624. }
  31625. if (this._indexBuffer) {
  31626. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31627. this._indexBuffer = null;
  31628. }
  31629. };
  31630. return PostProcessManager;
  31631. }());
  31632. BABYLON.PostProcessManager = PostProcessManager;
  31633. })(BABYLON || (BABYLON = {}));
  31634. //# sourceMappingURL=babylon.postProcessManager.js.map
  31635. var BABYLON;
  31636. (function (BABYLON) {
  31637. var PassPostProcess = (function (_super) {
  31638. __extends(PassPostProcess, _super);
  31639. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31640. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  31641. }
  31642. return PassPostProcess;
  31643. }(BABYLON.PostProcess));
  31644. BABYLON.PassPostProcess = PassPostProcess;
  31645. })(BABYLON || (BABYLON = {}));
  31646. //# sourceMappingURL=babylon.passPostProcess.js.map
  31647. var BABYLON;
  31648. (function (BABYLON) {
  31649. /**
  31650. * This is a holder class for the physics joint created by the physics plugin.
  31651. * It holds a set of functions to control the underlying joint.
  31652. */
  31653. var PhysicsJoint = (function () {
  31654. function PhysicsJoint(type, jointData) {
  31655. this.type = type;
  31656. this.jointData = jointData;
  31657. jointData.nativeParams = jointData.nativeParams || {};
  31658. }
  31659. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31660. get: function () {
  31661. return this._physicsJoint;
  31662. },
  31663. set: function (newJoint) {
  31664. if (this._physicsJoint) {
  31665. }
  31666. this._physicsJoint = newJoint;
  31667. },
  31668. enumerable: true,
  31669. configurable: true
  31670. });
  31671. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31672. set: function (physicsPlugin) {
  31673. this._physicsPlugin = physicsPlugin;
  31674. },
  31675. enumerable: true,
  31676. configurable: true
  31677. });
  31678. /**
  31679. * Execute a function that is physics-plugin specific.
  31680. * @param {Function} func the function that will be executed.
  31681. * It accepts two parameters: the physics world and the physics joint.
  31682. */
  31683. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31684. func(this._physicsPlugin.world, this._physicsJoint);
  31685. };
  31686. //TODO check if the native joints are the same
  31687. //Joint Types
  31688. PhysicsJoint.DistanceJoint = 0;
  31689. PhysicsJoint.HingeJoint = 1;
  31690. PhysicsJoint.BallAndSocketJoint = 2;
  31691. PhysicsJoint.WheelJoint = 3;
  31692. PhysicsJoint.SliderJoint = 4;
  31693. //OIMO
  31694. PhysicsJoint.PrismaticJoint = 5;
  31695. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31696. PhysicsJoint.UniversalJoint = 6;
  31697. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31698. //Cannon
  31699. //Similar to a Ball-Joint. Different in params
  31700. PhysicsJoint.PointToPointJoint = 8;
  31701. //Cannon only at the moment
  31702. PhysicsJoint.SpringJoint = 9;
  31703. PhysicsJoint.LockJoint = 10;
  31704. return PhysicsJoint;
  31705. }());
  31706. BABYLON.PhysicsJoint = PhysicsJoint;
  31707. /**
  31708. * A class representing a physics distance joint.
  31709. */
  31710. var DistanceJoint = (function (_super) {
  31711. __extends(DistanceJoint, _super);
  31712. function DistanceJoint(jointData) {
  31713. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  31714. }
  31715. /**
  31716. * Update the predefined distance.
  31717. */
  31718. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31719. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31720. };
  31721. return DistanceJoint;
  31722. }(PhysicsJoint));
  31723. BABYLON.DistanceJoint = DistanceJoint;
  31724. var MotorEnabledJoint = (function (_super) {
  31725. __extends(MotorEnabledJoint, _super);
  31726. function MotorEnabledJoint(type, jointData) {
  31727. _super.call(this, type, jointData);
  31728. }
  31729. /**
  31730. * Set the motor values.
  31731. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31732. * @param {number} force the force to apply
  31733. * @param {number} maxForce max force for this motor.
  31734. */
  31735. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31736. this._physicsPlugin.setMotor(this, force, maxForce);
  31737. };
  31738. /**
  31739. * Set the motor's limits.
  31740. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31741. */
  31742. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31743. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31744. };
  31745. return MotorEnabledJoint;
  31746. }(PhysicsJoint));
  31747. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31748. /**
  31749. * This class represents a single hinge physics joint
  31750. */
  31751. var HingeJoint = (function (_super) {
  31752. __extends(HingeJoint, _super);
  31753. function HingeJoint(jointData) {
  31754. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  31755. }
  31756. /**
  31757. * Set the motor values.
  31758. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31759. * @param {number} force the force to apply
  31760. * @param {number} maxForce max force for this motor.
  31761. */
  31762. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31763. this._physicsPlugin.setMotor(this, force, maxForce);
  31764. };
  31765. /**
  31766. * Set the motor's limits.
  31767. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31768. */
  31769. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31770. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31771. };
  31772. return HingeJoint;
  31773. }(MotorEnabledJoint));
  31774. BABYLON.HingeJoint = HingeJoint;
  31775. /**
  31776. * This class represents a dual hinge physics joint (same as wheel joint)
  31777. */
  31778. var Hinge2Joint = (function (_super) {
  31779. __extends(Hinge2Joint, _super);
  31780. function Hinge2Joint(jointData) {
  31781. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31782. }
  31783. /**
  31784. * Set the motor values.
  31785. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31786. * @param {number} force the force to apply
  31787. * @param {number} maxForce max force for this motor.
  31788. * @param {motorIndex} the motor's index, 0 or 1.
  31789. */
  31790. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31791. if (motorIndex === void 0) { motorIndex = 0; }
  31792. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31793. };
  31794. /**
  31795. * Set the motor limits.
  31796. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31797. * @param {number} upperLimit the upper limit
  31798. * @param {number} lowerLimit lower limit
  31799. * @param {motorIndex} the motor's index, 0 or 1.
  31800. */
  31801. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31802. if (motorIndex === void 0) { motorIndex = 0; }
  31803. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31804. };
  31805. return Hinge2Joint;
  31806. }(MotorEnabledJoint));
  31807. BABYLON.Hinge2Joint = Hinge2Joint;
  31808. })(BABYLON || (BABYLON = {}));
  31809. //# sourceMappingURL=babylon.physicsJoint.js.map
  31810. var BABYLON;
  31811. (function (BABYLON) {
  31812. var PhysicsImpostor = (function () {
  31813. function PhysicsImpostor(object, type, _options, _scene) {
  31814. var _this = this;
  31815. if (_options === void 0) { _options = { mass: 0 }; }
  31816. this.object = object;
  31817. this.type = type;
  31818. this._options = _options;
  31819. this._scene = _scene;
  31820. this._bodyUpdateRequired = false;
  31821. this._onBeforePhysicsStepCallbacks = new Array();
  31822. this._onAfterPhysicsStepCallbacks = new Array();
  31823. this._onPhysicsCollideCallbacks = [];
  31824. this._deltaPosition = BABYLON.Vector3.Zero();
  31825. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31826. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31827. /**
  31828. * this function is executed by the physics engine.
  31829. */
  31830. this.beforeStep = function () {
  31831. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31832. //conjugate deltaRotation
  31833. if (_this._deltaRotationConjugated) {
  31834. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31835. }
  31836. else {
  31837. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31838. }
  31839. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31840. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31841. func(_this);
  31842. });
  31843. };
  31844. /**
  31845. * this function is executed by the physics engine.
  31846. */
  31847. this.afterStep = function () {
  31848. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31849. func(_this);
  31850. });
  31851. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31852. _this.object.position.addInPlace(_this._deltaPosition);
  31853. if (_this._deltaRotation) {
  31854. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31855. }
  31856. };
  31857. //event and body object due to cannon's event-based architecture.
  31858. this.onCollide = function (e) {
  31859. if (!_this._onPhysicsCollideCallbacks.length)
  31860. return;
  31861. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31862. if (otherImpostor) {
  31863. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31864. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31865. }).forEach(function (obj) {
  31866. obj.callback(_this, otherImpostor);
  31867. });
  31868. }
  31869. };
  31870. //sanity check!
  31871. if (!this.object) {
  31872. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31873. return;
  31874. }
  31875. //legacy support for old syntax.
  31876. if (!this._scene && object.getScene) {
  31877. this._scene = object.getScene();
  31878. }
  31879. this._physicsEngine = this._scene.getPhysicsEngine();
  31880. if (!this._physicsEngine) {
  31881. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31882. }
  31883. else {
  31884. //set the object's quaternion, if not set
  31885. if (!this.object.rotationQuaternion) {
  31886. if (this.object.rotation) {
  31887. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31888. }
  31889. else {
  31890. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31891. }
  31892. }
  31893. //default options params
  31894. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31895. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31896. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31897. this._joints = [];
  31898. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31899. if (!this.object.parent) {
  31900. this._init();
  31901. }
  31902. }
  31903. }
  31904. /**
  31905. * This function will completly initialize this impostor.
  31906. * It will create a new body - but only if this mesh has no parent.
  31907. * If it has, this impostor will not be used other than to define the impostor
  31908. * of the child mesh.
  31909. */
  31910. PhysicsImpostor.prototype._init = function () {
  31911. this._physicsEngine.removeImpostor(this);
  31912. this.physicsBody = null;
  31913. this._parent = this._parent || this._getPhysicsParent();
  31914. if (!this.parent) {
  31915. this._physicsEngine.addImpostor(this);
  31916. }
  31917. };
  31918. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31919. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31920. var parentMesh = this.object.parent;
  31921. return parentMesh.physicsImpostor;
  31922. }
  31923. return;
  31924. };
  31925. /**
  31926. * Should a new body be generated.
  31927. */
  31928. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31929. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31930. };
  31931. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31932. this.forceUpdate();
  31933. };
  31934. /**
  31935. * Force a regeneration of this or the parent's impostor's body.
  31936. * Use under cautious - This will remove all joints already implemented.
  31937. */
  31938. PhysicsImpostor.prototype.forceUpdate = function () {
  31939. this._init();
  31940. if (this.parent) {
  31941. this.parent.forceUpdate();
  31942. }
  31943. };
  31944. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31945. /*public get mesh(): AbstractMesh {
  31946. return this._mesh;
  31947. }*/
  31948. /**
  31949. * Gets the body that holds this impostor. Either its own, or its parent.
  31950. */
  31951. get: function () {
  31952. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31953. },
  31954. /**
  31955. * Set the physics body. Used mainly by the physics engine/plugin
  31956. */
  31957. set: function (physicsBody) {
  31958. if (this._physicsBody) {
  31959. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  31960. }
  31961. this._physicsBody = physicsBody;
  31962. this.resetUpdateFlags();
  31963. },
  31964. enumerable: true,
  31965. configurable: true
  31966. });
  31967. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  31968. get: function () {
  31969. return this._parent;
  31970. },
  31971. set: function (value) {
  31972. this._parent = value;
  31973. },
  31974. enumerable: true,
  31975. configurable: true
  31976. });
  31977. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  31978. this._bodyUpdateRequired = false;
  31979. };
  31980. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  31981. if (this.object.getBoundingInfo) {
  31982. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  31983. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  31984. }
  31985. else {
  31986. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  31987. }
  31988. };
  31989. PhysicsImpostor.prototype.getObjectCenter = function () {
  31990. if (this.object.getBoundingInfo) {
  31991. return this.object.getBoundingInfo().boundingBox.center;
  31992. }
  31993. else {
  31994. return this.object.position;
  31995. }
  31996. };
  31997. /**
  31998. * Get a specific parametes from the options parameter.
  31999. */
  32000. PhysicsImpostor.prototype.getParam = function (paramName) {
  32001. return this._options[paramName];
  32002. };
  32003. /**
  32004. * Sets a specific parameter in the options given to the physics plugin
  32005. */
  32006. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32007. this._options[paramName] = value;
  32008. this._bodyUpdateRequired = true;
  32009. };
  32010. /**
  32011. * Specifically change the body's mass option. Won't recreate the physics body object
  32012. */
  32013. PhysicsImpostor.prototype.setMass = function (mass) {
  32014. if (this.getParam("mass") !== mass) {
  32015. this.setParam("mass", mass);
  32016. }
  32017. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32018. };
  32019. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32020. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32021. };
  32022. /**
  32023. * Set the body's linear velocity.
  32024. */
  32025. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32026. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32027. };
  32028. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32029. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32030. };
  32031. /**
  32032. * Set the body's linear velocity.
  32033. */
  32034. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32035. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32036. };
  32037. /**
  32038. * Execute a function with the physics plugin native code.
  32039. * Provide a function the will have two variables - the world object and the physics body object.
  32040. */
  32041. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32042. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32043. };
  32044. /**
  32045. * Register a function that will be executed before the physics world is stepping forward.
  32046. */
  32047. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32048. this._onBeforePhysicsStepCallbacks.push(func);
  32049. };
  32050. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32051. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32052. if (index > -1) {
  32053. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32054. }
  32055. else {
  32056. BABYLON.Tools.Warn("Function to remove was not found");
  32057. }
  32058. };
  32059. /**
  32060. * Register a function that will be executed after the physics step
  32061. */
  32062. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32063. this._onAfterPhysicsStepCallbacks.push(func);
  32064. };
  32065. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32066. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32067. if (index > -1) {
  32068. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32069. }
  32070. else {
  32071. BABYLON.Tools.Warn("Function to remove was not found");
  32072. }
  32073. };
  32074. /**
  32075. * register a function that will be executed when this impostor collides against a different body.
  32076. */
  32077. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32078. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32079. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32080. };
  32081. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32082. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32083. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32084. if (index > -1) {
  32085. this._onPhysicsCollideCallbacks.splice(index, 1);
  32086. }
  32087. else {
  32088. BABYLON.Tools.Warn("Function to remove was not found");
  32089. }
  32090. };
  32091. /**
  32092. * Apply a force
  32093. */
  32094. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32095. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32096. };
  32097. /**
  32098. * Apply an impulse
  32099. */
  32100. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32101. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32102. };
  32103. /**
  32104. * A help function to create a joint.
  32105. */
  32106. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32107. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32108. this.addJoint(otherImpostor, joint);
  32109. };
  32110. /**
  32111. * Add a joint to this impostor with a different impostor.
  32112. */
  32113. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32114. this._joints.push({
  32115. otherImpostor: otherImpostor,
  32116. joint: joint
  32117. });
  32118. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32119. };
  32120. /**
  32121. * Will keep this body still, in a sleep mode.
  32122. */
  32123. PhysicsImpostor.prototype.sleep = function () {
  32124. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32125. };
  32126. /**
  32127. * Wake the body up.
  32128. */
  32129. PhysicsImpostor.prototype.wakeUp = function () {
  32130. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32131. };
  32132. PhysicsImpostor.prototype.clone = function (newObject) {
  32133. if (!newObject)
  32134. return null;
  32135. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32136. };
  32137. PhysicsImpostor.prototype.dispose = function () {
  32138. var _this = this;
  32139. //no dispose if no physics engine is available.
  32140. if (!this._physicsEngine) {
  32141. return;
  32142. }
  32143. this._joints.forEach(function (j) {
  32144. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32145. });
  32146. //dispose the physics body
  32147. this._physicsEngine.removeImpostor(this);
  32148. if (this.parent) {
  32149. this.parent.forceUpdate();
  32150. }
  32151. else {
  32152. }
  32153. };
  32154. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32155. this._deltaPosition.copyFrom(position);
  32156. };
  32157. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32158. if (!this._deltaRotation) {
  32159. this._deltaRotation = new BABYLON.Quaternion();
  32160. }
  32161. this._deltaRotation.copyFrom(rotation);
  32162. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32163. };
  32164. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32165. //Impostor types
  32166. PhysicsImpostor.NoImpostor = 0;
  32167. PhysicsImpostor.SphereImpostor = 1;
  32168. PhysicsImpostor.BoxImpostor = 2;
  32169. PhysicsImpostor.PlaneImpostor = 3;
  32170. PhysicsImpostor.MeshImpostor = 4;
  32171. PhysicsImpostor.CylinderImpostor = 7;
  32172. PhysicsImpostor.ParticleImpostor = 8;
  32173. PhysicsImpostor.HeightmapImpostor = 9;
  32174. return PhysicsImpostor;
  32175. }());
  32176. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32177. })(BABYLON || (BABYLON = {}));
  32178. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32179. var BABYLON;
  32180. (function (BABYLON) {
  32181. var PhysicsEngine = (function () {
  32182. function PhysicsEngine(gravity, _physicsPlugin) {
  32183. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32184. this._physicsPlugin = _physicsPlugin;
  32185. //new methods and parameters
  32186. this._impostors = [];
  32187. this._joints = [];
  32188. if (!this._physicsPlugin.isSupported()) {
  32189. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32190. + "Please make sure it is included.");
  32191. }
  32192. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32193. this.setGravity(gravity);
  32194. this.setTimeStep();
  32195. }
  32196. PhysicsEngine.prototype.setGravity = function (gravity) {
  32197. this.gravity = gravity;
  32198. this._physicsPlugin.setGravity(this.gravity);
  32199. };
  32200. /**
  32201. * Set the time step of the physics engine.
  32202. * default is 1/60.
  32203. * To slow it down, enter 1/600 for example.
  32204. * To speed it up, 1/30
  32205. * @param {number} newTimeStep the new timestep to apply to this world.
  32206. */
  32207. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32208. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32209. this._physicsPlugin.setTimeStep(newTimeStep);
  32210. };
  32211. PhysicsEngine.prototype.dispose = function () {
  32212. this._impostors.forEach(function (impostor) {
  32213. impostor.dispose();
  32214. });
  32215. this._physicsPlugin.dispose();
  32216. };
  32217. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32218. return this._physicsPlugin.name;
  32219. };
  32220. /**
  32221. * Adding a new impostor for the impostor tracking.
  32222. * This will be done by the impostor itself.
  32223. * @param {PhysicsImpostor} impostor the impostor to add
  32224. */
  32225. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32226. impostor.uniqueId = this._impostors.push(impostor);
  32227. //if no parent, generate the body
  32228. if (!impostor.parent) {
  32229. this._physicsPlugin.generatePhysicsBody(impostor);
  32230. }
  32231. };
  32232. /**
  32233. * Remove an impostor from the engine.
  32234. * This impostor and its mesh will not longer be updated by the physics engine.
  32235. * @param {PhysicsImpostor} impostor the impostor to remove
  32236. */
  32237. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32238. var index = this._impostors.indexOf(impostor);
  32239. if (index > -1) {
  32240. var removed = this._impostors.splice(index, 1);
  32241. //Is it needed?
  32242. if (removed.length) {
  32243. //this will also remove it from the world.
  32244. removed[0].physicsBody = null;
  32245. }
  32246. }
  32247. };
  32248. /**
  32249. * Add a joint to the physics engine
  32250. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32251. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32252. * @param {PhysicsJoint} the joint that will connect both impostors.
  32253. */
  32254. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32255. var impostorJoint = {
  32256. mainImpostor: mainImpostor,
  32257. connectedImpostor: connectedImpostor,
  32258. joint: joint
  32259. };
  32260. joint.physicsPlugin = this._physicsPlugin;
  32261. this._joints.push(impostorJoint);
  32262. this._physicsPlugin.generateJoint(impostorJoint);
  32263. };
  32264. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32265. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32266. return (impostorJoint.connectedImpostor === connectedImpostor
  32267. && impostorJoint.joint === joint
  32268. && impostorJoint.mainImpostor === mainImpostor);
  32269. });
  32270. if (matchingJoints.length) {
  32271. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32272. }
  32273. };
  32274. /**
  32275. * Called by the scene. no need to call it.
  32276. */
  32277. PhysicsEngine.prototype._step = function (delta) {
  32278. var _this = this;
  32279. //check if any mesh has no body / requires an update
  32280. this._impostors.forEach(function (impostor) {
  32281. if (impostor.isBodyInitRequired()) {
  32282. _this._physicsPlugin.generatePhysicsBody(impostor);
  32283. }
  32284. });
  32285. if (delta > 0.1) {
  32286. delta = 0.1;
  32287. }
  32288. else if (delta <= 0) {
  32289. delta = 1.0 / 60.0;
  32290. }
  32291. this._physicsPlugin.executeStep(delta, this._impostors);
  32292. };
  32293. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32294. return this._physicsPlugin;
  32295. };
  32296. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32297. for (var i = 0; i < this._impostors.length; ++i) {
  32298. if (this._impostors[i].object === object) {
  32299. return this._impostors[i];
  32300. }
  32301. }
  32302. };
  32303. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32304. for (var i = 0; i < this._impostors.length; ++i) {
  32305. if (this._impostors[i].physicsBody === body) {
  32306. return this._impostors[i];
  32307. }
  32308. }
  32309. };
  32310. // Statics, Legacy support.
  32311. /**
  32312. * @Deprecated
  32313. *
  32314. */
  32315. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32316. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32317. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32318. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32319. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32320. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32321. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32322. PhysicsEngine.CapsuleImpostor = -1;
  32323. PhysicsEngine.ConeImpostor = -1;
  32324. PhysicsEngine.ConvexHullImpostor = -1;
  32325. PhysicsEngine.Epsilon = 0.001;
  32326. return PhysicsEngine;
  32327. }());
  32328. BABYLON.PhysicsEngine = PhysicsEngine;
  32329. })(BABYLON || (BABYLON = {}));
  32330. //# sourceMappingURL=babylon.physicsEngine.js.map
  32331. var BABYLON;
  32332. (function (BABYLON) {
  32333. var VertexData = (function () {
  32334. function VertexData() {
  32335. }
  32336. VertexData.prototype.set = function (data, kind) {
  32337. switch (kind) {
  32338. case BABYLON.VertexBuffer.PositionKind:
  32339. this.positions = data;
  32340. break;
  32341. case BABYLON.VertexBuffer.NormalKind:
  32342. this.normals = data;
  32343. break;
  32344. case BABYLON.VertexBuffer.UVKind:
  32345. this.uvs = data;
  32346. break;
  32347. case BABYLON.VertexBuffer.UV2Kind:
  32348. this.uvs2 = data;
  32349. break;
  32350. case BABYLON.VertexBuffer.UV3Kind:
  32351. this.uvs3 = data;
  32352. break;
  32353. case BABYLON.VertexBuffer.UV4Kind:
  32354. this.uvs4 = data;
  32355. break;
  32356. case BABYLON.VertexBuffer.UV5Kind:
  32357. this.uvs5 = data;
  32358. break;
  32359. case BABYLON.VertexBuffer.UV6Kind:
  32360. this.uvs6 = data;
  32361. break;
  32362. case BABYLON.VertexBuffer.ColorKind:
  32363. this.colors = data;
  32364. break;
  32365. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32366. this.matricesIndices = data;
  32367. break;
  32368. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32369. this.matricesWeights = data;
  32370. break;
  32371. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32372. this.matricesIndicesExtra = data;
  32373. break;
  32374. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32375. this.matricesWeightsExtra = data;
  32376. break;
  32377. }
  32378. };
  32379. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32380. this._applyTo(mesh, updatable);
  32381. };
  32382. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32383. this._applyTo(geometry, updatable);
  32384. };
  32385. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32386. this._update(mesh);
  32387. };
  32388. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32389. this._update(geometry);
  32390. };
  32391. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32392. if (this.positions) {
  32393. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32394. }
  32395. if (this.normals) {
  32396. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32397. }
  32398. if (this.uvs) {
  32399. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32400. }
  32401. if (this.uvs2) {
  32402. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32403. }
  32404. if (this.uvs3) {
  32405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32406. }
  32407. if (this.uvs4) {
  32408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32409. }
  32410. if (this.uvs5) {
  32411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32412. }
  32413. if (this.uvs6) {
  32414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32415. }
  32416. if (this.colors) {
  32417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32418. }
  32419. if (this.matricesIndices) {
  32420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32421. }
  32422. if (this.matricesWeights) {
  32423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32424. }
  32425. if (this.matricesIndicesExtra) {
  32426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32427. }
  32428. if (this.matricesWeightsExtra) {
  32429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32430. }
  32431. if (this.indices) {
  32432. meshOrGeometry.setIndices(this.indices);
  32433. }
  32434. };
  32435. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32436. if (this.positions) {
  32437. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32438. }
  32439. if (this.normals) {
  32440. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32441. }
  32442. if (this.uvs) {
  32443. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32444. }
  32445. if (this.uvs2) {
  32446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32447. }
  32448. if (this.uvs3) {
  32449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32450. }
  32451. if (this.uvs4) {
  32452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32453. }
  32454. if (this.uvs5) {
  32455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32456. }
  32457. if (this.uvs6) {
  32458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32459. }
  32460. if (this.colors) {
  32461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32462. }
  32463. if (this.matricesIndices) {
  32464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32465. }
  32466. if (this.matricesWeights) {
  32467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32468. }
  32469. if (this.matricesIndicesExtra) {
  32470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32471. }
  32472. if (this.matricesWeightsExtra) {
  32473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32474. }
  32475. if (this.indices) {
  32476. meshOrGeometry.setIndices(this.indices);
  32477. }
  32478. };
  32479. VertexData.prototype.transform = function (matrix) {
  32480. var transformed = BABYLON.Vector3.Zero();
  32481. var index;
  32482. if (this.positions) {
  32483. var position = BABYLON.Vector3.Zero();
  32484. for (index = 0; index < this.positions.length; index += 3) {
  32485. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32486. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32487. this.positions[index] = transformed.x;
  32488. this.positions[index + 1] = transformed.y;
  32489. this.positions[index + 2] = transformed.z;
  32490. }
  32491. }
  32492. if (this.normals) {
  32493. var normal = BABYLON.Vector3.Zero();
  32494. for (index = 0; index < this.normals.length; index += 3) {
  32495. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32496. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32497. this.normals[index] = transformed.x;
  32498. this.normals[index + 1] = transformed.y;
  32499. this.normals[index + 2] = transformed.z;
  32500. }
  32501. }
  32502. };
  32503. VertexData.prototype.merge = function (other) {
  32504. if (other.indices) {
  32505. if (!this.indices) {
  32506. this.indices = [];
  32507. }
  32508. var offset = this.positions ? this.positions.length / 3 : 0;
  32509. for (var index = 0; index < other.indices.length; index++) {
  32510. //TODO check type - if Int32Array!
  32511. this.indices.push(other.indices[index] + offset);
  32512. }
  32513. }
  32514. this.positions = this._mergeElement(this.positions, other.positions);
  32515. this.normals = this._mergeElement(this.normals, other.normals);
  32516. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32517. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32518. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32519. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32520. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32521. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32522. this.colors = this._mergeElement(this.colors, other.colors);
  32523. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32524. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32525. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32526. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32527. };
  32528. VertexData.prototype._mergeElement = function (source, other) {
  32529. if (!other)
  32530. return source;
  32531. if (!source)
  32532. return other;
  32533. var len = other.length + source.length;
  32534. var isSrcTypedArray = source instanceof Float32Array;
  32535. var isOthTypedArray = other instanceof Float32Array;
  32536. // use non-loop method when the source is Float32Array
  32537. if (isSrcTypedArray) {
  32538. var ret32 = new Float32Array(len);
  32539. ret32.set(source);
  32540. ret32.set(other, source.length);
  32541. return ret32;
  32542. }
  32543. else if (!isOthTypedArray) {
  32544. return source.concat(other);
  32545. }
  32546. else {
  32547. var ret = source.slice(0); // copy source to a separate array
  32548. for (var i = 0, len = other.length; i < len; i++) {
  32549. ret.push(other[i]);
  32550. }
  32551. return ret;
  32552. }
  32553. };
  32554. VertexData.prototype.serialize = function () {
  32555. var serializationObject = this.serialize();
  32556. if (this.positions) {
  32557. serializationObject.positions = this.positions;
  32558. }
  32559. if (this.normals) {
  32560. serializationObject.normals = this.normals;
  32561. }
  32562. if (this.uvs) {
  32563. serializationObject.uvs = this.uvs;
  32564. }
  32565. if (this.uvs2) {
  32566. serializationObject.uvs2 = this.uvs2;
  32567. }
  32568. if (this.uvs3) {
  32569. serializationObject.uvs3 = this.uvs3;
  32570. }
  32571. if (this.uvs4) {
  32572. serializationObject.uvs4 = this.uvs4;
  32573. }
  32574. if (this.uvs5) {
  32575. serializationObject.uvs5 = this.uvs5;
  32576. }
  32577. if (this.uvs6) {
  32578. serializationObject.uvs6 = this.uvs6;
  32579. }
  32580. if (this.colors) {
  32581. serializationObject.colors = this.colors;
  32582. }
  32583. if (this.matricesIndices) {
  32584. serializationObject.matricesIndices = this.matricesIndices;
  32585. serializationObject.matricesIndices._isExpanded = true;
  32586. }
  32587. if (this.matricesWeights) {
  32588. serializationObject.matricesWeights = this.matricesWeights;
  32589. }
  32590. if (this.matricesIndicesExtra) {
  32591. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32592. serializationObject.matricesIndicesExtra._isExpanded = true;
  32593. }
  32594. if (this.matricesWeightsExtra) {
  32595. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32596. }
  32597. serializationObject.indices = this.indices;
  32598. return serializationObject;
  32599. };
  32600. // Statics
  32601. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32602. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32603. };
  32604. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32605. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32606. };
  32607. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32608. var result = new VertexData();
  32609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32610. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32611. }
  32612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32613. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32614. }
  32615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32616. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32617. }
  32618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32619. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32620. }
  32621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32622. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32623. }
  32624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32625. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32626. }
  32627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32628. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32629. }
  32630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32631. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32632. }
  32633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32634. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32635. }
  32636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32637. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32638. }
  32639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32640. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32641. }
  32642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32643. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32644. }
  32645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32646. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32647. }
  32648. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32649. return result;
  32650. };
  32651. VertexData.CreateRibbon = function (options) {
  32652. var pathArray = options.pathArray;
  32653. var closeArray = options.closeArray || false;
  32654. var closePath = options.closePath || false;
  32655. var invertUV = options.invertUV || false;
  32656. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32657. var offset = options.offset || defaultOffset;
  32658. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32660. var positions = [];
  32661. var indices = [];
  32662. var normals = [];
  32663. var uvs = [];
  32664. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32665. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32666. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32667. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32668. var minlg; // minimal length among all paths from pathArray
  32669. var lg = []; // array of path lengths : nb of vertex per path
  32670. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32671. var p; // path iterator
  32672. var i; // point iterator
  32673. var j; // point iterator
  32674. // if single path in pathArray
  32675. if (pathArray.length < 2) {
  32676. var ar1 = [];
  32677. var ar2 = [];
  32678. for (i = 0; i < pathArray[0].length - offset; i++) {
  32679. ar1.push(pathArray[0][i]);
  32680. ar2.push(pathArray[0][i + offset]);
  32681. }
  32682. pathArray = [ar1, ar2];
  32683. }
  32684. // positions and horizontal distances (u)
  32685. var idc = 0;
  32686. var closePathCorr = (closePath) ? 1 : 0;
  32687. var path;
  32688. var l;
  32689. minlg = pathArray[0].length;
  32690. var vectlg;
  32691. var dist;
  32692. for (p = 0; p < pathArray.length; p++) {
  32693. uTotalDistance[p] = 0;
  32694. us[p] = [0];
  32695. path = pathArray[p];
  32696. l = path.length;
  32697. minlg = (minlg < l) ? minlg : l;
  32698. j = 0;
  32699. while (j < l) {
  32700. positions.push(path[j].x, path[j].y, path[j].z);
  32701. if (j > 0) {
  32702. vectlg = path[j].subtract(path[j - 1]).length();
  32703. dist = vectlg + uTotalDistance[p];
  32704. us[p].push(dist);
  32705. uTotalDistance[p] = dist;
  32706. }
  32707. j++;
  32708. }
  32709. if (closePath) {
  32710. j--;
  32711. positions.push(path[0].x, path[0].y, path[0].z);
  32712. vectlg = path[j].subtract(path[0]).length();
  32713. dist = vectlg + uTotalDistance[p];
  32714. us[p].push(dist);
  32715. uTotalDistance[p] = dist;
  32716. }
  32717. lg[p] = l + closePathCorr;
  32718. idx[p] = idc;
  32719. idc += (l + closePathCorr);
  32720. }
  32721. // vertical distances (v)
  32722. var path1;
  32723. var path2;
  32724. var vertex1;
  32725. var vertex2;
  32726. for (i = 0; i < minlg + closePathCorr; i++) {
  32727. vTotalDistance[i] = 0;
  32728. vs[i] = [0];
  32729. for (p = 0; p < pathArray.length - 1; p++) {
  32730. path1 = pathArray[p];
  32731. path2 = pathArray[p + 1];
  32732. if (i === minlg) {
  32733. vertex1 = path1[0];
  32734. vertex2 = path2[0];
  32735. }
  32736. else {
  32737. vertex1 = path1[i];
  32738. vertex2 = path2[i];
  32739. }
  32740. vectlg = vertex2.subtract(vertex1).length();
  32741. dist = vectlg + vTotalDistance[i];
  32742. vs[i].push(dist);
  32743. vTotalDistance[i] = dist;
  32744. }
  32745. if (closeArray) {
  32746. path1 = pathArray[p];
  32747. path2 = pathArray[0];
  32748. if (i === minlg) {
  32749. vertex2 = path2[0];
  32750. }
  32751. vectlg = vertex2.subtract(vertex1).length();
  32752. dist = vectlg + vTotalDistance[i];
  32753. vTotalDistance[i] = dist;
  32754. }
  32755. }
  32756. // uvs
  32757. var u;
  32758. var v;
  32759. for (p = 0; p < pathArray.length; p++) {
  32760. for (i = 0; i < minlg + closePathCorr; i++) {
  32761. u = us[p][i] / uTotalDistance[p];
  32762. v = vs[i][p] / vTotalDistance[i];
  32763. if (invertUV) {
  32764. uvs.push(v, u);
  32765. }
  32766. else {
  32767. uvs.push(u, v);
  32768. }
  32769. }
  32770. }
  32771. // indices
  32772. p = 0; // path index
  32773. var pi = 0; // positions array index
  32774. var l1 = lg[p] - 1; // path1 length
  32775. var l2 = lg[p + 1] - 1; // path2 length
  32776. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32777. var shft = idx[1] - idx[0]; // shift
  32778. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32779. while (pi <= min && p < path1nb) {
  32780. // 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
  32781. indices.push(pi, pi + shft, pi + 1);
  32782. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32783. pi += 1;
  32784. if (pi === min) {
  32785. p++;
  32786. if (p === lg.length - 1) {
  32787. shft = idx[0] - idx[p];
  32788. l1 = lg[p] - 1;
  32789. l2 = lg[0] - 1;
  32790. }
  32791. else {
  32792. shft = idx[p + 1] - idx[p];
  32793. l1 = lg[p] - 1;
  32794. l2 = lg[p + 1] - 1;
  32795. }
  32796. pi = idx[p];
  32797. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32798. }
  32799. }
  32800. // normals
  32801. VertexData.ComputeNormals(positions, indices, normals);
  32802. if (closePath) {
  32803. var indexFirst = 0;
  32804. var indexLast = 0;
  32805. for (p = 0; p < pathArray.length; p++) {
  32806. indexFirst = idx[p] * 3;
  32807. if (p + 1 < pathArray.length) {
  32808. indexLast = (idx[p + 1] - 1) * 3;
  32809. }
  32810. else {
  32811. indexLast = normals.length - 3;
  32812. }
  32813. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32814. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32815. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32816. normals[indexLast] = normals[indexFirst];
  32817. normals[indexLast + 1] = normals[indexFirst + 1];
  32818. normals[indexLast + 2] = normals[indexFirst + 2];
  32819. }
  32820. }
  32821. // sides
  32822. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32823. // Result
  32824. var vertexData = new VertexData();
  32825. vertexData.indices = indices;
  32826. vertexData.positions = positions;
  32827. vertexData.normals = normals;
  32828. vertexData.uvs = uvs;
  32829. if (closePath) {
  32830. vertexData._idx = idx;
  32831. }
  32832. return vertexData;
  32833. };
  32834. VertexData.CreateBox = function (options) {
  32835. var normalsSource = [
  32836. new BABYLON.Vector3(0, 0, 1),
  32837. new BABYLON.Vector3(0, 0, -1),
  32838. new BABYLON.Vector3(1, 0, 0),
  32839. new BABYLON.Vector3(-1, 0, 0),
  32840. new BABYLON.Vector3(0, 1, 0),
  32841. new BABYLON.Vector3(0, -1, 0)
  32842. ];
  32843. var indices = [];
  32844. var positions = [];
  32845. var normals = [];
  32846. var uvs = [];
  32847. var width = options.width || options.size || 1;
  32848. var height = options.height || options.size || 1;
  32849. var depth = options.depth || options.size || 1;
  32850. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32851. var faceUV = options.faceUV || new Array(6);
  32852. var faceColors = options.faceColors;
  32853. var colors = [];
  32854. // default face colors and UV if undefined
  32855. for (var f = 0; f < 6; f++) {
  32856. if (faceUV[f] === undefined) {
  32857. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32858. }
  32859. if (faceColors && faceColors[f] === undefined) {
  32860. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32861. }
  32862. }
  32863. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32864. // Create each face in turn.
  32865. for (var index = 0; index < normalsSource.length; index++) {
  32866. var normal = normalsSource[index];
  32867. // Get two vectors perpendicular to the face normal and to each other.
  32868. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32869. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32870. // Six indices (two triangles) per face.
  32871. var verticesLength = positions.length / 3;
  32872. indices.push(verticesLength);
  32873. indices.push(verticesLength + 1);
  32874. indices.push(verticesLength + 2);
  32875. indices.push(verticesLength);
  32876. indices.push(verticesLength + 2);
  32877. indices.push(verticesLength + 3);
  32878. // Four vertices per face.
  32879. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32880. positions.push(vertex.x, vertex.y, vertex.z);
  32881. normals.push(normal.x, normal.y, normal.z);
  32882. uvs.push(faceUV[index].z, faceUV[index].w);
  32883. if (faceColors) {
  32884. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32885. }
  32886. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32887. positions.push(vertex.x, vertex.y, vertex.z);
  32888. normals.push(normal.x, normal.y, normal.z);
  32889. uvs.push(faceUV[index].x, faceUV[index].w);
  32890. if (faceColors) {
  32891. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32892. }
  32893. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32894. positions.push(vertex.x, vertex.y, vertex.z);
  32895. normals.push(normal.x, normal.y, normal.z);
  32896. uvs.push(faceUV[index].x, faceUV[index].y);
  32897. if (faceColors) {
  32898. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32899. }
  32900. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32901. positions.push(vertex.x, vertex.y, vertex.z);
  32902. normals.push(normal.x, normal.y, normal.z);
  32903. uvs.push(faceUV[index].z, faceUV[index].y);
  32904. if (faceColors) {
  32905. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32906. }
  32907. }
  32908. // sides
  32909. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32910. // Result
  32911. var vertexData = new VertexData();
  32912. vertexData.indices = indices;
  32913. vertexData.positions = positions;
  32914. vertexData.normals = normals;
  32915. vertexData.uvs = uvs;
  32916. if (faceColors) {
  32917. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32918. vertexData.colors = totalColors;
  32919. }
  32920. return vertexData;
  32921. };
  32922. VertexData.CreateSphere = function (options) {
  32923. var segments = options.segments || 32;
  32924. var diameterX = options.diameterX || options.diameter || 1;
  32925. var diameterY = options.diameterY || options.diameter || 1;
  32926. var diameterZ = options.diameterZ || options.diameter || 1;
  32927. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32928. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32929. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32930. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32931. var totalZRotationSteps = 2 + segments;
  32932. var totalYRotationSteps = 2 * totalZRotationSteps;
  32933. var indices = [];
  32934. var positions = [];
  32935. var normals = [];
  32936. var uvs = [];
  32937. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32938. var normalizedZ = zRotationStep / totalZRotationSteps;
  32939. var angleZ = normalizedZ * Math.PI * slice;
  32940. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32941. var normalizedY = yRotationStep / totalYRotationSteps;
  32942. var angleY = normalizedY * Math.PI * 2 * arc;
  32943. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32944. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32945. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32946. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32947. var vertex = complete.multiply(radius);
  32948. var normal = complete.divide(radius).normalize();
  32949. positions.push(vertex.x, vertex.y, vertex.z);
  32950. normals.push(normal.x, normal.y, normal.z);
  32951. uvs.push(normalizedY, normalizedZ);
  32952. }
  32953. if (zRotationStep > 0) {
  32954. var verticesCount = positions.length / 3;
  32955. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32956. indices.push((firstIndex));
  32957. indices.push((firstIndex + 1));
  32958. indices.push(firstIndex + totalYRotationSteps + 1);
  32959. indices.push((firstIndex + totalYRotationSteps + 1));
  32960. indices.push((firstIndex + 1));
  32961. indices.push((firstIndex + totalYRotationSteps + 2));
  32962. }
  32963. }
  32964. }
  32965. // Sides
  32966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32967. // Result
  32968. var vertexData = new VertexData();
  32969. vertexData.indices = indices;
  32970. vertexData.positions = positions;
  32971. vertexData.normals = normals;
  32972. vertexData.uvs = uvs;
  32973. return vertexData;
  32974. };
  32975. // Cylinder and cone
  32976. VertexData.CreateCylinder = function (options) {
  32977. var height = options.height || 2;
  32978. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32979. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32980. var tessellation = options.tessellation || 24;
  32981. var subdivisions = options.subdivisions || 1;
  32982. var hasRings = options.hasRings;
  32983. var enclose = options.enclose;
  32984. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32985. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32986. var faceUV = options.faceUV || new Array(3);
  32987. var faceColors = options.faceColors;
  32988. // default face colors and UV if undefined
  32989. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32990. var ringNb = (hasRings) ? subdivisions : 1;
  32991. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32992. var f;
  32993. for (f = 0; f < surfaceNb; f++) {
  32994. if (faceColors && faceColors[f] === undefined) {
  32995. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32996. }
  32997. }
  32998. for (f = 0; f < surfaceNb; f++) {
  32999. if (faceUV && faceUV[f] === undefined) {
  33000. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33001. }
  33002. }
  33003. var indices = [];
  33004. var positions = [];
  33005. var normals = [];
  33006. var uvs = [];
  33007. var colors = [];
  33008. var angle_step = Math.PI * 2 * arc / tessellation;
  33009. var angle;
  33010. var h;
  33011. var radius;
  33012. var tan = (diameterBottom - diameterTop) / 2 / height;
  33013. var ringVertex = BABYLON.Vector3.Zero();
  33014. var ringNormal = BABYLON.Vector3.Zero();
  33015. var ringFirstVertex = BABYLON.Vector3.Zero();
  33016. var ringFirstNormal = BABYLON.Vector3.Zero();
  33017. var quadNormal = BABYLON.Vector3.Zero();
  33018. var Y = BABYLON.Axis.Y;
  33019. // positions, normals, uvs
  33020. var i;
  33021. var j;
  33022. var r;
  33023. var ringIdx = 1;
  33024. var s = 1; // surface index
  33025. var cs = 0;
  33026. var v = 0;
  33027. for (i = 0; i <= subdivisions; i++) {
  33028. h = i / subdivisions;
  33029. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33030. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33031. for (r = 0; r < ringIdx; r++) {
  33032. if (hasRings) {
  33033. s += r;
  33034. }
  33035. if (enclose) {
  33036. s += 2 * r;
  33037. }
  33038. for (j = 0; j <= tessellation; j++) {
  33039. angle = j * angle_step;
  33040. // position
  33041. ringVertex.x = Math.cos(-angle) * radius;
  33042. ringVertex.y = -height / 2 + h * height;
  33043. ringVertex.z = Math.sin(-angle) * radius;
  33044. // normal
  33045. if (diameterTop === 0 && i === subdivisions) {
  33046. // if no top cap, reuse former normals
  33047. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33048. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33049. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33050. }
  33051. else {
  33052. ringNormal.x = ringVertex.x;
  33053. ringNormal.z = ringVertex.z;
  33054. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33055. ringNormal.normalize();
  33056. }
  33057. // keep first ring vertex values for enclose
  33058. if (j === 0) {
  33059. ringFirstVertex.copyFrom(ringVertex);
  33060. ringFirstNormal.copyFrom(ringNormal);
  33061. }
  33062. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33063. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33064. if (hasRings) {
  33065. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33066. }
  33067. else {
  33068. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33069. }
  33070. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33071. if (faceColors) {
  33072. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33073. }
  33074. }
  33075. // if enclose, add four vertices and their dedicated normals
  33076. if (arc !== 1 && enclose) {
  33077. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33078. positions.push(0, ringVertex.y, 0);
  33079. positions.push(0, ringVertex.y, 0);
  33080. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33081. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33082. quadNormal.normalize();
  33083. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33084. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33085. quadNormal.normalize();
  33086. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33087. if (hasRings) {
  33088. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33089. }
  33090. else {
  33091. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33092. }
  33093. uvs.push(faceUV[s + 1].x, v);
  33094. uvs.push(faceUV[s + 1].z, v);
  33095. if (hasRings) {
  33096. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33097. }
  33098. else {
  33099. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33100. }
  33101. uvs.push(faceUV[s + 2].x, v);
  33102. uvs.push(faceUV[s + 2].z, v);
  33103. if (faceColors) {
  33104. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33105. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33106. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33107. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33108. }
  33109. }
  33110. if (cs !== s) {
  33111. cs = s;
  33112. }
  33113. }
  33114. }
  33115. // indices
  33116. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33117. var s;
  33118. i = 0;
  33119. for (s = 0; s < subdivisions; s++) {
  33120. for (j = 0; j < tessellation; j++) {
  33121. var i0 = i * (e + 1) + j;
  33122. var i1 = (i + 1) * (e + 1) + j;
  33123. var i2 = i * (e + 1) + (j + 1);
  33124. var i3 = (i + 1) * (e + 1) + (j + 1);
  33125. indices.push(i0, i1, i2);
  33126. indices.push(i3, i2, i1);
  33127. }
  33128. if (arc !== 1 && enclose) {
  33129. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33130. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33131. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33132. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33133. }
  33134. i = (hasRings) ? (i + 2) : (i + 1);
  33135. }
  33136. // Caps
  33137. var createCylinderCap = function (isTop) {
  33138. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33139. if (radius === 0) {
  33140. return;
  33141. }
  33142. // Cap positions, normals & uvs
  33143. var angle;
  33144. var circleVector;
  33145. var i;
  33146. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33147. var c;
  33148. if (faceColors) {
  33149. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33150. }
  33151. // cap center
  33152. var vbase = positions.length / 3;
  33153. var offset = isTop ? height / 2 : -height / 2;
  33154. var center = new BABYLON.Vector3(0, offset, 0);
  33155. positions.push(center.x, center.y, center.z);
  33156. normals.push(0, isTop ? 1 : -1, 0);
  33157. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33158. if (faceColors) {
  33159. colors.push(c.r, c.g, c.b, c.a);
  33160. }
  33161. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33162. for (i = 0; i <= tessellation; i++) {
  33163. angle = Math.PI * 2 * i * arc / tessellation;
  33164. var cos = Math.cos(-angle);
  33165. var sin = Math.sin(-angle);
  33166. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33167. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33168. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33169. normals.push(0, isTop ? 1 : -1, 0);
  33170. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33171. if (faceColors) {
  33172. colors.push(c.r, c.g, c.b, c.a);
  33173. }
  33174. }
  33175. // Cap indices
  33176. for (i = 0; i < tessellation; i++) {
  33177. if (!isTop) {
  33178. indices.push(vbase);
  33179. indices.push(vbase + (i + 1));
  33180. indices.push(vbase + (i + 2));
  33181. }
  33182. else {
  33183. indices.push(vbase);
  33184. indices.push(vbase + (i + 2));
  33185. indices.push(vbase + (i + 1));
  33186. }
  33187. }
  33188. };
  33189. // add caps to geometry
  33190. createCylinderCap(false);
  33191. createCylinderCap(true);
  33192. // Sides
  33193. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33194. var vertexData = new VertexData();
  33195. vertexData.indices = indices;
  33196. vertexData.positions = positions;
  33197. vertexData.normals = normals;
  33198. vertexData.uvs = uvs;
  33199. if (faceColors) {
  33200. vertexData.colors = colors;
  33201. }
  33202. return vertexData;
  33203. };
  33204. VertexData.CreateTorus = function (options) {
  33205. var indices = [];
  33206. var positions = [];
  33207. var normals = [];
  33208. var uvs = [];
  33209. var diameter = options.diameter || 1;
  33210. var thickness = options.thickness || 0.5;
  33211. var tessellation = options.tessellation || 16;
  33212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33213. var stride = tessellation + 1;
  33214. for (var i = 0; i <= tessellation; i++) {
  33215. var u = i / tessellation;
  33216. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33217. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33218. for (var j = 0; j <= tessellation; j++) {
  33219. var v = 1 - j / tessellation;
  33220. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33221. var dx = Math.cos(innerAngle);
  33222. var dy = Math.sin(innerAngle);
  33223. // Create a vertex.
  33224. var normal = new BABYLON.Vector3(dx, dy, 0);
  33225. var position = normal.scale(thickness / 2);
  33226. var textureCoordinate = new BABYLON.Vector2(u, v);
  33227. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33228. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33229. positions.push(position.x, position.y, position.z);
  33230. normals.push(normal.x, normal.y, normal.z);
  33231. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33232. // And create indices for two triangles.
  33233. var nextI = (i + 1) % stride;
  33234. var nextJ = (j + 1) % stride;
  33235. indices.push(i * stride + j);
  33236. indices.push(i * stride + nextJ);
  33237. indices.push(nextI * stride + j);
  33238. indices.push(i * stride + nextJ);
  33239. indices.push(nextI * stride + nextJ);
  33240. indices.push(nextI * stride + j);
  33241. }
  33242. }
  33243. // Sides
  33244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33245. // Result
  33246. var vertexData = new VertexData();
  33247. vertexData.indices = indices;
  33248. vertexData.positions = positions;
  33249. vertexData.normals = normals;
  33250. vertexData.uvs = uvs;
  33251. return vertexData;
  33252. };
  33253. VertexData.CreateLineSystem = function (options) {
  33254. var indices = [];
  33255. var positions = [];
  33256. var lines = options.lines;
  33257. var idx = 0;
  33258. for (var l = 0; l < lines.length; l++) {
  33259. var points = lines[l];
  33260. for (var index = 0; index < points.length; index++) {
  33261. positions.push(points[index].x, points[index].y, points[index].z);
  33262. if (index > 0) {
  33263. indices.push(idx - 1);
  33264. indices.push(idx);
  33265. }
  33266. idx++;
  33267. }
  33268. }
  33269. var vertexData = new VertexData();
  33270. vertexData.indices = indices;
  33271. vertexData.positions = positions;
  33272. return vertexData;
  33273. };
  33274. VertexData.CreateDashedLines = function (options) {
  33275. var dashSize = options.dashSize || 3;
  33276. var gapSize = options.gapSize || 1;
  33277. var dashNb = options.dashNb || 200;
  33278. var points = options.points;
  33279. var positions = new Array();
  33280. var indices = new Array();
  33281. var curvect = BABYLON.Vector3.Zero();
  33282. var lg = 0;
  33283. var nb = 0;
  33284. var shft = 0;
  33285. var dashshft = 0;
  33286. var curshft = 0;
  33287. var idx = 0;
  33288. var i = 0;
  33289. for (i = 0; i < points.length - 1; i++) {
  33290. points[i + 1].subtractToRef(points[i], curvect);
  33291. lg += curvect.length();
  33292. }
  33293. shft = lg / dashNb;
  33294. dashshft = dashSize * shft / (dashSize + gapSize);
  33295. for (i = 0; i < points.length - 1; i++) {
  33296. points[i + 1].subtractToRef(points[i], curvect);
  33297. nb = Math.floor(curvect.length() / shft);
  33298. curvect.normalize();
  33299. for (var j = 0; j < nb; j++) {
  33300. curshft = shft * j;
  33301. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33302. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33303. indices.push(idx, idx + 1);
  33304. idx += 2;
  33305. }
  33306. }
  33307. // Result
  33308. var vertexData = new VertexData();
  33309. vertexData.positions = positions;
  33310. vertexData.indices = indices;
  33311. return vertexData;
  33312. };
  33313. VertexData.CreateGround = function (options) {
  33314. var indices = [];
  33315. var positions = [];
  33316. var normals = [];
  33317. var uvs = [];
  33318. var row, col;
  33319. var width = options.width || 1;
  33320. var height = options.height || 1;
  33321. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33322. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33323. for (row = 0; row <= subdivisionsY; row++) {
  33324. for (col = 0; col <= subdivisionsX; col++) {
  33325. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33326. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33327. positions.push(position.x, position.y, position.z);
  33328. normals.push(normal.x, normal.y, normal.z);
  33329. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33330. }
  33331. }
  33332. for (row = 0; row < subdivisionsY; row++) {
  33333. for (col = 0; col < subdivisionsX; col++) {
  33334. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33335. indices.push(col + 1 + row * (subdivisionsX + 1));
  33336. indices.push(col + row * (subdivisionsX + 1));
  33337. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33338. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33339. indices.push(col + row * (subdivisionsX + 1));
  33340. }
  33341. }
  33342. // Result
  33343. var vertexData = new VertexData();
  33344. vertexData.indices = indices;
  33345. vertexData.positions = positions;
  33346. vertexData.normals = normals;
  33347. vertexData.uvs = uvs;
  33348. return vertexData;
  33349. };
  33350. VertexData.CreateTiledGround = function (options) {
  33351. var xmin = options.xmin || -1.0;
  33352. var zmin = options.zmin || -1.0;
  33353. var xmax = options.xmax || 1.0;
  33354. var zmax = options.zmax || 1.0;
  33355. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33356. var precision = options.precision || { w: 1, h: 1 };
  33357. var indices = [];
  33358. var positions = [];
  33359. var normals = [];
  33360. var uvs = [];
  33361. var row, col, tileRow, tileCol;
  33362. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33363. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33364. precision.w = (precision.w < 1) ? 1 : precision.w;
  33365. precision.h = (precision.h < 1) ? 1 : precision.h;
  33366. var tileSize = {
  33367. 'w': (xmax - xmin) / subdivisions.w,
  33368. 'h': (zmax - zmin) / subdivisions.h
  33369. };
  33370. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33371. // Indices
  33372. var base = positions.length / 3;
  33373. var rowLength = precision.w + 1;
  33374. for (row = 0; row < precision.h; row++) {
  33375. for (col = 0; col < precision.w; col++) {
  33376. var square = [
  33377. base + col + row * rowLength,
  33378. base + (col + 1) + row * rowLength,
  33379. base + (col + 1) + (row + 1) * rowLength,
  33380. base + col + (row + 1) * rowLength
  33381. ];
  33382. indices.push(square[1]);
  33383. indices.push(square[2]);
  33384. indices.push(square[3]);
  33385. indices.push(square[0]);
  33386. indices.push(square[1]);
  33387. indices.push(square[3]);
  33388. }
  33389. }
  33390. // Position, normals and uvs
  33391. var position = BABYLON.Vector3.Zero();
  33392. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33393. for (row = 0; row <= precision.h; row++) {
  33394. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33395. for (col = 0; col <= precision.w; col++) {
  33396. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33397. position.y = 0;
  33398. positions.push(position.x, position.y, position.z);
  33399. normals.push(normal.x, normal.y, normal.z);
  33400. uvs.push(col / precision.w, row / precision.h);
  33401. }
  33402. }
  33403. }
  33404. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33405. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33406. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33407. }
  33408. }
  33409. // Result
  33410. var vertexData = new VertexData();
  33411. vertexData.indices = indices;
  33412. vertexData.positions = positions;
  33413. vertexData.normals = normals;
  33414. vertexData.uvs = uvs;
  33415. return vertexData;
  33416. };
  33417. VertexData.CreateGroundFromHeightMap = function (options) {
  33418. var indices = [];
  33419. var positions = [];
  33420. var normals = [];
  33421. var uvs = [];
  33422. var row, col;
  33423. // Vertices
  33424. for (row = 0; row <= options.subdivisions; row++) {
  33425. for (col = 0; col <= options.subdivisions; col++) {
  33426. 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));
  33427. // Compute height
  33428. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33429. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33430. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33431. var r = options.buffer[pos] / 255.0;
  33432. var g = options.buffer[pos + 1] / 255.0;
  33433. var b = options.buffer[pos + 2] / 255.0;
  33434. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33435. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33436. // Add vertex
  33437. positions.push(position.x, position.y, position.z);
  33438. normals.push(0, 0, 0);
  33439. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33440. }
  33441. }
  33442. // Indices
  33443. for (row = 0; row < options.subdivisions; row++) {
  33444. for (col = 0; col < options.subdivisions; col++) {
  33445. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33446. indices.push(col + 1 + row * (options.subdivisions + 1));
  33447. indices.push(col + row * (options.subdivisions + 1));
  33448. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33449. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33450. indices.push(col + row * (options.subdivisions + 1));
  33451. }
  33452. }
  33453. // Normals
  33454. VertexData.ComputeNormals(positions, indices, normals);
  33455. // Result
  33456. var vertexData = new VertexData();
  33457. vertexData.indices = indices;
  33458. vertexData.positions = positions;
  33459. vertexData.normals = normals;
  33460. vertexData.uvs = uvs;
  33461. return vertexData;
  33462. };
  33463. VertexData.CreatePlane = function (options) {
  33464. var indices = [];
  33465. var positions = [];
  33466. var normals = [];
  33467. var uvs = [];
  33468. var width = options.width || options.size || 1;
  33469. var height = options.height || options.size || 1;
  33470. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33471. // Vertices
  33472. var halfWidth = width / 2.0;
  33473. var halfHeight = height / 2.0;
  33474. positions.push(-halfWidth, -halfHeight, 0);
  33475. normals.push(0, 0, -1.0);
  33476. uvs.push(0.0, 0.0);
  33477. positions.push(halfWidth, -halfHeight, 0);
  33478. normals.push(0, 0, -1.0);
  33479. uvs.push(1.0, 0.0);
  33480. positions.push(halfWidth, halfHeight, 0);
  33481. normals.push(0, 0, -1.0);
  33482. uvs.push(1.0, 1.0);
  33483. positions.push(-halfWidth, halfHeight, 0);
  33484. normals.push(0, 0, -1.0);
  33485. uvs.push(0.0, 1.0);
  33486. // Indices
  33487. indices.push(0);
  33488. indices.push(1);
  33489. indices.push(2);
  33490. indices.push(0);
  33491. indices.push(2);
  33492. indices.push(3);
  33493. // Sides
  33494. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33495. // Result
  33496. var vertexData = new VertexData();
  33497. vertexData.indices = indices;
  33498. vertexData.positions = positions;
  33499. vertexData.normals = normals;
  33500. vertexData.uvs = uvs;
  33501. return vertexData;
  33502. };
  33503. VertexData.CreateDisc = function (options) {
  33504. var positions = [];
  33505. var indices = [];
  33506. var normals = [];
  33507. var uvs = [];
  33508. var radius = options.radius || 0.5;
  33509. var tessellation = options.tessellation || 64;
  33510. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33511. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33512. // positions and uvs
  33513. positions.push(0, 0, 0); // disc center first
  33514. uvs.push(0.5, 0.5);
  33515. var theta = Math.PI * 2 * arc;
  33516. var step = theta / tessellation;
  33517. for (var a = 0; a < theta; a += step) {
  33518. var x = Math.cos(a);
  33519. var y = Math.sin(a);
  33520. var u = (x + 1) / 2;
  33521. var v = (1 - y) / 2;
  33522. positions.push(radius * x, radius * y, 0);
  33523. uvs.push(u, v);
  33524. }
  33525. if (arc === 1) {
  33526. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33527. uvs.push(uvs[2], uvs[3]);
  33528. }
  33529. //indices
  33530. var vertexNb = positions.length / 3;
  33531. for (var i = 1; i < vertexNb - 1; i++) {
  33532. indices.push(i + 1, 0, i);
  33533. }
  33534. // result
  33535. VertexData.ComputeNormals(positions, indices, normals);
  33536. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33537. var vertexData = new VertexData();
  33538. vertexData.indices = indices;
  33539. vertexData.positions = positions;
  33540. vertexData.normals = normals;
  33541. vertexData.uvs = uvs;
  33542. return vertexData;
  33543. };
  33544. VertexData.CreateIcoSphere = function (options) {
  33545. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33546. var radius = options.radius || 1;
  33547. var flat = (options.flat === undefined) ? true : options.flat;
  33548. var subdivisions = options.subdivisions || 4;
  33549. var radiusX = options.radiusX || radius;
  33550. var radiusY = options.radiusY || radius;
  33551. var radiusZ = options.radiusZ || radius;
  33552. var t = (1 + Math.sqrt(5)) / 2;
  33553. // 12 vertex x,y,z
  33554. var ico_vertices = [
  33555. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33556. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33557. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33558. ];
  33559. // index of 3 vertex makes a face of icopshere
  33560. var ico_indices = [
  33561. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33562. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33563. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33564. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33565. ];
  33566. // vertex for uv have aliased position, not for UV
  33567. var vertices_unalias_id = [
  33568. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33569. // vertex alias
  33570. 0,
  33571. 2,
  33572. 3,
  33573. 3,
  33574. 3,
  33575. 4,
  33576. 7,
  33577. 8,
  33578. 9,
  33579. 9,
  33580. 10,
  33581. 11 // 23: B + 12
  33582. ];
  33583. // uv as integer step (not pixels !)
  33584. var ico_vertexuv = [
  33585. 5, 1, 3, 1, 6, 4, 0, 0,
  33586. 5, 3, 4, 2, 2, 2, 4, 0,
  33587. 2, 0, 1, 1, 6, 0, 6, 2,
  33588. // vertex alias (for same vertex on different faces)
  33589. 0, 4,
  33590. 3, 3,
  33591. 4, 4,
  33592. 3, 1,
  33593. 4, 2,
  33594. 4, 4,
  33595. 0, 2,
  33596. 1, 1,
  33597. 2, 2,
  33598. 3, 3,
  33599. 1, 3,
  33600. 2, 4 // 23: B + 12
  33601. ];
  33602. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33603. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33604. // First island of uv mapping
  33605. // v = 4h 3+ 2
  33606. // v = 3h 9+ 4
  33607. // v = 2h 9+ 5 B
  33608. // v = 1h 9 1 0
  33609. // v = 0h 3 8 7 A
  33610. // u = 0 1 2 3 4 5 6 *a
  33611. // Second island of uv mapping
  33612. // v = 4h 0+ B+ 4+
  33613. // v = 3h A+ 2+
  33614. // v = 2h 7+ 6 3+
  33615. // v = 1h 8+ 3+
  33616. // v = 0h
  33617. // u = 0 1 2 3 4 5 6 *a
  33618. // Face layout on texture UV mapping
  33619. // ============
  33620. // \ 4 /\ 16 / ======
  33621. // \ / \ / /\ 11 /
  33622. // \/ 7 \/ / \ /
  33623. // ======= / 10 \/
  33624. // /\ 17 /\ =======
  33625. // / \ / \ \ 15 /\
  33626. // / 8 \/ 12 \ \ / \
  33627. // ============ \/ 6 \
  33628. // \ 18 /\ ============
  33629. // \ / \ \ 5 /\ 0 /
  33630. // \/ 13 \ \ / \ /
  33631. // ======= \/ 1 \/
  33632. // =============
  33633. // /\ 19 /\ 2 /\
  33634. // / \ / \ / \
  33635. // / 14 \/ 9 \/ 3 \
  33636. // ===================
  33637. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33638. var ustep = 138 / 1024;
  33639. var vstep = 239 / 1024;
  33640. var uoffset = 60 / 1024;
  33641. var voffset = 26 / 1024;
  33642. // Second island should have margin, not to touch the first island
  33643. // avoid any borderline artefact in pixel rounding
  33644. var island_u_offset = -40 / 1024;
  33645. var island_v_offset = +20 / 1024;
  33646. // face is either island 0 or 1 :
  33647. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33648. var island = [
  33649. 0, 0, 0, 0, 1,
  33650. 0, 0, 1, 1, 0,
  33651. 0, 0, 1, 1, 0,
  33652. 0, 1, 1, 1, 0 // 15 - 19
  33653. ];
  33654. var indices = [];
  33655. var positions = [];
  33656. var normals = [];
  33657. var uvs = [];
  33658. var current_indice = 0;
  33659. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33660. var face_vertex_pos = new Array(3);
  33661. var face_vertex_uv = new Array(3);
  33662. var v012;
  33663. for (v012 = 0; v012 < 3; v012++) {
  33664. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33665. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33666. }
  33667. // create all with normals
  33668. for (var face = 0; face < 20; face++) {
  33669. // 3 vertex per face
  33670. for (v012 = 0; v012 < 3; v012++) {
  33671. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33672. var v_id = ico_indices[3 * face + v012];
  33673. // vertex have 3D position (x,y,z)
  33674. 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]);
  33675. // Normalize to get normal, then scale to radius
  33676. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33677. // uv Coordinates from vertex ID
  33678. 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);
  33679. }
  33680. // Subdivide the face (interpolate pos, norm, uv)
  33681. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33682. // - norm is linear interpolation of vertex corner normal
  33683. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33684. // - uv is linear interpolation
  33685. //
  33686. // Topology is as below for sub-divide by 2
  33687. // vertex shown as v0,v1,v2
  33688. // interp index is i1 to progress in range [v0,v1[
  33689. // interp index is i2 to progress in range [v0,v2[
  33690. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33691. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33692. //
  33693. //
  33694. // i2 v2
  33695. // ^ ^
  33696. // / / \
  33697. // / / \
  33698. // / / \
  33699. // / / (0,1) \
  33700. // / #---------\
  33701. // / / \ (0,0)'/ \
  33702. // / / \ / \
  33703. // / / \ / \
  33704. // / / (0,0) \ / (1,0) \
  33705. // / #---------#---------\
  33706. // v0 v1
  33707. //
  33708. // --------------------> i1
  33709. //
  33710. // interp of (i1,i2):
  33711. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33712. // along i1 : lerp(x0,x1, i1/(S-i2))
  33713. //
  33714. // centroid of triangle is needed to get help normal computation
  33715. // (c1,c2) are used for centroid location
  33716. var interp_vertex = function (i1, i2, c1, c2) {
  33717. // vertex is interpolated from
  33718. // - face_vertex_pos[0..2]
  33719. // - face_vertex_uv[0..2]
  33720. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33721. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33722. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33723. pos_interp.normalize();
  33724. var vertex_normal;
  33725. if (flat) {
  33726. // in flat mode, recalculate normal as face centroid normal
  33727. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33728. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33729. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33730. }
  33731. else {
  33732. // in smooth mode, recalculate normal from each single vertex position
  33733. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33734. }
  33735. // Vertex normal need correction due to X,Y,Z radius scaling
  33736. vertex_normal.x /= radiusX;
  33737. vertex_normal.y /= radiusY;
  33738. vertex_normal.z /= radiusZ;
  33739. vertex_normal.normalize();
  33740. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33741. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33742. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33743. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33744. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33745. uvs.push(uv_interp.x, uv_interp.y);
  33746. // push each vertex has member of a face
  33747. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33748. indices.push(current_indice);
  33749. current_indice++;
  33750. };
  33751. for (var i2 = 0; i2 < subdivisions; i2++) {
  33752. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33753. // face : (i1,i2) for /\ :
  33754. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33755. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33756. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33757. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33758. if (i1 + i2 + 1 < subdivisions) {
  33759. // face : (i1,i2)' for \/ :
  33760. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33761. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33762. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33763. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33764. }
  33765. }
  33766. }
  33767. }
  33768. // Sides
  33769. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33770. // Result
  33771. var vertexData = new VertexData();
  33772. vertexData.indices = indices;
  33773. vertexData.positions = positions;
  33774. vertexData.normals = normals;
  33775. vertexData.uvs = uvs;
  33776. return vertexData;
  33777. };
  33778. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33779. VertexData.CreatePolyhedron = function (options) {
  33780. // provided polyhedron types :
  33781. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33782. // 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)
  33783. var polyhedra = [];
  33784. 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]] };
  33785. 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]] };
  33786. polyhedra[2] = {
  33787. 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]],
  33788. 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]]
  33789. };
  33790. polyhedra[3] = {
  33791. 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]],
  33792. 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]]
  33793. };
  33794. polyhedra[4] = {
  33795. 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]],
  33796. 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]]
  33797. };
  33798. 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]] };
  33799. 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]] };
  33800. 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]] };
  33801. 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]] };
  33802. 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]] };
  33803. 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]] };
  33804. 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]] };
  33805. 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]] };
  33806. 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]] };
  33807. polyhedra[14] = {
  33808. 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]],
  33809. 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]]
  33810. };
  33811. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33812. var size = options.size;
  33813. var sizeX = options.sizeX || size || 1;
  33814. var sizeY = options.sizeY || size || 1;
  33815. var sizeZ = options.sizeZ || size || 1;
  33816. var data = options.custom || polyhedra[type];
  33817. var nbfaces = data.face.length;
  33818. var faceUV = options.faceUV || new Array(nbfaces);
  33819. var faceColors = options.faceColors;
  33820. var flat = (options.flat === undefined) ? true : options.flat;
  33821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33822. var positions = [];
  33823. var indices = [];
  33824. var normals = [];
  33825. var uvs = [];
  33826. var colors = [];
  33827. var index = 0;
  33828. var faceIdx = 0; // face cursor in the array "indexes"
  33829. var indexes = [];
  33830. var i = 0;
  33831. var f = 0;
  33832. var u, v, ang, x, y, tmp;
  33833. // default face colors and UV if undefined
  33834. if (flat) {
  33835. for (f = 0; f < nbfaces; f++) {
  33836. if (faceColors && faceColors[f] === undefined) {
  33837. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33838. }
  33839. if (faceUV && faceUV[f] === undefined) {
  33840. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33841. }
  33842. }
  33843. }
  33844. if (!flat) {
  33845. for (i = 0; i < data.vertex.length; i++) {
  33846. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33847. uvs.push(0, 0);
  33848. }
  33849. for (f = 0; f < nbfaces; f++) {
  33850. for (i = 0; i < data.face[f].length - 2; i++) {
  33851. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33852. }
  33853. }
  33854. }
  33855. else {
  33856. for (f = 0; f < nbfaces; f++) {
  33857. var fl = data.face[f].length; // number of vertices of the current face
  33858. ang = 2 * Math.PI / fl;
  33859. x = 0.5 * Math.tan(ang / 2);
  33860. y = 0.5;
  33861. // positions, uvs, colors
  33862. for (i = 0; i < fl; i++) {
  33863. // positions
  33864. 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);
  33865. indexes.push(index);
  33866. index++;
  33867. // uvs
  33868. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33869. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33870. uvs.push(u, v);
  33871. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33872. y = x * Math.sin(ang) + y * Math.cos(ang);
  33873. x = tmp;
  33874. // colors
  33875. if (faceColors) {
  33876. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33877. }
  33878. }
  33879. // indices from indexes
  33880. for (i = 0; i < fl - 2; i++) {
  33881. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33882. }
  33883. faceIdx += fl;
  33884. }
  33885. }
  33886. VertexData.ComputeNormals(positions, indices, normals);
  33887. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33888. var vertexData = new VertexData();
  33889. vertexData.positions = positions;
  33890. vertexData.indices = indices;
  33891. vertexData.normals = normals;
  33892. vertexData.uvs = uvs;
  33893. if (faceColors && flat) {
  33894. vertexData.colors = colors;
  33895. }
  33896. return vertexData;
  33897. };
  33898. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33899. VertexData.CreateTorusKnot = function (options) {
  33900. var indices = [];
  33901. var positions = [];
  33902. var normals = [];
  33903. var uvs = [];
  33904. var radius = options.radius || 2;
  33905. var tube = options.tube || 0.5;
  33906. var radialSegments = options.radialSegments || 32;
  33907. var tubularSegments = options.tubularSegments || 32;
  33908. var p = options.p || 2;
  33909. var q = options.q || 3;
  33910. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33911. // Helper
  33912. var getPos = function (angle) {
  33913. var cu = Math.cos(angle);
  33914. var su = Math.sin(angle);
  33915. var quOverP = q / p * angle;
  33916. var cs = Math.cos(quOverP);
  33917. var tx = radius * (2 + cs) * 0.5 * cu;
  33918. var ty = radius * (2 + cs) * su * 0.5;
  33919. var tz = radius * Math.sin(quOverP) * 0.5;
  33920. return new BABYLON.Vector3(tx, ty, tz);
  33921. };
  33922. // Vertices
  33923. var i;
  33924. var j;
  33925. for (i = 0; i <= radialSegments; i++) {
  33926. var modI = i % radialSegments;
  33927. var u = modI / radialSegments * 2 * p * Math.PI;
  33928. var p1 = getPos(u);
  33929. var p2 = getPos(u + 0.01);
  33930. var tang = p2.subtract(p1);
  33931. var n = p2.add(p1);
  33932. var bitan = BABYLON.Vector3.Cross(tang, n);
  33933. n = BABYLON.Vector3.Cross(bitan, tang);
  33934. bitan.normalize();
  33935. n.normalize();
  33936. for (j = 0; j < tubularSegments; j++) {
  33937. var modJ = j % tubularSegments;
  33938. var v = modJ / tubularSegments * 2 * Math.PI;
  33939. var cx = -tube * Math.cos(v);
  33940. var cy = tube * Math.sin(v);
  33941. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33942. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33943. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33944. uvs.push(i / radialSegments);
  33945. uvs.push(j / tubularSegments);
  33946. }
  33947. }
  33948. for (i = 0; i < radialSegments; i++) {
  33949. for (j = 0; j < tubularSegments; j++) {
  33950. var jNext = (j + 1) % tubularSegments;
  33951. var a = i * tubularSegments + j;
  33952. var b = (i + 1) * tubularSegments + j;
  33953. var c = (i + 1) * tubularSegments + jNext;
  33954. var d = i * tubularSegments + jNext;
  33955. indices.push(d);
  33956. indices.push(b);
  33957. indices.push(a);
  33958. indices.push(d);
  33959. indices.push(c);
  33960. indices.push(b);
  33961. }
  33962. }
  33963. // Normals
  33964. VertexData.ComputeNormals(positions, indices, normals);
  33965. // Sides
  33966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33967. // Result
  33968. var vertexData = new VertexData();
  33969. vertexData.indices = indices;
  33970. vertexData.positions = positions;
  33971. vertexData.normals = normals;
  33972. vertexData.uvs = uvs;
  33973. return vertexData;
  33974. };
  33975. // Tools
  33976. /**
  33977. * @param {any} - positions (number[] or Float32Array)
  33978. * @param {any} - indices (number[] or Uint16Array)
  33979. * @param {any} - normals (number[] or Float32Array)
  33980. */
  33981. VertexData.ComputeNormals = function (positions, indices, normals) {
  33982. var index = 0;
  33983. var p1p2x = 0.0;
  33984. var p1p2y = 0.0;
  33985. var p1p2z = 0.0;
  33986. var p3p2x = 0.0;
  33987. var p3p2y = 0.0;
  33988. var p3p2z = 0.0;
  33989. var faceNormalx = 0.0;
  33990. var faceNormaly = 0.0;
  33991. var faceNormalz = 0.0;
  33992. var length = 0.0;
  33993. var i1 = 0;
  33994. var i2 = 0;
  33995. var i3 = 0;
  33996. for (index = 0; index < positions.length; index++) {
  33997. normals[index] = 0.0;
  33998. }
  33999. // indice triplet = 1 face
  34000. var nbFaces = indices.length / 3;
  34001. for (index = 0; index < nbFaces; index++) {
  34002. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34003. i2 = indices[index * 3 + 1];
  34004. i3 = indices[index * 3 + 2];
  34005. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34006. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34007. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34008. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34009. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34010. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34011. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34012. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34013. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34014. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34015. length = (length === 0) ? 1.0 : length;
  34016. faceNormalx /= length; // normalize this normal
  34017. faceNormaly /= length;
  34018. faceNormalz /= length;
  34019. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34020. normals[i1 * 3 + 1] += faceNormaly;
  34021. normals[i1 * 3 + 2] += faceNormalz;
  34022. normals[i2 * 3] += faceNormalx;
  34023. normals[i2 * 3 + 1] += faceNormaly;
  34024. normals[i2 * 3 + 2] += faceNormalz;
  34025. normals[i3 * 3] += faceNormalx;
  34026. normals[i3 * 3 + 1] += faceNormaly;
  34027. normals[i3 * 3 + 2] += faceNormalz;
  34028. }
  34029. // last normalization of each normal
  34030. for (index = 0; index < normals.length / 3; index++) {
  34031. faceNormalx = normals[index * 3];
  34032. faceNormaly = normals[index * 3 + 1];
  34033. faceNormalz = normals[index * 3 + 2];
  34034. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34035. length = (length === 0) ? 1.0 : length;
  34036. faceNormalx /= length;
  34037. faceNormaly /= length;
  34038. faceNormalz /= length;
  34039. normals[index * 3] = faceNormalx;
  34040. normals[index * 3 + 1] = faceNormaly;
  34041. normals[index * 3 + 2] = faceNormalz;
  34042. }
  34043. };
  34044. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34045. var li = indices.length;
  34046. var ln = normals.length;
  34047. var i;
  34048. var n;
  34049. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34050. switch (sideOrientation) {
  34051. case BABYLON.Mesh.FRONTSIDE:
  34052. // nothing changed
  34053. break;
  34054. case BABYLON.Mesh.BACKSIDE:
  34055. var tmp;
  34056. // indices
  34057. for (i = 0; i < li; i += 3) {
  34058. tmp = indices[i];
  34059. indices[i] = indices[i + 2];
  34060. indices[i + 2] = tmp;
  34061. }
  34062. // normals
  34063. for (n = 0; n < ln; n++) {
  34064. normals[n] = -normals[n];
  34065. }
  34066. break;
  34067. case BABYLON.Mesh.DOUBLESIDE:
  34068. // positions
  34069. var lp = positions.length;
  34070. var l = lp / 3;
  34071. for (var p = 0; p < lp; p++) {
  34072. positions[lp + p] = positions[p];
  34073. }
  34074. // indices
  34075. for (i = 0; i < li; i += 3) {
  34076. indices[i + li] = indices[i + 2] + l;
  34077. indices[i + 1 + li] = indices[i + 1] + l;
  34078. indices[i + 2 + li] = indices[i] + l;
  34079. }
  34080. // normals
  34081. for (n = 0; n < ln; n++) {
  34082. normals[ln + n] = -normals[n];
  34083. }
  34084. // uvs
  34085. var lu = uvs.length;
  34086. for (var u = 0; u < lu; u++) {
  34087. uvs[u + lu] = uvs[u];
  34088. }
  34089. break;
  34090. }
  34091. };
  34092. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34093. var vertexData = new VertexData();
  34094. // positions
  34095. var positions = parsedVertexData.positions;
  34096. if (positions) {
  34097. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34098. }
  34099. // normals
  34100. var normals = parsedVertexData.normals;
  34101. if (normals) {
  34102. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34103. }
  34104. // uvs
  34105. var uvs = parsedVertexData.uvs;
  34106. if (uvs) {
  34107. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34108. }
  34109. // uv2s
  34110. var uv2s = parsedVertexData.uv2s;
  34111. if (uv2s) {
  34112. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34113. }
  34114. // uv3s
  34115. var uv3s = parsedVertexData.uv3s;
  34116. if (uv3s) {
  34117. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34118. }
  34119. // uv4s
  34120. var uv4s = parsedVertexData.uv4s;
  34121. if (uv4s) {
  34122. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34123. }
  34124. // uv5s
  34125. var uv5s = parsedVertexData.uv5s;
  34126. if (uv5s) {
  34127. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34128. }
  34129. // uv6s
  34130. var uv6s = parsedVertexData.uv6s;
  34131. if (uv6s) {
  34132. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34133. }
  34134. // colors
  34135. var colors = parsedVertexData.colors;
  34136. if (colors) {
  34137. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34138. }
  34139. // matricesIndices
  34140. var matricesIndices = parsedVertexData.matricesIndices;
  34141. if (matricesIndices) {
  34142. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34143. }
  34144. // matricesWeights
  34145. var matricesWeights = parsedVertexData.matricesWeights;
  34146. if (matricesWeights) {
  34147. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34148. }
  34149. // indices
  34150. var indices = parsedVertexData.indices;
  34151. if (indices) {
  34152. vertexData.indices = indices;
  34153. }
  34154. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34155. };
  34156. return VertexData;
  34157. }());
  34158. BABYLON.VertexData = VertexData;
  34159. })(BABYLON || (BABYLON = {}));
  34160. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34161. var BABYLON;
  34162. (function (BABYLON) {
  34163. var Tags = (function () {
  34164. function Tags() {
  34165. }
  34166. Tags.EnableFor = function (obj) {
  34167. obj._tags = obj._tags || {};
  34168. obj.hasTags = function () {
  34169. return Tags.HasTags(obj);
  34170. };
  34171. obj.addTags = function (tagsString) {
  34172. return Tags.AddTagsTo(obj, tagsString);
  34173. };
  34174. obj.removeTags = function (tagsString) {
  34175. return Tags.RemoveTagsFrom(obj, tagsString);
  34176. };
  34177. obj.matchesTagsQuery = function (tagsQuery) {
  34178. return Tags.MatchesQuery(obj, tagsQuery);
  34179. };
  34180. };
  34181. Tags.DisableFor = function (obj) {
  34182. delete obj._tags;
  34183. delete obj.hasTags;
  34184. delete obj.addTags;
  34185. delete obj.removeTags;
  34186. delete obj.matchesTagsQuery;
  34187. };
  34188. Tags.HasTags = function (obj) {
  34189. if (!obj._tags) {
  34190. return false;
  34191. }
  34192. return !BABYLON.Tools.IsEmpty(obj._tags);
  34193. };
  34194. Tags.GetTags = function (obj, asString) {
  34195. if (asString === void 0) { asString = true; }
  34196. if (!obj._tags) {
  34197. return null;
  34198. }
  34199. if (asString) {
  34200. var tagsArray = [];
  34201. for (var tag in obj._tags) {
  34202. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34203. tagsArray.push(tag);
  34204. }
  34205. }
  34206. return tagsArray.join(" ");
  34207. }
  34208. else {
  34209. return obj._tags;
  34210. }
  34211. };
  34212. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34213. // a tag cannot start with '||', '&&', and '!'
  34214. // it cannot contain whitespaces
  34215. Tags.AddTagsTo = function (obj, tagsString) {
  34216. if (!tagsString) {
  34217. return;
  34218. }
  34219. if (typeof tagsString !== "string") {
  34220. return;
  34221. }
  34222. var tags = tagsString.split(" ");
  34223. tags.forEach(function (tag, index, array) {
  34224. Tags._AddTagTo(obj, tag);
  34225. });
  34226. };
  34227. Tags._AddTagTo = function (obj, tag) {
  34228. tag = tag.trim();
  34229. if (tag === "" || tag === "true" || tag === "false") {
  34230. return;
  34231. }
  34232. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34233. return;
  34234. }
  34235. Tags.EnableFor(obj);
  34236. obj._tags[tag] = true;
  34237. };
  34238. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34239. if (!Tags.HasTags(obj)) {
  34240. return;
  34241. }
  34242. var tags = tagsString.split(" ");
  34243. for (var t in tags) {
  34244. Tags._RemoveTagFrom(obj, tags[t]);
  34245. }
  34246. };
  34247. Tags._RemoveTagFrom = function (obj, tag) {
  34248. delete obj._tags[tag];
  34249. };
  34250. Tags.MatchesQuery = function (obj, tagsQuery) {
  34251. if (tagsQuery === undefined) {
  34252. return true;
  34253. }
  34254. if (tagsQuery === "") {
  34255. return Tags.HasTags(obj);
  34256. }
  34257. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34258. };
  34259. return Tags;
  34260. }());
  34261. BABYLON.Tags = Tags;
  34262. })(BABYLON || (BABYLON = {}));
  34263. //# sourceMappingURL=babylon.tags.js.map
  34264. var BABYLON;
  34265. (function (BABYLON) {
  34266. var Internals;
  34267. (function (Internals) {
  34268. var AndOrNotEvaluator = (function () {
  34269. function AndOrNotEvaluator() {
  34270. }
  34271. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34272. if (!query.match(/\([^\(\)]*\)/g)) {
  34273. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34274. }
  34275. else {
  34276. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34277. // remove parenthesis
  34278. r = r.slice(1, r.length - 1);
  34279. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34280. });
  34281. }
  34282. if (query === "true") {
  34283. return true;
  34284. }
  34285. if (query === "false") {
  34286. return false;
  34287. }
  34288. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34289. };
  34290. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34291. evaluateCallback = evaluateCallback || (function (r) {
  34292. return r === "true" ? true : false;
  34293. });
  34294. var result;
  34295. var or = parenthesisContent.split("||");
  34296. for (var i in or) {
  34297. if (or.hasOwnProperty(i)) {
  34298. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34299. var and = ori.split("&&");
  34300. if (and.length > 1) {
  34301. for (var j = 0; j < and.length; ++j) {
  34302. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34303. if (andj !== "true" && andj !== "false") {
  34304. if (andj[0] === "!") {
  34305. result = !evaluateCallback(andj.substring(1));
  34306. }
  34307. else {
  34308. result = evaluateCallback(andj);
  34309. }
  34310. }
  34311. else {
  34312. result = andj === "true" ? true : false;
  34313. }
  34314. if (!result) {
  34315. ori = "false";
  34316. break;
  34317. }
  34318. }
  34319. }
  34320. if (result || ori === "true") {
  34321. result = true;
  34322. break;
  34323. }
  34324. // result equals false (or undefined)
  34325. if (ori !== "true" && ori !== "false") {
  34326. if (ori[0] === "!") {
  34327. result = !evaluateCallback(ori.substring(1));
  34328. }
  34329. else {
  34330. result = evaluateCallback(ori);
  34331. }
  34332. }
  34333. else {
  34334. result = ori === "true" ? true : false;
  34335. }
  34336. }
  34337. }
  34338. // the whole parenthesis scope is replaced by 'true' or 'false'
  34339. return result ? "true" : "false";
  34340. };
  34341. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34342. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34343. // remove whitespaces
  34344. r = r.replace(/[\s]/g, function () { return ""; });
  34345. return r.length % 2 ? "!" : "";
  34346. });
  34347. booleanString = booleanString.trim();
  34348. if (booleanString === "!true") {
  34349. booleanString = "false";
  34350. }
  34351. else if (booleanString === "!false") {
  34352. booleanString = "true";
  34353. }
  34354. return booleanString;
  34355. };
  34356. return AndOrNotEvaluator;
  34357. }());
  34358. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34359. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34360. })(BABYLON || (BABYLON = {}));
  34361. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34362. var BABYLON;
  34363. (function (BABYLON) {
  34364. var PostProcessRenderPass = (function () {
  34365. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34366. this._enabled = true;
  34367. this._refCount = 0;
  34368. this._name = name;
  34369. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34370. this.setRenderList(renderList);
  34371. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34372. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34373. this._scene = scene;
  34374. this._renderList = renderList;
  34375. }
  34376. // private
  34377. PostProcessRenderPass.prototype._incRefCount = function () {
  34378. if (this._refCount === 0) {
  34379. this._scene.customRenderTargets.push(this._renderTexture);
  34380. }
  34381. return ++this._refCount;
  34382. };
  34383. PostProcessRenderPass.prototype._decRefCount = function () {
  34384. this._refCount--;
  34385. if (this._refCount <= 0) {
  34386. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34387. }
  34388. return this._refCount;
  34389. };
  34390. PostProcessRenderPass.prototype._update = function () {
  34391. this.setRenderList(this._renderList);
  34392. };
  34393. // public
  34394. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34395. this._renderTexture.renderList = renderList;
  34396. };
  34397. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34398. return this._renderTexture;
  34399. };
  34400. return PostProcessRenderPass;
  34401. }());
  34402. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34403. })(BABYLON || (BABYLON = {}));
  34404. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34405. var BABYLON;
  34406. (function (BABYLON) {
  34407. var PostProcessRenderEffect = (function () {
  34408. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34409. this._engine = engine;
  34410. this._name = name;
  34411. this._singleInstance = singleInstance || true;
  34412. this._getPostProcess = getPostProcess;
  34413. this._cameras = [];
  34414. this._indicesForCamera = [];
  34415. this._postProcesses = {};
  34416. this._renderPasses = {};
  34417. this._renderEffectAsPasses = {};
  34418. }
  34419. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34420. get: function () {
  34421. for (var index in this._postProcesses) {
  34422. if (!this._postProcesses[index].isSupported) {
  34423. return false;
  34424. }
  34425. }
  34426. return true;
  34427. },
  34428. enumerable: true,
  34429. configurable: true
  34430. });
  34431. PostProcessRenderEffect.prototype._update = function () {
  34432. for (var renderPassName in this._renderPasses) {
  34433. this._renderPasses[renderPassName]._update();
  34434. }
  34435. };
  34436. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34437. this._renderPasses[renderPass._name] = renderPass;
  34438. this._linkParameters();
  34439. };
  34440. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34441. delete this._renderPasses[renderPass._name];
  34442. this._linkParameters();
  34443. };
  34444. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34445. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34446. this._linkParameters();
  34447. };
  34448. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34449. for (var renderPassName in this._renderPasses) {
  34450. if (renderPassName === passName) {
  34451. return this._renderPasses[passName];
  34452. }
  34453. }
  34454. };
  34455. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34456. this._renderPasses = {};
  34457. this._linkParameters();
  34458. };
  34459. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34460. var cameraKey;
  34461. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34462. for (var i = 0; i < _cam.length; i++) {
  34463. var camera = _cam[i];
  34464. var cameraName = camera.name;
  34465. if (this._singleInstance) {
  34466. cameraKey = 0;
  34467. }
  34468. else {
  34469. cameraKey = cameraName;
  34470. }
  34471. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34472. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34473. if (!this._indicesForCamera[cameraName]) {
  34474. this._indicesForCamera[cameraName] = [];
  34475. }
  34476. this._indicesForCamera[cameraName].push(index);
  34477. if (this._cameras.indexOf(camera) === -1) {
  34478. this._cameras[cameraName] = camera;
  34479. }
  34480. for (var passName in this._renderPasses) {
  34481. this._renderPasses[passName]._incRefCount();
  34482. }
  34483. }
  34484. this._linkParameters();
  34485. };
  34486. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34487. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34488. for (var i = 0; i < _cam.length; i++) {
  34489. var camera = _cam[i];
  34490. var cameraName = camera.name;
  34491. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34492. var index = this._cameras.indexOf(cameraName);
  34493. this._indicesForCamera.splice(index, 1);
  34494. this._cameras.splice(index, 1);
  34495. for (var passName in this._renderPasses) {
  34496. this._renderPasses[passName]._decRefCount();
  34497. }
  34498. }
  34499. };
  34500. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34501. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34502. for (var i = 0; i < _cam.length; i++) {
  34503. var camera = _cam[i];
  34504. var cameraName = camera.name;
  34505. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34506. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34507. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34508. }
  34509. }
  34510. for (var passName in this._renderPasses) {
  34511. this._renderPasses[passName]._incRefCount();
  34512. }
  34513. }
  34514. };
  34515. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34516. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34517. for (var i = 0; i < _cam.length; i++) {
  34518. var camera = _cam[i];
  34519. var cameraName = camera.Name;
  34520. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34521. for (var passName in this._renderPasses) {
  34522. this._renderPasses[passName]._decRefCount();
  34523. }
  34524. }
  34525. };
  34526. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34527. if (this._singleInstance) {
  34528. return this._postProcesses[0];
  34529. }
  34530. else {
  34531. return this._postProcesses[camera.name];
  34532. }
  34533. };
  34534. PostProcessRenderEffect.prototype._linkParameters = function () {
  34535. var _this = this;
  34536. for (var index in this._postProcesses) {
  34537. if (this.applyParameters) {
  34538. this.applyParameters(this._postProcesses[index]);
  34539. }
  34540. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34541. _this._linkTextures(effect);
  34542. });
  34543. }
  34544. };
  34545. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34546. for (var renderPassName in this._renderPasses) {
  34547. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34548. }
  34549. for (var renderEffectName in this._renderEffectAsPasses) {
  34550. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34551. }
  34552. };
  34553. return PostProcessRenderEffect;
  34554. }());
  34555. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34556. })(BABYLON || (BABYLON = {}));
  34557. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34558. var BABYLON;
  34559. (function (BABYLON) {
  34560. var PostProcessRenderPipeline = (function () {
  34561. function PostProcessRenderPipeline(engine, name) {
  34562. this._engine = engine;
  34563. this._name = name;
  34564. this._renderEffects = {};
  34565. this._renderEffectsForIsolatedPass = {};
  34566. this._cameras = [];
  34567. }
  34568. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34569. get: function () {
  34570. for (var renderEffectName in this._renderEffects) {
  34571. if (!this._renderEffects[renderEffectName].isSupported) {
  34572. return false;
  34573. }
  34574. }
  34575. return true;
  34576. },
  34577. enumerable: true,
  34578. configurable: true
  34579. });
  34580. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34581. this._renderEffects[renderEffect._name] = renderEffect;
  34582. };
  34583. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34584. var renderEffects = this._renderEffects[renderEffectName];
  34585. if (!renderEffects) {
  34586. return;
  34587. }
  34588. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34589. };
  34590. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34591. var renderEffects = this._renderEffects[renderEffectName];
  34592. if (!renderEffects) {
  34593. return;
  34594. }
  34595. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34596. };
  34597. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34599. var indicesToDelete = [];
  34600. var i;
  34601. for (i = 0; i < _cam.length; i++) {
  34602. var camera = _cam[i];
  34603. var cameraName = camera.name;
  34604. if (this._cameras.indexOf(camera) === -1) {
  34605. this._cameras[cameraName] = camera;
  34606. }
  34607. else if (unique) {
  34608. indicesToDelete.push(i);
  34609. }
  34610. }
  34611. for (i = 0; i < indicesToDelete.length; i++) {
  34612. cameras.splice(indicesToDelete[i], 1);
  34613. }
  34614. for (var renderEffectName in this._renderEffects) {
  34615. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34616. }
  34617. };
  34618. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34619. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34620. for (var renderEffectName in this._renderEffects) {
  34621. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34622. }
  34623. for (var i = 0; i < _cam.length; i++) {
  34624. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34625. }
  34626. };
  34627. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34628. var _this = this;
  34629. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34630. var pass = null;
  34631. var renderEffectName;
  34632. for (renderEffectName in this._renderEffects) {
  34633. pass = this._renderEffects[renderEffectName].getPass(passName);
  34634. if (pass != null) {
  34635. break;
  34636. }
  34637. }
  34638. if (pass === null) {
  34639. return;
  34640. }
  34641. for (renderEffectName in this._renderEffects) {
  34642. this._renderEffects[renderEffectName]._disable(_cam);
  34643. }
  34644. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34645. for (var i = 0; i < _cam.length; i++) {
  34646. var camera = _cam[i];
  34647. var cameraName = camera.name;
  34648. 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); });
  34649. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34650. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34651. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34652. }
  34653. };
  34654. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34655. var _this = this;
  34656. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34657. for (var i = 0; i < _cam.length; i++) {
  34658. var camera = _cam[i];
  34659. var cameraName = camera.name;
  34660. 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); });
  34661. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34662. }
  34663. for (var renderEffectName in this._renderEffects) {
  34664. this._renderEffects[renderEffectName]._enable(_cam);
  34665. }
  34666. };
  34667. PostProcessRenderPipeline.prototype._update = function () {
  34668. for (var renderEffectName in this._renderEffects) {
  34669. this._renderEffects[renderEffectName]._update();
  34670. }
  34671. for (var i = 0; i < this._cameras.length; i++) {
  34672. var cameraName = this._cameras[i].name;
  34673. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34674. this._renderEffectsForIsolatedPass[cameraName]._update();
  34675. }
  34676. }
  34677. };
  34678. PostProcessRenderPipeline.prototype.dispose = function () {
  34679. // Must be implemented by children
  34680. };
  34681. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34682. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34683. return PostProcessRenderPipeline;
  34684. }());
  34685. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34686. })(BABYLON || (BABYLON = {}));
  34687. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34688. var BABYLON;
  34689. (function (BABYLON) {
  34690. var PostProcessRenderPipelineManager = (function () {
  34691. function PostProcessRenderPipelineManager() {
  34692. this._renderPipelines = {};
  34693. }
  34694. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34695. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34696. };
  34697. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34698. var renderPipeline = this._renderPipelines[renderPipelineName];
  34699. if (!renderPipeline) {
  34700. return;
  34701. }
  34702. renderPipeline._attachCameras(cameras, unique);
  34703. };
  34704. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34705. var renderPipeline = this._renderPipelines[renderPipelineName];
  34706. if (!renderPipeline) {
  34707. return;
  34708. }
  34709. renderPipeline._detachCameras(cameras);
  34710. };
  34711. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34712. var renderPipeline = this._renderPipelines[renderPipelineName];
  34713. if (!renderPipeline) {
  34714. return;
  34715. }
  34716. renderPipeline._enableEffect(renderEffectName, cameras);
  34717. };
  34718. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34719. var renderPipeline = this._renderPipelines[renderPipelineName];
  34720. if (!renderPipeline) {
  34721. return;
  34722. }
  34723. renderPipeline._disableEffect(renderEffectName, cameras);
  34724. };
  34725. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34726. var renderPipeline = this._renderPipelines[renderPipelineName];
  34727. if (!renderPipeline) {
  34728. return;
  34729. }
  34730. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34731. };
  34732. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34733. var renderPipeline = this._renderPipelines[renderPipelineName];
  34734. if (!renderPipeline) {
  34735. return;
  34736. }
  34737. renderPipeline._disableDisplayOnlyPass(cameras);
  34738. };
  34739. PostProcessRenderPipelineManager.prototype.update = function () {
  34740. for (var renderPipelineName in this._renderPipelines) {
  34741. var pipeline = this._renderPipelines[renderPipelineName];
  34742. if (!pipeline.isSupported) {
  34743. pipeline.dispose();
  34744. delete this._renderPipelines[renderPipelineName];
  34745. }
  34746. else {
  34747. pipeline._update();
  34748. }
  34749. }
  34750. };
  34751. return PostProcessRenderPipelineManager;
  34752. }());
  34753. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34754. })(BABYLON || (BABYLON = {}));
  34755. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34756. var BABYLON;
  34757. (function (BABYLON) {
  34758. var BoundingBoxRenderer = (function () {
  34759. function BoundingBoxRenderer(scene) {
  34760. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34761. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34762. this.showBackLines = true;
  34763. this.renderList = new BABYLON.SmartArray(32);
  34764. this._vertexBuffers = {};
  34765. this._scene = scene;
  34766. }
  34767. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34768. if (this._colorShader) {
  34769. return;
  34770. }
  34771. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34772. attributes: [BABYLON.VertexBuffer.PositionKind],
  34773. uniforms: ["worldViewProjection", "color"]
  34774. });
  34775. var engine = this._scene.getEngine();
  34776. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34778. 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]);
  34779. };
  34780. BoundingBoxRenderer.prototype.reset = function () {
  34781. this.renderList.reset();
  34782. };
  34783. BoundingBoxRenderer.prototype.render = function () {
  34784. if (this.renderList.length === 0) {
  34785. return;
  34786. }
  34787. this._prepareRessources();
  34788. if (!this._colorShader.isReady()) {
  34789. return;
  34790. }
  34791. var engine = this._scene.getEngine();
  34792. engine.setDepthWrite(false);
  34793. this._colorShader._preBind();
  34794. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34795. var boundingBox = this.renderList.data[boundingBoxIndex];
  34796. var min = boundingBox.minimum;
  34797. var max = boundingBox.maximum;
  34798. var diff = max.subtract(min);
  34799. var median = min.add(diff.scale(0.5));
  34800. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34801. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34802. .multiply(boundingBox.getWorldMatrix());
  34803. // VBOs
  34804. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34805. if (this.showBackLines) {
  34806. // Back
  34807. engine.setDepthFunctionToGreaterOrEqual();
  34808. this._scene.resetCachedMaterial();
  34809. this._colorShader.setColor4("color", this.backColor.toColor4());
  34810. this._colorShader.bind(worldMatrix);
  34811. // Draw order
  34812. engine.draw(false, 0, 24);
  34813. }
  34814. // Front
  34815. engine.setDepthFunctionToLess();
  34816. this._scene.resetCachedMaterial();
  34817. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34818. this._colorShader.bind(worldMatrix);
  34819. // Draw order
  34820. engine.draw(false, 0, 24);
  34821. }
  34822. this._colorShader.unbind();
  34823. engine.setDepthFunctionToLessOrEqual();
  34824. engine.setDepthWrite(true);
  34825. };
  34826. BoundingBoxRenderer.prototype.dispose = function () {
  34827. if (!this._colorShader) {
  34828. return;
  34829. }
  34830. this._colorShader.dispose();
  34831. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34832. if (buffer) {
  34833. buffer.dispose();
  34834. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34835. }
  34836. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34837. };
  34838. return BoundingBoxRenderer;
  34839. }());
  34840. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34841. })(BABYLON || (BABYLON = {}));
  34842. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34843. var BABYLON;
  34844. (function (BABYLON) {
  34845. var Condition = (function () {
  34846. function Condition(actionManager) {
  34847. this._actionManager = actionManager;
  34848. }
  34849. Condition.prototype.isValid = function () {
  34850. return true;
  34851. };
  34852. Condition.prototype._getProperty = function (propertyPath) {
  34853. return this._actionManager._getProperty(propertyPath);
  34854. };
  34855. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34856. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34857. };
  34858. Condition.prototype.serialize = function () {
  34859. };
  34860. Condition.prototype._serialize = function (serializedCondition) {
  34861. return {
  34862. type: 2,
  34863. children: [],
  34864. name: serializedCondition.name,
  34865. properties: serializedCondition.properties
  34866. };
  34867. };
  34868. return Condition;
  34869. }());
  34870. BABYLON.Condition = Condition;
  34871. var ValueCondition = (function (_super) {
  34872. __extends(ValueCondition, _super);
  34873. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34874. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34875. _super.call(this, actionManager);
  34876. this.propertyPath = propertyPath;
  34877. this.value = value;
  34878. this.operator = operator;
  34879. this._target = target;
  34880. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34881. this._property = this._getProperty(this.propertyPath);
  34882. }
  34883. Object.defineProperty(ValueCondition, "IsEqual", {
  34884. get: function () {
  34885. return ValueCondition._IsEqual;
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. Object.defineProperty(ValueCondition, "IsDifferent", {
  34891. get: function () {
  34892. return ValueCondition._IsDifferent;
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(ValueCondition, "IsGreater", {
  34898. get: function () {
  34899. return ValueCondition._IsGreater;
  34900. },
  34901. enumerable: true,
  34902. configurable: true
  34903. });
  34904. Object.defineProperty(ValueCondition, "IsLesser", {
  34905. get: function () {
  34906. return ValueCondition._IsLesser;
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. // Methods
  34912. ValueCondition.prototype.isValid = function () {
  34913. switch (this.operator) {
  34914. case ValueCondition.IsGreater:
  34915. return this._effectiveTarget[this._property] > this.value;
  34916. case ValueCondition.IsLesser:
  34917. return this._effectiveTarget[this._property] < this.value;
  34918. case ValueCondition.IsEqual:
  34919. case ValueCondition.IsDifferent:
  34920. var check;
  34921. if (this.value.equals) {
  34922. check = this.value.equals(this._effectiveTarget[this._property]);
  34923. }
  34924. else {
  34925. check = this.value === this._effectiveTarget[this._property];
  34926. }
  34927. return this.operator === ValueCondition.IsEqual ? check : !check;
  34928. }
  34929. return false;
  34930. };
  34931. ValueCondition.prototype.serialize = function () {
  34932. return this._serialize({
  34933. name: "ValueCondition",
  34934. properties: [
  34935. BABYLON.Action._GetTargetProperty(this._target),
  34936. { name: "propertyPath", value: this.propertyPath },
  34937. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34938. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34939. ]
  34940. });
  34941. };
  34942. ValueCondition.GetOperatorName = function (operator) {
  34943. switch (operator) {
  34944. case ValueCondition._IsEqual: return "IsEqual";
  34945. case ValueCondition._IsDifferent: return "IsDifferent";
  34946. case ValueCondition._IsGreater: return "IsGreater";
  34947. case ValueCondition._IsLesser: return "IsLesser";
  34948. default: return "";
  34949. }
  34950. };
  34951. // Statics
  34952. ValueCondition._IsEqual = 0;
  34953. ValueCondition._IsDifferent = 1;
  34954. ValueCondition._IsGreater = 2;
  34955. ValueCondition._IsLesser = 3;
  34956. return ValueCondition;
  34957. }(Condition));
  34958. BABYLON.ValueCondition = ValueCondition;
  34959. var PredicateCondition = (function (_super) {
  34960. __extends(PredicateCondition, _super);
  34961. function PredicateCondition(actionManager, predicate) {
  34962. _super.call(this, actionManager);
  34963. this.predicate = predicate;
  34964. }
  34965. PredicateCondition.prototype.isValid = function () {
  34966. return this.predicate();
  34967. };
  34968. return PredicateCondition;
  34969. }(Condition));
  34970. BABYLON.PredicateCondition = PredicateCondition;
  34971. var StateCondition = (function (_super) {
  34972. __extends(StateCondition, _super);
  34973. function StateCondition(actionManager, target, value) {
  34974. _super.call(this, actionManager);
  34975. this.value = value;
  34976. this._target = target;
  34977. }
  34978. // Methods
  34979. StateCondition.prototype.isValid = function () {
  34980. return this._target.state === this.value;
  34981. };
  34982. StateCondition.prototype.serialize = function () {
  34983. return this._serialize({
  34984. name: "StateCondition",
  34985. properties: [
  34986. BABYLON.Action._GetTargetProperty(this._target),
  34987. { name: "value", value: this.value }
  34988. ]
  34989. });
  34990. };
  34991. return StateCondition;
  34992. }(Condition));
  34993. BABYLON.StateCondition = StateCondition;
  34994. })(BABYLON || (BABYLON = {}));
  34995. //# sourceMappingURL=babylon.condition.js.map
  34996. var BABYLON;
  34997. (function (BABYLON) {
  34998. var Action = (function () {
  34999. function Action(triggerOptions, condition) {
  35000. this.triggerOptions = triggerOptions;
  35001. if (triggerOptions.parameter) {
  35002. this.trigger = triggerOptions.trigger;
  35003. this._triggerParameter = triggerOptions.parameter;
  35004. }
  35005. else {
  35006. this.trigger = triggerOptions;
  35007. }
  35008. this._nextActiveAction = this;
  35009. this._condition = condition;
  35010. }
  35011. // Methods
  35012. Action.prototype._prepare = function () {
  35013. };
  35014. Action.prototype.getTriggerParameter = function () {
  35015. return this._triggerParameter;
  35016. };
  35017. Action.prototype._executeCurrent = function (evt) {
  35018. if (this._nextActiveAction._condition) {
  35019. var condition = this._nextActiveAction._condition;
  35020. var currentRenderId = this._actionManager.getScene().getRenderId();
  35021. // We cache the current evaluation for the current frame
  35022. if (condition._evaluationId === currentRenderId) {
  35023. if (!condition._currentResult) {
  35024. return;
  35025. }
  35026. }
  35027. else {
  35028. condition._evaluationId = currentRenderId;
  35029. if (!condition.isValid()) {
  35030. condition._currentResult = false;
  35031. return;
  35032. }
  35033. condition._currentResult = true;
  35034. }
  35035. }
  35036. this._nextActiveAction.execute(evt);
  35037. this.skipToNextActiveAction();
  35038. };
  35039. Action.prototype.execute = function (evt) {
  35040. };
  35041. Action.prototype.skipToNextActiveAction = function () {
  35042. if (this._nextActiveAction._child) {
  35043. if (!this._nextActiveAction._child._actionManager) {
  35044. this._nextActiveAction._child._actionManager = this._actionManager;
  35045. }
  35046. this._nextActiveAction = this._nextActiveAction._child;
  35047. }
  35048. else {
  35049. this._nextActiveAction = this;
  35050. }
  35051. };
  35052. Action.prototype.then = function (action) {
  35053. this._child = action;
  35054. action._actionManager = this._actionManager;
  35055. action._prepare();
  35056. return action;
  35057. };
  35058. Action.prototype._getProperty = function (propertyPath) {
  35059. return this._actionManager._getProperty(propertyPath);
  35060. };
  35061. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35062. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35063. };
  35064. Action.prototype.serialize = function (parent) {
  35065. };
  35066. // Called by BABYLON.Action objects in serialize(...). Internal use
  35067. Action.prototype._serialize = function (serializedAction, parent) {
  35068. var serializationObject = {
  35069. type: 1,
  35070. children: [],
  35071. name: serializedAction.name,
  35072. properties: serializedAction.properties || []
  35073. };
  35074. // Serialize child
  35075. if (this._child) {
  35076. this._child.serialize(serializationObject);
  35077. }
  35078. // Check if "this" has a condition
  35079. if (this._condition) {
  35080. var serializedCondition = this._condition.serialize();
  35081. serializedCondition.children.push(serializationObject);
  35082. if (parent) {
  35083. parent.children.push(serializedCondition);
  35084. }
  35085. return serializedCondition;
  35086. }
  35087. if (parent) {
  35088. parent.children.push(serializationObject);
  35089. }
  35090. return serializationObject;
  35091. };
  35092. Action._SerializeValueAsString = function (value) {
  35093. if (typeof value === "number") {
  35094. return value.toString();
  35095. }
  35096. if (typeof value === "boolean") {
  35097. return value ? "true" : "false";
  35098. }
  35099. if (value instanceof BABYLON.Vector2) {
  35100. return value.x + ", " + value.y;
  35101. }
  35102. if (value instanceof BABYLON.Vector3) {
  35103. return value.x + ", " + value.y + ", " + value.z;
  35104. }
  35105. if (value instanceof BABYLON.Color3) {
  35106. return value.r + ", " + value.g + ", " + value.b;
  35107. }
  35108. if (value instanceof BABYLON.Color4) {
  35109. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35110. }
  35111. return value; // string
  35112. };
  35113. Action._GetTargetProperty = function (target) {
  35114. return {
  35115. name: "target",
  35116. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35117. : target instanceof BABYLON.Light ? "LightProperties"
  35118. : target instanceof BABYLON.Camera ? "CameraProperties"
  35119. : "SceneProperties",
  35120. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35121. };
  35122. };
  35123. return Action;
  35124. }());
  35125. BABYLON.Action = Action;
  35126. })(BABYLON || (BABYLON = {}));
  35127. //# sourceMappingURL=babylon.action.js.map
  35128. var BABYLON;
  35129. (function (BABYLON) {
  35130. /**
  35131. * ActionEvent is the event beint sent when an action is triggered.
  35132. */
  35133. var ActionEvent = (function () {
  35134. /**
  35135. * @constructor
  35136. * @param source The mesh or sprite that triggered the action.
  35137. * @param pointerX The X mouse cursor position at the time of the event
  35138. * @param pointerY The Y mouse cursor position at the time of the event
  35139. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35140. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35141. */
  35142. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35143. this.source = source;
  35144. this.pointerX = pointerX;
  35145. this.pointerY = pointerY;
  35146. this.meshUnderPointer = meshUnderPointer;
  35147. this.sourceEvent = sourceEvent;
  35148. this.additionalData = additionalData;
  35149. }
  35150. /**
  35151. * Helper function to auto-create an ActionEvent from a source mesh.
  35152. * @param source The source mesh that triggered the event
  35153. * @param evt {Event} The original (browser) event
  35154. */
  35155. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35156. var scene = source.getScene();
  35157. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35158. };
  35159. /**
  35160. * Helper function to auto-create an ActionEvent from a source mesh.
  35161. * @param source The source sprite that triggered the event
  35162. * @param scene Scene associated with the sprite
  35163. * @param evt {Event} The original (browser) event
  35164. */
  35165. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35166. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35167. };
  35168. /**
  35169. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35170. * @param scene the scene where the event occurred
  35171. * @param evt {Event} The original (browser) event
  35172. */
  35173. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35174. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35175. };
  35176. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35177. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35178. };
  35179. return ActionEvent;
  35180. }());
  35181. BABYLON.ActionEvent = ActionEvent;
  35182. /**
  35183. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35184. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35185. */
  35186. var ActionManager = (function () {
  35187. function ActionManager(scene) {
  35188. // Members
  35189. this.actions = new Array();
  35190. this.hoverCursor = '';
  35191. this._scene = scene;
  35192. scene._actionManagers.push(this);
  35193. }
  35194. Object.defineProperty(ActionManager, "NothingTrigger", {
  35195. get: function () {
  35196. return ActionManager._NothingTrigger;
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35202. get: function () {
  35203. return ActionManager._OnPickTrigger;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35209. get: function () {
  35210. return ActionManager._OnLeftPickTrigger;
  35211. },
  35212. enumerable: true,
  35213. configurable: true
  35214. });
  35215. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35216. get: function () {
  35217. return ActionManager._OnRightPickTrigger;
  35218. },
  35219. enumerable: true,
  35220. configurable: true
  35221. });
  35222. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35223. get: function () {
  35224. return ActionManager._OnCenterPickTrigger;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35230. get: function () {
  35231. return ActionManager._OnPickDownTrigger;
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35237. get: function () {
  35238. return ActionManager._OnPickUpTrigger;
  35239. },
  35240. enumerable: true,
  35241. configurable: true
  35242. });
  35243. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35244. /// This trigger will only be raised if you also declared a OnPickDown
  35245. get: function () {
  35246. return ActionManager._OnPickOutTrigger;
  35247. },
  35248. enumerable: true,
  35249. configurable: true
  35250. });
  35251. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35252. get: function () {
  35253. return ActionManager._OnLongPressTrigger;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35259. get: function () {
  35260. return ActionManager._OnPointerOverTrigger;
  35261. },
  35262. enumerable: true,
  35263. configurable: true
  35264. });
  35265. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35266. get: function () {
  35267. return ActionManager._OnPointerOutTrigger;
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35273. get: function () {
  35274. return ActionManager._OnEveryFrameTrigger;
  35275. },
  35276. enumerable: true,
  35277. configurable: true
  35278. });
  35279. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35280. get: function () {
  35281. return ActionManager._OnIntersectionEnterTrigger;
  35282. },
  35283. enumerable: true,
  35284. configurable: true
  35285. });
  35286. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35287. get: function () {
  35288. return ActionManager._OnIntersectionExitTrigger;
  35289. },
  35290. enumerable: true,
  35291. configurable: true
  35292. });
  35293. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35294. get: function () {
  35295. return ActionManager._OnKeyDownTrigger;
  35296. },
  35297. enumerable: true,
  35298. configurable: true
  35299. });
  35300. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35301. get: function () {
  35302. return ActionManager._OnKeyUpTrigger;
  35303. },
  35304. enumerable: true,
  35305. configurable: true
  35306. });
  35307. // Methods
  35308. ActionManager.prototype.dispose = function () {
  35309. var index = this._scene._actionManagers.indexOf(this);
  35310. if (index > -1) {
  35311. this._scene._actionManagers.splice(index, 1);
  35312. }
  35313. };
  35314. ActionManager.prototype.getScene = function () {
  35315. return this._scene;
  35316. };
  35317. /**
  35318. * Does this action manager handles actions of any of the given triggers
  35319. * @param {number[]} triggers - the triggers to be tested
  35320. * @return {boolean} whether one (or more) of the triggers is handeled
  35321. */
  35322. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35323. for (var index = 0; index < this.actions.length; index++) {
  35324. var action = this.actions[index];
  35325. if (triggers.indexOf(action.trigger) > -1) {
  35326. return true;
  35327. }
  35328. }
  35329. return false;
  35330. };
  35331. /**
  35332. * Does this action manager handles actions of a given trigger
  35333. * @param {number} trigger - the trigger to be tested
  35334. * @return {boolean} whether the trigger is handeled
  35335. */
  35336. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35337. for (var index = 0; index < this.actions.length; index++) {
  35338. var action = this.actions[index];
  35339. if (action.trigger === trigger) {
  35340. return true;
  35341. }
  35342. }
  35343. return false;
  35344. };
  35345. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35346. /**
  35347. * Does this action manager has pointer triggers
  35348. * @return {boolean} whether or not it has pointer triggers
  35349. */
  35350. get: function () {
  35351. for (var index = 0; index < this.actions.length; index++) {
  35352. var action = this.actions[index];
  35353. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35354. return true;
  35355. }
  35356. }
  35357. return false;
  35358. },
  35359. enumerable: true,
  35360. configurable: true
  35361. });
  35362. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35363. /**
  35364. * Does this action manager has pick triggers
  35365. * @return {boolean} whether or not it has pick triggers
  35366. */
  35367. get: function () {
  35368. for (var index = 0; index < this.actions.length; index++) {
  35369. var action = this.actions[index];
  35370. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35371. return true;
  35372. }
  35373. }
  35374. return false;
  35375. },
  35376. enumerable: true,
  35377. configurable: true
  35378. });
  35379. /**
  35380. * Registers an action to this action manager
  35381. * @param {BABYLON.Action} action - the action to be registered
  35382. * @return {BABYLON.Action} the action amended (prepared) after registration
  35383. */
  35384. ActionManager.prototype.registerAction = function (action) {
  35385. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35386. if (this.getScene().actionManager !== this) {
  35387. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35388. return null;
  35389. }
  35390. }
  35391. this.actions.push(action);
  35392. action._actionManager = this;
  35393. action._prepare();
  35394. return action;
  35395. };
  35396. /**
  35397. * Process a specific trigger
  35398. * @param {number} trigger - the trigger to process
  35399. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35400. */
  35401. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35402. for (var index = 0; index < this.actions.length; index++) {
  35403. var action = this.actions[index];
  35404. if (action.trigger === trigger) {
  35405. if (trigger === ActionManager.OnKeyUpTrigger
  35406. || trigger === ActionManager.OnKeyDownTrigger) {
  35407. var parameter = action.getTriggerParameter();
  35408. if (parameter) {
  35409. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35410. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35411. if (actualkey !== parameter.toLowerCase()) {
  35412. continue;
  35413. }
  35414. }
  35415. }
  35416. action._executeCurrent(evt);
  35417. }
  35418. }
  35419. };
  35420. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35421. var properties = propertyPath.split(".");
  35422. for (var index = 0; index < properties.length - 1; index++) {
  35423. target = target[properties[index]];
  35424. }
  35425. return target;
  35426. };
  35427. ActionManager.prototype._getProperty = function (propertyPath) {
  35428. var properties = propertyPath.split(".");
  35429. return properties[properties.length - 1];
  35430. };
  35431. ActionManager.prototype.serialize = function (name) {
  35432. var root = {
  35433. children: [],
  35434. name: name,
  35435. type: 3,
  35436. properties: [] // Empty for root but required
  35437. };
  35438. for (var i = 0; i < this.actions.length; i++) {
  35439. var triggerObject = {
  35440. type: 0,
  35441. children: [],
  35442. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35443. properties: []
  35444. };
  35445. var triggerOptions = this.actions[i].triggerOptions;
  35446. if (triggerOptions && typeof triggerOptions !== "number") {
  35447. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35448. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35449. }
  35450. else {
  35451. var parameter = {};
  35452. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35453. if (triggerOptions.parameter.mesh) {
  35454. parameter._meshId = triggerOptions.parameter.mesh.id;
  35455. }
  35456. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35457. }
  35458. }
  35459. // Serialize child action, recursively
  35460. this.actions[i].serialize(triggerObject);
  35461. // Add serialized trigger
  35462. root.children.push(triggerObject);
  35463. }
  35464. return root;
  35465. };
  35466. ActionManager.Parse = function (parsedActions, object, scene) {
  35467. var actionManager = new BABYLON.ActionManager(scene);
  35468. if (object === null)
  35469. scene.actionManager = actionManager;
  35470. else
  35471. object.actionManager = actionManager;
  35472. // instanciate a new object
  35473. var instanciate = function (name, params) {
  35474. var newInstance = Object.create(BABYLON[name].prototype);
  35475. newInstance.constructor.apply(newInstance, params);
  35476. return newInstance;
  35477. };
  35478. var parseParameter = function (name, value, target, propertyPath) {
  35479. if (propertyPath === null) {
  35480. // String, boolean or float
  35481. var floatValue = parseFloat(value);
  35482. if (value === "true" || value === "false")
  35483. return value === "true";
  35484. else
  35485. return isNaN(floatValue) ? value : floatValue;
  35486. }
  35487. var effectiveTarget = propertyPath.split(".");
  35488. var values = value.split(",");
  35489. // Get effective Target
  35490. for (var i = 0; i < effectiveTarget.length; i++) {
  35491. target = target[effectiveTarget[i]];
  35492. }
  35493. // Return appropriate value with its type
  35494. if (typeof (target) === "boolean")
  35495. return values[0] === "true";
  35496. if (typeof (target) === "string")
  35497. return values[0];
  35498. // Parameters with multiple values such as Vector3 etc.
  35499. var split = new Array();
  35500. for (var i = 0; i < values.length; i++)
  35501. split.push(parseFloat(values[i]));
  35502. if (target instanceof BABYLON.Vector3)
  35503. return BABYLON.Vector3.FromArray(split);
  35504. if (target instanceof BABYLON.Vector4)
  35505. return BABYLON.Vector4.FromArray(split);
  35506. if (target instanceof BABYLON.Color3)
  35507. return BABYLON.Color3.FromArray(split);
  35508. if (target instanceof BABYLON.Color4)
  35509. return BABYLON.Color4.FromArray(split);
  35510. return parseFloat(values[0]);
  35511. };
  35512. // traverse graph per trigger
  35513. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35514. if (combineArray === void 0) { combineArray = null; }
  35515. if (parsedAction.detached)
  35516. return;
  35517. var parameters = new Array();
  35518. var target = null;
  35519. var propertyPath = null;
  35520. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35521. // Parameters
  35522. if (parsedAction.type === 2)
  35523. parameters.push(actionManager);
  35524. else
  35525. parameters.push(trigger);
  35526. if (combine) {
  35527. var actions = new Array();
  35528. for (var j = 0; j < parsedAction.combine.length; j++) {
  35529. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35530. }
  35531. parameters.push(actions);
  35532. }
  35533. else {
  35534. for (var i = 0; i < parsedAction.properties.length; i++) {
  35535. var value = parsedAction.properties[i].value;
  35536. var name = parsedAction.properties[i].name;
  35537. var targetType = parsedAction.properties[i].targetType;
  35538. if (name === "target")
  35539. if (targetType !== null && targetType === "SceneProperties")
  35540. value = target = scene;
  35541. else
  35542. value = target = scene.getNodeByName(value);
  35543. else if (name === "parent")
  35544. value = scene.getNodeByName(value);
  35545. else if (name === "sound")
  35546. value = scene.getSoundByName(value);
  35547. else if (name !== "propertyPath") {
  35548. if (parsedAction.type === 2 && name === "operator")
  35549. value = BABYLON.ValueCondition[value];
  35550. else
  35551. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35552. }
  35553. else {
  35554. propertyPath = value;
  35555. }
  35556. parameters.push(value);
  35557. }
  35558. }
  35559. if (combineArray === null) {
  35560. parameters.push(condition);
  35561. }
  35562. else {
  35563. parameters.push(null);
  35564. }
  35565. // If interpolate value action
  35566. if (parsedAction.name === "InterpolateValueAction") {
  35567. var param = parameters[parameters.length - 2];
  35568. parameters[parameters.length - 1] = param;
  35569. parameters[parameters.length - 2] = condition;
  35570. }
  35571. // Action or condition(s) and not CombineAction
  35572. var newAction = instanciate(parsedAction.name, parameters);
  35573. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35574. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35575. if (action)
  35576. action.then(nothing);
  35577. else
  35578. actionManager.registerAction(nothing);
  35579. action = nothing;
  35580. }
  35581. if (combineArray === null) {
  35582. if (newAction instanceof BABYLON.Condition) {
  35583. condition = newAction;
  35584. newAction = action;
  35585. }
  35586. else {
  35587. condition = null;
  35588. if (action)
  35589. action.then(newAction);
  35590. else
  35591. actionManager.registerAction(newAction);
  35592. }
  35593. }
  35594. else {
  35595. combineArray.push(newAction);
  35596. }
  35597. for (var i = 0; i < parsedAction.children.length; i++)
  35598. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35599. };
  35600. // triggers
  35601. for (var i = 0; i < parsedActions.children.length; i++) {
  35602. var triggerParams;
  35603. var trigger = parsedActions.children[i];
  35604. if (trigger.properties.length > 0) {
  35605. var param = trigger.properties[0].value;
  35606. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35607. if (value._meshId) {
  35608. value.mesh = scene.getMeshByID(value._meshId);
  35609. }
  35610. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35611. }
  35612. else
  35613. triggerParams = BABYLON.ActionManager[trigger.name];
  35614. for (var j = 0; j < trigger.children.length; j++) {
  35615. if (!trigger.detached)
  35616. traverse(trigger.children[j], triggerParams, null, null);
  35617. }
  35618. }
  35619. };
  35620. ActionManager.GetTriggerName = function (trigger) {
  35621. switch (trigger) {
  35622. case 0: return "NothingTrigger";
  35623. case 1: return "OnPickTrigger";
  35624. case 2: return "OnLeftPickTrigger";
  35625. case 3: return "OnRightPickTrigger";
  35626. case 4: return "OnCenterPickTrigger";
  35627. case 5: return "OnPickDownTrigger";
  35628. case 6: return "OnPickUpTrigger";
  35629. case 7: return "OnLongPressTrigger";
  35630. case 8: return "OnPointerOverTrigger";
  35631. case 9: return "OnPointerOutTrigger";
  35632. case 10: return "OnEveryFrameTrigger";
  35633. case 11: return "OnIntersectionEnterTrigger";
  35634. case 12: return "OnIntersectionExitTrigger";
  35635. case 13: return "OnKeyDownTrigger";
  35636. case 14: return "OnKeyUpTrigger";
  35637. case 15: return "OnPickOutTrigger";
  35638. default: return "";
  35639. }
  35640. };
  35641. // Statics
  35642. ActionManager._NothingTrigger = 0;
  35643. ActionManager._OnPickTrigger = 1;
  35644. ActionManager._OnLeftPickTrigger = 2;
  35645. ActionManager._OnRightPickTrigger = 3;
  35646. ActionManager._OnCenterPickTrigger = 4;
  35647. ActionManager._OnPickDownTrigger = 5;
  35648. ActionManager._OnPickUpTrigger = 6;
  35649. ActionManager._OnLongPressTrigger = 7;
  35650. ActionManager._OnPointerOverTrigger = 8;
  35651. ActionManager._OnPointerOutTrigger = 9;
  35652. ActionManager._OnEveryFrameTrigger = 10;
  35653. ActionManager._OnIntersectionEnterTrigger = 11;
  35654. ActionManager._OnIntersectionExitTrigger = 12;
  35655. ActionManager._OnKeyDownTrigger = 13;
  35656. ActionManager._OnKeyUpTrigger = 14;
  35657. ActionManager._OnPickOutTrigger = 15;
  35658. ActionManager.DragMovementThreshold = 10; // in pixels
  35659. ActionManager.LongPressDelay = 500; // in milliseconds
  35660. return ActionManager;
  35661. }());
  35662. BABYLON.ActionManager = ActionManager;
  35663. })(BABYLON || (BABYLON = {}));
  35664. //# sourceMappingURL=babylon.actionManager.js.map
  35665. var BABYLON;
  35666. (function (BABYLON) {
  35667. var InterpolateValueAction = (function (_super) {
  35668. __extends(InterpolateValueAction, _super);
  35669. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35670. if (duration === void 0) { duration = 1000; }
  35671. _super.call(this, triggerOptions, condition);
  35672. this.propertyPath = propertyPath;
  35673. this.value = value;
  35674. this.duration = duration;
  35675. this.stopOtherAnimations = stopOtherAnimations;
  35676. this.onInterpolationDone = onInterpolationDone;
  35677. this._target = this._effectiveTarget = target;
  35678. }
  35679. InterpolateValueAction.prototype._prepare = function () {
  35680. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35681. this._property = this._getProperty(this.propertyPath);
  35682. };
  35683. InterpolateValueAction.prototype.execute = function () {
  35684. var scene = this._actionManager.getScene();
  35685. var keys = [
  35686. {
  35687. frame: 0,
  35688. value: this._effectiveTarget[this._property]
  35689. }, {
  35690. frame: 100,
  35691. value: this.value
  35692. }
  35693. ];
  35694. var dataType;
  35695. if (typeof this.value === "number") {
  35696. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35697. }
  35698. else if (this.value instanceof BABYLON.Color3) {
  35699. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35700. }
  35701. else if (this.value instanceof BABYLON.Vector3) {
  35702. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35703. }
  35704. else if (this.value instanceof BABYLON.Matrix) {
  35705. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35706. }
  35707. else if (this.value instanceof BABYLON.Quaternion) {
  35708. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35709. }
  35710. else {
  35711. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35712. return;
  35713. }
  35714. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35715. animation.setKeys(keys);
  35716. if (this.stopOtherAnimations) {
  35717. scene.stopAnimation(this._effectiveTarget);
  35718. }
  35719. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35720. };
  35721. InterpolateValueAction.prototype.serialize = function (parent) {
  35722. return _super.prototype._serialize.call(this, {
  35723. name: "InterpolateValueAction",
  35724. properties: [
  35725. BABYLON.Action._GetTargetProperty(this._target),
  35726. { name: "propertyPath", value: this.propertyPath },
  35727. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35728. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35729. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35730. ]
  35731. }, parent);
  35732. };
  35733. return InterpolateValueAction;
  35734. }(BABYLON.Action));
  35735. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35736. })(BABYLON || (BABYLON = {}));
  35737. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35738. var BABYLON;
  35739. (function (BABYLON) {
  35740. var SwitchBooleanAction = (function (_super) {
  35741. __extends(SwitchBooleanAction, _super);
  35742. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35743. _super.call(this, triggerOptions, condition);
  35744. this.propertyPath = propertyPath;
  35745. this._target = this._effectiveTarget = target;
  35746. }
  35747. SwitchBooleanAction.prototype._prepare = function () {
  35748. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35749. this._property = this._getProperty(this.propertyPath);
  35750. };
  35751. SwitchBooleanAction.prototype.execute = function () {
  35752. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35753. };
  35754. SwitchBooleanAction.prototype.serialize = function (parent) {
  35755. return _super.prototype._serialize.call(this, {
  35756. name: "SwitchBooleanAction",
  35757. properties: [
  35758. BABYLON.Action._GetTargetProperty(this._target),
  35759. { name: "propertyPath", value: this.propertyPath }
  35760. ]
  35761. }, parent);
  35762. };
  35763. return SwitchBooleanAction;
  35764. }(BABYLON.Action));
  35765. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35766. var SetStateAction = (function (_super) {
  35767. __extends(SetStateAction, _super);
  35768. function SetStateAction(triggerOptions, target, value, condition) {
  35769. _super.call(this, triggerOptions, condition);
  35770. this.value = value;
  35771. this._target = target;
  35772. }
  35773. SetStateAction.prototype.execute = function () {
  35774. this._target.state = this.value;
  35775. };
  35776. SetStateAction.prototype.serialize = function (parent) {
  35777. return _super.prototype._serialize.call(this, {
  35778. name: "SetStateAction",
  35779. properties: [
  35780. BABYLON.Action._GetTargetProperty(this._target),
  35781. { name: "value", value: this.value }
  35782. ]
  35783. }, parent);
  35784. };
  35785. return SetStateAction;
  35786. }(BABYLON.Action));
  35787. BABYLON.SetStateAction = SetStateAction;
  35788. var SetValueAction = (function (_super) {
  35789. __extends(SetValueAction, _super);
  35790. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35791. _super.call(this, triggerOptions, condition);
  35792. this.propertyPath = propertyPath;
  35793. this.value = value;
  35794. this._target = this._effectiveTarget = target;
  35795. }
  35796. SetValueAction.prototype._prepare = function () {
  35797. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35798. this._property = this._getProperty(this.propertyPath);
  35799. };
  35800. SetValueAction.prototype.execute = function () {
  35801. this._effectiveTarget[this._property] = this.value;
  35802. if (this._target.markAsDirty) {
  35803. this._target.markAsDirty(this._property);
  35804. }
  35805. };
  35806. SetValueAction.prototype.serialize = function (parent) {
  35807. return _super.prototype._serialize.call(this, {
  35808. name: "SetValueAction",
  35809. properties: [
  35810. BABYLON.Action._GetTargetProperty(this._target),
  35811. { name: "propertyPath", value: this.propertyPath },
  35812. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35813. ]
  35814. }, parent);
  35815. };
  35816. return SetValueAction;
  35817. }(BABYLON.Action));
  35818. BABYLON.SetValueAction = SetValueAction;
  35819. var IncrementValueAction = (function (_super) {
  35820. __extends(IncrementValueAction, _super);
  35821. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35822. _super.call(this, triggerOptions, condition);
  35823. this.propertyPath = propertyPath;
  35824. this.value = value;
  35825. this._target = this._effectiveTarget = target;
  35826. }
  35827. IncrementValueAction.prototype._prepare = function () {
  35828. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35829. this._property = this._getProperty(this.propertyPath);
  35830. if (typeof this._effectiveTarget[this._property] !== "number") {
  35831. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35832. }
  35833. };
  35834. IncrementValueAction.prototype.execute = function () {
  35835. this._effectiveTarget[this._property] += this.value;
  35836. if (this._target.markAsDirty) {
  35837. this._target.markAsDirty(this._property);
  35838. }
  35839. };
  35840. IncrementValueAction.prototype.serialize = function (parent) {
  35841. return _super.prototype._serialize.call(this, {
  35842. name: "IncrementValueAction",
  35843. properties: [
  35844. BABYLON.Action._GetTargetProperty(this._target),
  35845. { name: "propertyPath", value: this.propertyPath },
  35846. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35847. ]
  35848. }, parent);
  35849. };
  35850. return IncrementValueAction;
  35851. }(BABYLON.Action));
  35852. BABYLON.IncrementValueAction = IncrementValueAction;
  35853. var PlayAnimationAction = (function (_super) {
  35854. __extends(PlayAnimationAction, _super);
  35855. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35856. _super.call(this, triggerOptions, condition);
  35857. this.from = from;
  35858. this.to = to;
  35859. this.loop = loop;
  35860. this._target = target;
  35861. }
  35862. PlayAnimationAction.prototype._prepare = function () {
  35863. };
  35864. PlayAnimationAction.prototype.execute = function () {
  35865. var scene = this._actionManager.getScene();
  35866. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35867. };
  35868. PlayAnimationAction.prototype.serialize = function (parent) {
  35869. return _super.prototype._serialize.call(this, {
  35870. name: "PlayAnimationAction",
  35871. properties: [
  35872. BABYLON.Action._GetTargetProperty(this._target),
  35873. { name: "from", value: String(this.from) },
  35874. { name: "to", value: String(this.to) },
  35875. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35876. ]
  35877. }, parent);
  35878. };
  35879. return PlayAnimationAction;
  35880. }(BABYLON.Action));
  35881. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35882. var StopAnimationAction = (function (_super) {
  35883. __extends(StopAnimationAction, _super);
  35884. function StopAnimationAction(triggerOptions, target, condition) {
  35885. _super.call(this, triggerOptions, condition);
  35886. this._target = target;
  35887. }
  35888. StopAnimationAction.prototype._prepare = function () {
  35889. };
  35890. StopAnimationAction.prototype.execute = function () {
  35891. var scene = this._actionManager.getScene();
  35892. scene.stopAnimation(this._target);
  35893. };
  35894. StopAnimationAction.prototype.serialize = function (parent) {
  35895. return _super.prototype._serialize.call(this, {
  35896. name: "StopAnimationAction",
  35897. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35898. }, parent);
  35899. };
  35900. return StopAnimationAction;
  35901. }(BABYLON.Action));
  35902. BABYLON.StopAnimationAction = StopAnimationAction;
  35903. var DoNothingAction = (function (_super) {
  35904. __extends(DoNothingAction, _super);
  35905. function DoNothingAction(triggerOptions, condition) {
  35906. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35907. _super.call(this, triggerOptions, condition);
  35908. }
  35909. DoNothingAction.prototype.execute = function () {
  35910. };
  35911. DoNothingAction.prototype.serialize = function (parent) {
  35912. return _super.prototype._serialize.call(this, {
  35913. name: "DoNothingAction",
  35914. properties: []
  35915. }, parent);
  35916. };
  35917. return DoNothingAction;
  35918. }(BABYLON.Action));
  35919. BABYLON.DoNothingAction = DoNothingAction;
  35920. var CombineAction = (function (_super) {
  35921. __extends(CombineAction, _super);
  35922. function CombineAction(triggerOptions, children, condition) {
  35923. _super.call(this, triggerOptions, condition);
  35924. this.children = children;
  35925. }
  35926. CombineAction.prototype._prepare = function () {
  35927. for (var index = 0; index < this.children.length; index++) {
  35928. this.children[index]._actionManager = this._actionManager;
  35929. this.children[index]._prepare();
  35930. }
  35931. };
  35932. CombineAction.prototype.execute = function (evt) {
  35933. for (var index = 0; index < this.children.length; index++) {
  35934. this.children[index].execute(evt);
  35935. }
  35936. };
  35937. CombineAction.prototype.serialize = function (parent) {
  35938. var serializationObject = _super.prototype._serialize.call(this, {
  35939. name: "CombineAction",
  35940. properties: [],
  35941. combine: []
  35942. }, parent);
  35943. for (var i = 0; i < this.children.length; i++) {
  35944. serializationObject.combine.push(this.children[i].serialize(null));
  35945. }
  35946. return serializationObject;
  35947. };
  35948. return CombineAction;
  35949. }(BABYLON.Action));
  35950. BABYLON.CombineAction = CombineAction;
  35951. var ExecuteCodeAction = (function (_super) {
  35952. __extends(ExecuteCodeAction, _super);
  35953. function ExecuteCodeAction(triggerOptions, func, condition) {
  35954. _super.call(this, triggerOptions, condition);
  35955. this.func = func;
  35956. }
  35957. ExecuteCodeAction.prototype.execute = function (evt) {
  35958. this.func(evt);
  35959. };
  35960. return ExecuteCodeAction;
  35961. }(BABYLON.Action));
  35962. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  35963. var SetParentAction = (function (_super) {
  35964. __extends(SetParentAction, _super);
  35965. function SetParentAction(triggerOptions, target, parent, condition) {
  35966. _super.call(this, triggerOptions, condition);
  35967. this._target = target;
  35968. this._parent = parent;
  35969. }
  35970. SetParentAction.prototype._prepare = function () {
  35971. };
  35972. SetParentAction.prototype.execute = function () {
  35973. if (this._target.parent === this._parent) {
  35974. return;
  35975. }
  35976. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  35977. invertParentWorldMatrix.invert();
  35978. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  35979. this._target.parent = this._parent;
  35980. };
  35981. SetParentAction.prototype.serialize = function (parent) {
  35982. return _super.prototype._serialize.call(this, {
  35983. name: "SetParentAction",
  35984. properties: [
  35985. BABYLON.Action._GetTargetProperty(this._target),
  35986. BABYLON.Action._GetTargetProperty(this._parent),
  35987. ]
  35988. }, parent);
  35989. };
  35990. return SetParentAction;
  35991. }(BABYLON.Action));
  35992. BABYLON.SetParentAction = SetParentAction;
  35993. var PlaySoundAction = (function (_super) {
  35994. __extends(PlaySoundAction, _super);
  35995. function PlaySoundAction(triggerOptions, sound, condition) {
  35996. _super.call(this, triggerOptions, condition);
  35997. this._sound = sound;
  35998. }
  35999. PlaySoundAction.prototype._prepare = function () {
  36000. };
  36001. PlaySoundAction.prototype.execute = function () {
  36002. if (this._sound !== undefined)
  36003. this._sound.play();
  36004. };
  36005. PlaySoundAction.prototype.serialize = function (parent) {
  36006. return _super.prototype._serialize.call(this, {
  36007. name: "PlaySoundAction",
  36008. properties: [{ name: "sound", value: this._sound.name }]
  36009. }, parent);
  36010. };
  36011. return PlaySoundAction;
  36012. }(BABYLON.Action));
  36013. BABYLON.PlaySoundAction = PlaySoundAction;
  36014. var StopSoundAction = (function (_super) {
  36015. __extends(StopSoundAction, _super);
  36016. function StopSoundAction(triggerOptions, sound, condition) {
  36017. _super.call(this, triggerOptions, condition);
  36018. this._sound = sound;
  36019. }
  36020. StopSoundAction.prototype._prepare = function () {
  36021. };
  36022. StopSoundAction.prototype.execute = function () {
  36023. if (this._sound !== undefined)
  36024. this._sound.stop();
  36025. };
  36026. StopSoundAction.prototype.serialize = function (parent) {
  36027. return _super.prototype._serialize.call(this, {
  36028. name: "StopSoundAction",
  36029. properties: [{ name: "sound", value: this._sound.name }]
  36030. }, parent);
  36031. };
  36032. return StopSoundAction;
  36033. }(BABYLON.Action));
  36034. BABYLON.StopSoundAction = StopSoundAction;
  36035. })(BABYLON || (BABYLON = {}));
  36036. //# sourceMappingURL=babylon.directActions.js.map
  36037. var BABYLON;
  36038. (function (BABYLON) {
  36039. var Geometry = (function () {
  36040. function Geometry(id, scene, vertexData, updatable, mesh) {
  36041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36042. this._totalVertices = 0;
  36043. this._isDisposed = false;
  36044. this.id = id;
  36045. this._engine = scene.getEngine();
  36046. this._meshes = [];
  36047. this._scene = scene;
  36048. //Init vertex buffer cache
  36049. this._vertexBuffers = {};
  36050. this._indices = [];
  36051. // vertexData
  36052. if (vertexData) {
  36053. this.setAllVerticesData(vertexData, updatable);
  36054. }
  36055. else {
  36056. this._totalVertices = 0;
  36057. this._indices = [];
  36058. }
  36059. // applyToMesh
  36060. if (mesh) {
  36061. if (mesh instanceof BABYLON.LinesMesh) {
  36062. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36063. this.updateExtend();
  36064. }
  36065. this.applyToMesh(mesh);
  36066. mesh.computeWorldMatrix(true);
  36067. }
  36068. }
  36069. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36070. /**
  36071. * 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
  36072. * @returns The Bias Vector
  36073. */
  36074. get: function () {
  36075. return this._boundingBias;
  36076. },
  36077. set: function (value) {
  36078. if (this._boundingBias && this._boundingBias.equals(value)) {
  36079. return;
  36080. }
  36081. this._boundingBias = value.clone();
  36082. this.updateBoundingInfo(true, null);
  36083. },
  36084. enumerable: true,
  36085. configurable: true
  36086. });
  36087. Object.defineProperty(Geometry.prototype, "extend", {
  36088. get: function () {
  36089. return this._extend;
  36090. },
  36091. enumerable: true,
  36092. configurable: true
  36093. });
  36094. Geometry.prototype.getScene = function () {
  36095. return this._scene;
  36096. };
  36097. Geometry.prototype.getEngine = function () {
  36098. return this._engine;
  36099. };
  36100. Geometry.prototype.isReady = function () {
  36101. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36102. };
  36103. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36104. get: function () {
  36105. for (var index = 0; index < this._meshes.length; index++) {
  36106. if (!this._meshes[index].doNotSerialize) {
  36107. return false;
  36108. }
  36109. }
  36110. return true;
  36111. },
  36112. enumerable: true,
  36113. configurable: true
  36114. });
  36115. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36116. vertexData.applyToGeometry(this, updatable);
  36117. this.notifyUpdate();
  36118. };
  36119. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36120. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36121. this.setVerticesBuffer(buffer);
  36122. };
  36123. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36124. var kind = buffer.getKind();
  36125. if (this._vertexBuffers[kind]) {
  36126. this._vertexBuffers[kind].dispose();
  36127. }
  36128. this._vertexBuffers[kind] = buffer;
  36129. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36130. var data = buffer.getData();
  36131. var stride = buffer.getStrideSize();
  36132. this._totalVertices = data.length / stride;
  36133. this.updateExtend(data, stride);
  36134. var meshes = this._meshes;
  36135. var numOfMeshes = meshes.length;
  36136. for (var index = 0; index < numOfMeshes; index++) {
  36137. var mesh = meshes[index];
  36138. mesh._resetPointsArrayCache();
  36139. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36140. mesh._createGlobalSubMesh();
  36141. mesh.computeWorldMatrix(true);
  36142. }
  36143. }
  36144. this.notifyUpdate(kind);
  36145. };
  36146. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36147. var vertexBuffer = this.getVertexBuffer(kind);
  36148. if (!vertexBuffer) {
  36149. return;
  36150. }
  36151. vertexBuffer.updateDirectly(data, offset);
  36152. this.notifyUpdate(kind);
  36153. };
  36154. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36155. var vertexBuffer = this.getVertexBuffer(kind);
  36156. if (!vertexBuffer) {
  36157. return;
  36158. }
  36159. vertexBuffer.update(data);
  36160. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36161. var stride = vertexBuffer.getStrideSize();
  36162. this._totalVertices = data.length / stride;
  36163. this.updateBoundingInfo(updateExtends, data);
  36164. }
  36165. this.notifyUpdate(kind);
  36166. };
  36167. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36168. if (updateExtends) {
  36169. this.updateExtend(data);
  36170. }
  36171. var meshes = this._meshes;
  36172. var numOfMeshes = meshes.length;
  36173. for (var index = 0; index < numOfMeshes; index++) {
  36174. var mesh = meshes[index];
  36175. mesh._resetPointsArrayCache();
  36176. if (updateExtends) {
  36177. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36178. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36179. var subMesh = mesh.subMeshes[subIndex];
  36180. subMesh.refreshBoundingInfo();
  36181. }
  36182. }
  36183. }
  36184. };
  36185. Geometry.prototype.getTotalVertices = function () {
  36186. if (!this.isReady()) {
  36187. return 0;
  36188. }
  36189. return this._totalVertices;
  36190. };
  36191. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36192. var vertexBuffer = this.getVertexBuffer(kind);
  36193. if (!vertexBuffer) {
  36194. return null;
  36195. }
  36196. var orig = vertexBuffer.getData();
  36197. if (!copyWhenShared || this._meshes.length === 1) {
  36198. return orig;
  36199. }
  36200. else {
  36201. var len = orig.length;
  36202. var copy = [];
  36203. for (var i = 0; i < len; i++) {
  36204. copy.push(orig[i]);
  36205. }
  36206. return copy;
  36207. }
  36208. };
  36209. Geometry.prototype.getVertexBuffer = function (kind) {
  36210. if (!this.isReady()) {
  36211. return null;
  36212. }
  36213. return this._vertexBuffers[kind];
  36214. };
  36215. Geometry.prototype.getVertexBuffers = function () {
  36216. if (!this.isReady()) {
  36217. return null;
  36218. }
  36219. return this._vertexBuffers;
  36220. };
  36221. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36222. if (!this._vertexBuffers) {
  36223. if (this._delayInfo) {
  36224. return this._delayInfo.indexOf(kind) !== -1;
  36225. }
  36226. return false;
  36227. }
  36228. return this._vertexBuffers[kind] !== undefined;
  36229. };
  36230. Geometry.prototype.getVerticesDataKinds = function () {
  36231. var result = [];
  36232. var kind;
  36233. if (!this._vertexBuffers && this._delayInfo) {
  36234. for (kind in this._delayInfo) {
  36235. result.push(kind);
  36236. }
  36237. }
  36238. else {
  36239. for (kind in this._vertexBuffers) {
  36240. result.push(kind);
  36241. }
  36242. }
  36243. return result;
  36244. };
  36245. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36246. if (this._indexBuffer) {
  36247. this._engine._releaseBuffer(this._indexBuffer);
  36248. }
  36249. this._indices = indices;
  36250. if (this._meshes.length !== 0 && this._indices) {
  36251. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36252. }
  36253. if (totalVertices !== undefined) {
  36254. this._totalVertices = totalVertices;
  36255. }
  36256. var meshes = this._meshes;
  36257. var numOfMeshes = meshes.length;
  36258. for (var index = 0; index < numOfMeshes; index++) {
  36259. meshes[index]._createGlobalSubMesh();
  36260. }
  36261. this.notifyUpdate();
  36262. };
  36263. Geometry.prototype.getTotalIndices = function () {
  36264. if (!this.isReady()) {
  36265. return 0;
  36266. }
  36267. return this._indices.length;
  36268. };
  36269. Geometry.prototype.getIndices = function (copyWhenShared) {
  36270. if (!this.isReady()) {
  36271. return null;
  36272. }
  36273. var orig = this._indices;
  36274. if (!copyWhenShared || this._meshes.length === 1) {
  36275. return orig;
  36276. }
  36277. else {
  36278. var len = orig.length;
  36279. var copy = [];
  36280. for (var i = 0; i < len; i++) {
  36281. copy.push(orig[i]);
  36282. }
  36283. return copy;
  36284. }
  36285. };
  36286. Geometry.prototype.getIndexBuffer = function () {
  36287. if (!this.isReady()) {
  36288. return null;
  36289. }
  36290. return this._indexBuffer;
  36291. };
  36292. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36293. var meshes = this._meshes;
  36294. var index = meshes.indexOf(mesh);
  36295. if (index === -1) {
  36296. return;
  36297. }
  36298. for (var kind in this._vertexBuffers) {
  36299. this._vertexBuffers[kind].dispose();
  36300. }
  36301. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36302. this._indexBuffer = null;
  36303. }
  36304. meshes.splice(index, 1);
  36305. mesh._geometry = null;
  36306. if (meshes.length === 0 && shouldDispose) {
  36307. this.dispose();
  36308. }
  36309. };
  36310. Geometry.prototype.applyToMesh = function (mesh) {
  36311. if (mesh._geometry === this) {
  36312. return;
  36313. }
  36314. var previousGeometry = mesh._geometry;
  36315. if (previousGeometry) {
  36316. previousGeometry.releaseForMesh(mesh);
  36317. }
  36318. var meshes = this._meshes;
  36319. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36320. mesh._geometry = this;
  36321. this._scene.pushGeometry(this);
  36322. meshes.push(mesh);
  36323. if (this.isReady()) {
  36324. this._applyToMesh(mesh);
  36325. }
  36326. else {
  36327. mesh._boundingInfo = this._boundingInfo;
  36328. }
  36329. };
  36330. Geometry.prototype.updateExtend = function (data, stride) {
  36331. if (data === void 0) { data = null; }
  36332. if (!data) {
  36333. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36334. }
  36335. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36336. };
  36337. Geometry.prototype._applyToMesh = function (mesh) {
  36338. var numOfMeshes = this._meshes.length;
  36339. // vertexBuffers
  36340. for (var kind in this._vertexBuffers) {
  36341. if (numOfMeshes === 1) {
  36342. this._vertexBuffers[kind].create();
  36343. }
  36344. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36345. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36346. mesh._resetPointsArrayCache();
  36347. if (!this._extend) {
  36348. this.updateExtend(this._vertexBuffers[kind].getData());
  36349. }
  36350. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36351. mesh._createGlobalSubMesh();
  36352. //bounding info was just created again, world matrix should be applied again.
  36353. mesh._updateBoundingInfo();
  36354. }
  36355. }
  36356. // indexBuffer
  36357. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36358. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36359. }
  36360. if (this._indexBuffer) {
  36361. this._indexBuffer.references = numOfMeshes;
  36362. }
  36363. };
  36364. Geometry.prototype.notifyUpdate = function (kind) {
  36365. if (this.onGeometryUpdated) {
  36366. this.onGeometryUpdated(this, kind);
  36367. }
  36368. };
  36369. Geometry.prototype.load = function (scene, onLoaded) {
  36370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36371. return;
  36372. }
  36373. if (this.isReady()) {
  36374. if (onLoaded) {
  36375. onLoaded();
  36376. }
  36377. return;
  36378. }
  36379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36380. this._queueLoad(scene, onLoaded);
  36381. };
  36382. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36383. var _this = this;
  36384. scene._addPendingData(this);
  36385. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36386. _this._delayLoadingFunction(JSON.parse(data), _this);
  36387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36388. _this._delayInfo = [];
  36389. scene._removePendingData(_this);
  36390. var meshes = _this._meshes;
  36391. var numOfMeshes = meshes.length;
  36392. for (var index = 0; index < numOfMeshes; index++) {
  36393. _this._applyToMesh(meshes[index]);
  36394. }
  36395. if (onLoaded) {
  36396. onLoaded();
  36397. }
  36398. }, function () { }, scene.database);
  36399. };
  36400. /**
  36401. * Invert the geometry to move from a right handed system to a left handed one.
  36402. */
  36403. Geometry.prototype.toLeftHanded = function () {
  36404. // Flip faces
  36405. var tIndices = this.getIndices(false);
  36406. if (tIndices != null && tIndices.length > 0) {
  36407. for (var i = 0; i < tIndices.length; i += 3) {
  36408. var tTemp = tIndices[i + 0];
  36409. tIndices[i + 0] = tIndices[i + 2];
  36410. tIndices[i + 2] = tTemp;
  36411. }
  36412. this.setIndices(tIndices);
  36413. }
  36414. // Negate position.z
  36415. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36416. if (tPositions != null && tPositions.length > 0) {
  36417. for (var i = 0; i < tPositions.length; i += 3) {
  36418. tPositions[i + 2] = -tPositions[i + 2];
  36419. }
  36420. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36421. }
  36422. // Negate normal.z
  36423. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36424. if (tNormals != null && tNormals.length > 0) {
  36425. for (var i = 0; i < tNormals.length; i += 3) {
  36426. tNormals[i + 2] = -tNormals[i + 2];
  36427. }
  36428. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36429. }
  36430. };
  36431. Geometry.prototype.isDisposed = function () {
  36432. return this._isDisposed;
  36433. };
  36434. Geometry.prototype.dispose = function () {
  36435. var meshes = this._meshes;
  36436. var numOfMeshes = meshes.length;
  36437. var index;
  36438. for (index = 0; index < numOfMeshes; index++) {
  36439. this.releaseForMesh(meshes[index]);
  36440. }
  36441. this._meshes = [];
  36442. for (var kind in this._vertexBuffers) {
  36443. this._vertexBuffers[kind].dispose();
  36444. }
  36445. this._vertexBuffers = {};
  36446. this._totalVertices = 0;
  36447. if (this._indexBuffer) {
  36448. this._engine._releaseBuffer(this._indexBuffer);
  36449. }
  36450. this._indexBuffer = null;
  36451. this._indices = [];
  36452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36453. this.delayLoadingFile = null;
  36454. this._delayLoadingFunction = null;
  36455. this._delayInfo = [];
  36456. this._boundingInfo = null;
  36457. this._scene.removeGeometry(this);
  36458. this._isDisposed = true;
  36459. };
  36460. Geometry.prototype.copy = function (id) {
  36461. var vertexData = new BABYLON.VertexData();
  36462. vertexData.indices = [];
  36463. var indices = this.getIndices();
  36464. for (var index = 0; index < indices.length; index++) {
  36465. vertexData.indices.push(indices[index]);
  36466. }
  36467. var updatable = false;
  36468. var stopChecking = false;
  36469. var kind;
  36470. for (kind in this._vertexBuffers) {
  36471. // using slice() to make a copy of the array and not just reference it
  36472. var data = this.getVerticesData(kind);
  36473. if (data instanceof Float32Array) {
  36474. vertexData.set(new Float32Array(data), kind);
  36475. }
  36476. else {
  36477. vertexData.set(data.slice(0), kind);
  36478. }
  36479. if (!stopChecking) {
  36480. updatable = this.getVertexBuffer(kind).isUpdatable();
  36481. stopChecking = !updatable;
  36482. }
  36483. }
  36484. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36485. geometry.delayLoadState = this.delayLoadState;
  36486. geometry.delayLoadingFile = this.delayLoadingFile;
  36487. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36488. for (kind in this._delayInfo) {
  36489. geometry._delayInfo = geometry._delayInfo || [];
  36490. geometry._delayInfo.push(kind);
  36491. }
  36492. // Bounding info
  36493. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36494. return geometry;
  36495. };
  36496. Geometry.prototype.serialize = function () {
  36497. var serializationObject = {};
  36498. serializationObject.id = this.id;
  36499. if (BABYLON.Tags.HasTags(this)) {
  36500. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36501. }
  36502. return serializationObject;
  36503. };
  36504. Geometry.prototype.serializeVerticeData = function () {
  36505. var serializationObject = this.serialize();
  36506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36507. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36508. }
  36509. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36510. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36511. }
  36512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36513. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36514. }
  36515. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36516. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36517. }
  36518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36519. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36520. }
  36521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36522. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36523. }
  36524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36525. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36526. }
  36527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36528. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36529. }
  36530. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36531. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36532. }
  36533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36534. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36535. serializationObject.matricesIndices._isExpanded = true;
  36536. }
  36537. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36538. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36539. }
  36540. serializationObject.indices = this.getIndices();
  36541. return serializationObject;
  36542. };
  36543. // Statics
  36544. Geometry.ExtractFromMesh = function (mesh, id) {
  36545. var geometry = mesh._geometry;
  36546. if (!geometry) {
  36547. return null;
  36548. }
  36549. return geometry.copy(id);
  36550. };
  36551. /**
  36552. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36553. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36554. * Be aware Math.random() could cause collisions, but:
  36555. * "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"
  36556. */
  36557. Geometry.RandomId = function () {
  36558. return BABYLON.Tools.RandomId();
  36559. };
  36560. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36561. var scene = mesh.getScene();
  36562. // Geometry
  36563. var geometryId = parsedGeometry.geometryId;
  36564. if (geometryId) {
  36565. var geometry = scene.getGeometryByID(geometryId);
  36566. if (geometry) {
  36567. geometry.applyToMesh(mesh);
  36568. }
  36569. }
  36570. else if (parsedGeometry instanceof ArrayBuffer) {
  36571. var binaryInfo = mesh._binaryInfo;
  36572. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36573. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36574. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36575. }
  36576. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36577. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36578. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36579. }
  36580. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36581. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36582. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36583. }
  36584. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36585. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36586. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36587. }
  36588. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36589. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36590. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36591. }
  36592. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36593. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36594. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36595. }
  36596. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36597. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36598. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36599. }
  36600. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36601. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36602. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36603. }
  36604. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36605. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36606. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36607. }
  36608. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36609. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36611. }
  36612. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36613. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36615. }
  36616. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36617. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36618. mesh.setIndices(indicesData);
  36619. }
  36620. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36621. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36622. mesh.subMeshes = [];
  36623. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36624. var materialIndex = subMeshesData[(i * 5) + 0];
  36625. var verticesStart = subMeshesData[(i * 5) + 1];
  36626. var verticesCount = subMeshesData[(i * 5) + 2];
  36627. var indexStart = subMeshesData[(i * 5) + 3];
  36628. var indexCount = subMeshesData[(i * 5) + 4];
  36629. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36630. }
  36631. }
  36632. }
  36633. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36634. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36635. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36636. if (parsedGeometry.uvs) {
  36637. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36638. }
  36639. if (parsedGeometry.uvs2) {
  36640. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36641. }
  36642. if (parsedGeometry.uvs3) {
  36643. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36644. }
  36645. if (parsedGeometry.uvs4) {
  36646. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36647. }
  36648. if (parsedGeometry.uvs5) {
  36649. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36650. }
  36651. if (parsedGeometry.uvs6) {
  36652. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36653. }
  36654. if (parsedGeometry.colors) {
  36655. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36656. }
  36657. if (parsedGeometry.matricesIndices) {
  36658. if (!parsedGeometry.matricesIndices._isExpanded) {
  36659. var floatIndices = [];
  36660. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36661. var matricesIndex = parsedGeometry.matricesIndices[i];
  36662. floatIndices.push(matricesIndex & 0x000000FF);
  36663. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36664. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36665. floatIndices.push(matricesIndex >> 24);
  36666. }
  36667. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36668. }
  36669. else {
  36670. delete parsedGeometry.matricesIndices._isExpanded;
  36671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36672. }
  36673. }
  36674. if (parsedGeometry.matricesIndicesExtra) {
  36675. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36676. var floatIndices = [];
  36677. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36678. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36679. floatIndices.push(matricesIndex & 0x000000FF);
  36680. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36681. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36682. floatIndices.push(matricesIndex >> 24);
  36683. }
  36684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36685. }
  36686. else {
  36687. delete parsedGeometry.matricesIndices._isExpanded;
  36688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36689. }
  36690. }
  36691. if (parsedGeometry.matricesWeights) {
  36692. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36693. }
  36694. if (parsedGeometry.matricesWeightsExtra) {
  36695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36696. }
  36697. mesh.setIndices(parsedGeometry.indices);
  36698. }
  36699. // SubMeshes
  36700. if (parsedGeometry.subMeshes) {
  36701. mesh.subMeshes = [];
  36702. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36703. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36704. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36705. }
  36706. }
  36707. // Flat shading
  36708. if (mesh._shouldGenerateFlatShading) {
  36709. mesh.convertToFlatShadedMesh();
  36710. delete mesh._shouldGenerateFlatShading;
  36711. }
  36712. // Update
  36713. mesh.computeWorldMatrix(true);
  36714. // Octree
  36715. if (scene['_selectionOctree']) {
  36716. scene['_selectionOctree'].addMesh(mesh);
  36717. }
  36718. };
  36719. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36720. if (scene.getGeometryByID(parsedVertexData.id)) {
  36721. return null; // null since geometry could be something else than a box...
  36722. }
  36723. var geometry = new Geometry(parsedVertexData.id, scene);
  36724. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36725. if (parsedVertexData.delayLoadingFile) {
  36726. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36727. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36728. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36729. geometry._delayInfo = [];
  36730. if (parsedVertexData.hasUVs) {
  36731. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36732. }
  36733. if (parsedVertexData.hasUVs2) {
  36734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36735. }
  36736. if (parsedVertexData.hasUVs3) {
  36737. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36738. }
  36739. if (parsedVertexData.hasUVs4) {
  36740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36741. }
  36742. if (parsedVertexData.hasUVs5) {
  36743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36744. }
  36745. if (parsedVertexData.hasUVs6) {
  36746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36747. }
  36748. if (parsedVertexData.hasColors) {
  36749. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36750. }
  36751. if (parsedVertexData.hasMatricesIndices) {
  36752. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36753. }
  36754. if (parsedVertexData.hasMatricesWeights) {
  36755. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36756. }
  36757. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36758. }
  36759. else {
  36760. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36761. }
  36762. scene.pushGeometry(geometry, true);
  36763. return geometry;
  36764. };
  36765. return Geometry;
  36766. }());
  36767. BABYLON.Geometry = Geometry;
  36768. /////// Primitives //////////////////////////////////////////////
  36769. var Geometry;
  36770. (function (Geometry) {
  36771. var Primitives;
  36772. (function (Primitives) {
  36773. /// Abstract class
  36774. var _Primitive = (function (_super) {
  36775. __extends(_Primitive, _super);
  36776. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36777. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  36778. this._canBeRegenerated = _canBeRegenerated;
  36779. this._beingRegenerated = true;
  36780. this.regenerate();
  36781. this._beingRegenerated = false;
  36782. }
  36783. _Primitive.prototype.canBeRegenerated = function () {
  36784. return this._canBeRegenerated;
  36785. };
  36786. _Primitive.prototype.regenerate = function () {
  36787. if (!this._canBeRegenerated) {
  36788. return;
  36789. }
  36790. this._beingRegenerated = true;
  36791. this.setAllVerticesData(this._regenerateVertexData(), false);
  36792. this._beingRegenerated = false;
  36793. };
  36794. _Primitive.prototype.asNewGeometry = function (id) {
  36795. return _super.prototype.copy.call(this, id);
  36796. };
  36797. // overrides
  36798. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36799. if (!this._beingRegenerated) {
  36800. return;
  36801. }
  36802. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36803. };
  36804. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36805. if (!this._beingRegenerated) {
  36806. return;
  36807. }
  36808. _super.prototype.setVerticesData.call(this, kind, data, false);
  36809. };
  36810. // to override
  36811. // protected
  36812. _Primitive.prototype._regenerateVertexData = function () {
  36813. throw new Error("Abstract method");
  36814. };
  36815. _Primitive.prototype.copy = function (id) {
  36816. throw new Error("Must be overriden in sub-classes.");
  36817. };
  36818. _Primitive.prototype.serialize = function () {
  36819. var serializationObject = _super.prototype.serialize.call(this);
  36820. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36821. return serializationObject;
  36822. };
  36823. return _Primitive;
  36824. }(Geometry));
  36825. Primitives._Primitive = _Primitive;
  36826. var Ribbon = (function (_super) {
  36827. __extends(Ribbon, _super);
  36828. // Members
  36829. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36830. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36831. _super.call(this, id, scene, canBeRegenerated, mesh);
  36832. this.pathArray = pathArray;
  36833. this.closeArray = closeArray;
  36834. this.closePath = closePath;
  36835. this.offset = offset;
  36836. this.side = side;
  36837. }
  36838. Ribbon.prototype._regenerateVertexData = function () {
  36839. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36840. };
  36841. Ribbon.prototype.copy = function (id) {
  36842. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36843. };
  36844. return Ribbon;
  36845. }(_Primitive));
  36846. Primitives.Ribbon = Ribbon;
  36847. var Box = (function (_super) {
  36848. __extends(Box, _super);
  36849. // Members
  36850. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36851. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36852. _super.call(this, id, scene, canBeRegenerated, mesh);
  36853. this.size = size;
  36854. this.side = side;
  36855. }
  36856. Box.prototype._regenerateVertexData = function () {
  36857. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36858. };
  36859. Box.prototype.copy = function (id) {
  36860. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36861. };
  36862. Box.prototype.serialize = function () {
  36863. var serializationObject = _super.prototype.serialize.call(this);
  36864. serializationObject.size = this.size;
  36865. return serializationObject;
  36866. };
  36867. Box.Parse = function (parsedBox, scene) {
  36868. if (scene.getGeometryByID(parsedBox.id)) {
  36869. return null; // null since geometry could be something else than a box...
  36870. }
  36871. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36872. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36873. scene.pushGeometry(box, true);
  36874. return box;
  36875. };
  36876. return Box;
  36877. }(_Primitive));
  36878. Primitives.Box = Box;
  36879. var Sphere = (function (_super) {
  36880. __extends(Sphere, _super);
  36881. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36882. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36883. _super.call(this, id, scene, canBeRegenerated, mesh);
  36884. this.segments = segments;
  36885. this.diameter = diameter;
  36886. this.side = side;
  36887. }
  36888. Sphere.prototype._regenerateVertexData = function () {
  36889. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36890. };
  36891. Sphere.prototype.copy = function (id) {
  36892. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36893. };
  36894. Sphere.prototype.serialize = function () {
  36895. var serializationObject = _super.prototype.serialize.call(this);
  36896. serializationObject.segments = this.segments;
  36897. serializationObject.diameter = this.diameter;
  36898. return serializationObject;
  36899. };
  36900. Sphere.Parse = function (parsedSphere, scene) {
  36901. if (scene.getGeometryByID(parsedSphere.id)) {
  36902. return null; // null since geometry could be something else than a sphere...
  36903. }
  36904. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36905. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36906. scene.pushGeometry(sphere, true);
  36907. return sphere;
  36908. };
  36909. return Sphere;
  36910. }(_Primitive));
  36911. Primitives.Sphere = Sphere;
  36912. var Disc = (function (_super) {
  36913. __extends(Disc, _super);
  36914. // Members
  36915. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36917. _super.call(this, id, scene, canBeRegenerated, mesh);
  36918. this.radius = radius;
  36919. this.tessellation = tessellation;
  36920. this.side = side;
  36921. }
  36922. Disc.prototype._regenerateVertexData = function () {
  36923. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36924. };
  36925. Disc.prototype.copy = function (id) {
  36926. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36927. };
  36928. return Disc;
  36929. }(_Primitive));
  36930. Primitives.Disc = Disc;
  36931. var Cylinder = (function (_super) {
  36932. __extends(Cylinder, _super);
  36933. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36934. if (subdivisions === void 0) { subdivisions = 1; }
  36935. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36936. _super.call(this, id, scene, canBeRegenerated, mesh);
  36937. this.height = height;
  36938. this.diameterTop = diameterTop;
  36939. this.diameterBottom = diameterBottom;
  36940. this.tessellation = tessellation;
  36941. this.subdivisions = subdivisions;
  36942. this.side = side;
  36943. }
  36944. Cylinder.prototype._regenerateVertexData = function () {
  36945. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36946. };
  36947. Cylinder.prototype.copy = function (id) {
  36948. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36949. };
  36950. Cylinder.prototype.serialize = function () {
  36951. var serializationObject = _super.prototype.serialize.call(this);
  36952. serializationObject.height = this.height;
  36953. serializationObject.diameterTop = this.diameterTop;
  36954. serializationObject.diameterBottom = this.diameterBottom;
  36955. serializationObject.tessellation = this.tessellation;
  36956. return serializationObject;
  36957. };
  36958. Cylinder.Parse = function (parsedCylinder, scene) {
  36959. if (scene.getGeometryByID(parsedCylinder.id)) {
  36960. return null; // null since geometry could be something else than a cylinder...
  36961. }
  36962. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36963. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36964. scene.pushGeometry(cylinder, true);
  36965. return cylinder;
  36966. };
  36967. return Cylinder;
  36968. }(_Primitive));
  36969. Primitives.Cylinder = Cylinder;
  36970. var Torus = (function (_super) {
  36971. __extends(Torus, _super);
  36972. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  36973. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36974. _super.call(this, id, scene, canBeRegenerated, mesh);
  36975. this.diameter = diameter;
  36976. this.thickness = thickness;
  36977. this.tessellation = tessellation;
  36978. this.side = side;
  36979. }
  36980. Torus.prototype._regenerateVertexData = function () {
  36981. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36982. };
  36983. Torus.prototype.copy = function (id) {
  36984. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36985. };
  36986. Torus.prototype.serialize = function () {
  36987. var serializationObject = _super.prototype.serialize.call(this);
  36988. serializationObject.diameter = this.diameter;
  36989. serializationObject.thickness = this.thickness;
  36990. serializationObject.tessellation = this.tessellation;
  36991. return serializationObject;
  36992. };
  36993. Torus.Parse = function (parsedTorus, scene) {
  36994. if (scene.getGeometryByID(parsedTorus.id)) {
  36995. return null; // null since geometry could be something else than a torus...
  36996. }
  36997. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36998. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36999. scene.pushGeometry(torus, true);
  37000. return torus;
  37001. };
  37002. return Torus;
  37003. }(_Primitive));
  37004. Primitives.Torus = Torus;
  37005. var Ground = (function (_super) {
  37006. __extends(Ground, _super);
  37007. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37008. _super.call(this, id, scene, canBeRegenerated, mesh);
  37009. this.width = width;
  37010. this.height = height;
  37011. this.subdivisions = subdivisions;
  37012. }
  37013. Ground.prototype._regenerateVertexData = function () {
  37014. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37015. };
  37016. Ground.prototype.copy = function (id) {
  37017. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37018. };
  37019. Ground.prototype.serialize = function () {
  37020. var serializationObject = _super.prototype.serialize.call(this);
  37021. serializationObject.width = this.width;
  37022. serializationObject.height = this.height;
  37023. serializationObject.subdivisions = this.subdivisions;
  37024. return serializationObject;
  37025. };
  37026. Ground.Parse = function (parsedGround, scene) {
  37027. if (scene.getGeometryByID(parsedGround.id)) {
  37028. return null; // null since geometry could be something else than a ground...
  37029. }
  37030. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37031. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37032. scene.pushGeometry(ground, true);
  37033. return ground;
  37034. };
  37035. return Ground;
  37036. }(_Primitive));
  37037. Primitives.Ground = Ground;
  37038. var TiledGround = (function (_super) {
  37039. __extends(TiledGround, _super);
  37040. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37041. _super.call(this, id, scene, canBeRegenerated, mesh);
  37042. this.xmin = xmin;
  37043. this.zmin = zmin;
  37044. this.xmax = xmax;
  37045. this.zmax = zmax;
  37046. this.subdivisions = subdivisions;
  37047. this.precision = precision;
  37048. }
  37049. TiledGround.prototype._regenerateVertexData = function () {
  37050. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37051. };
  37052. TiledGround.prototype.copy = function (id) {
  37053. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37054. };
  37055. return TiledGround;
  37056. }(_Primitive));
  37057. Primitives.TiledGround = TiledGround;
  37058. var Plane = (function (_super) {
  37059. __extends(Plane, _super);
  37060. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37062. _super.call(this, id, scene, canBeRegenerated, mesh);
  37063. this.size = size;
  37064. this.side = side;
  37065. }
  37066. Plane.prototype._regenerateVertexData = function () {
  37067. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37068. };
  37069. Plane.prototype.copy = function (id) {
  37070. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37071. };
  37072. Plane.prototype.serialize = function () {
  37073. var serializationObject = _super.prototype.serialize.call(this);
  37074. serializationObject.size = this.size;
  37075. return serializationObject;
  37076. };
  37077. Plane.Parse = function (parsedPlane, scene) {
  37078. if (scene.getGeometryByID(parsedPlane.id)) {
  37079. return null; // null since geometry could be something else than a ground...
  37080. }
  37081. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37082. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37083. scene.pushGeometry(plane, true);
  37084. return plane;
  37085. };
  37086. return Plane;
  37087. }(_Primitive));
  37088. Primitives.Plane = Plane;
  37089. var TorusKnot = (function (_super) {
  37090. __extends(TorusKnot, _super);
  37091. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37092. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37093. _super.call(this, id, scene, canBeRegenerated, mesh);
  37094. this.radius = radius;
  37095. this.tube = tube;
  37096. this.radialSegments = radialSegments;
  37097. this.tubularSegments = tubularSegments;
  37098. this.p = p;
  37099. this.q = q;
  37100. this.side = side;
  37101. }
  37102. TorusKnot.prototype._regenerateVertexData = function () {
  37103. 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 });
  37104. };
  37105. TorusKnot.prototype.copy = function (id) {
  37106. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37107. };
  37108. TorusKnot.prototype.serialize = function () {
  37109. var serializationObject = _super.prototype.serialize.call(this);
  37110. serializationObject.radius = this.radius;
  37111. serializationObject.tube = this.tube;
  37112. serializationObject.radialSegments = this.radialSegments;
  37113. serializationObject.tubularSegments = this.tubularSegments;
  37114. serializationObject.p = this.p;
  37115. serializationObject.q = this.q;
  37116. return serializationObject;
  37117. };
  37118. ;
  37119. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37120. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37121. return null; // null since geometry could be something else than a ground...
  37122. }
  37123. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37124. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37125. scene.pushGeometry(torusKnot, true);
  37126. return torusKnot;
  37127. };
  37128. return TorusKnot;
  37129. }(_Primitive));
  37130. Primitives.TorusKnot = TorusKnot;
  37131. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37132. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37133. })(BABYLON || (BABYLON = {}));
  37134. //# sourceMappingURL=babylon.geometry.js.map
  37135. var BABYLON;
  37136. (function (BABYLON) {
  37137. var GroundMesh = (function (_super) {
  37138. __extends(GroundMesh, _super);
  37139. function GroundMesh(name, scene) {
  37140. _super.call(this, name, scene);
  37141. this.generateOctree = false;
  37142. this._worldInverse = new BABYLON.Matrix();
  37143. }
  37144. GroundMesh.prototype.getClassName = function () {
  37145. return "GroundMesh";
  37146. };
  37147. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37148. get: function () {
  37149. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37150. },
  37151. enumerable: true,
  37152. configurable: true
  37153. });
  37154. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37155. get: function () {
  37156. return this._subdivisionsX;
  37157. },
  37158. enumerable: true,
  37159. configurable: true
  37160. });
  37161. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37162. get: function () {
  37163. return this._subdivisionsY;
  37164. },
  37165. enumerable: true,
  37166. configurable: true
  37167. });
  37168. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37169. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37170. this._subdivisionsX = chunksCount;
  37171. this._subdivisionsY = chunksCount;
  37172. this.subdivide(chunksCount);
  37173. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37174. };
  37175. /**
  37176. * Returns a height (y) value in the Worl system :
  37177. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37178. * Returns the ground y position if (x, z) are outside the ground surface.
  37179. * Not pertinent if the ground is rotated.
  37180. */
  37181. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37182. // express x and y in the ground local system
  37183. x -= this.position.x;
  37184. z -= this.position.z;
  37185. x /= this.scaling.x;
  37186. z /= this.scaling.z;
  37187. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37188. return this.position.y;
  37189. }
  37190. if (!this._heightQuads || this._heightQuads.length == 0) {
  37191. this._initHeightQuads();
  37192. this._computeHeightQuads();
  37193. }
  37194. var facet = this._getFacetAt(x, z);
  37195. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37196. // return y in the World system
  37197. return y * this.scaling.y + this.position.y;
  37198. };
  37199. /**
  37200. * Returns a normalized vector (Vector3) orthogonal to the ground
  37201. * at the ground coordinates (x, z) expressed in the World system.
  37202. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37203. * Not pertinent if the ground is rotated.
  37204. */
  37205. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37206. var normal = new BABYLON.Vector3(0, 1, 0);
  37207. this.getNormalAtCoordinatesToRef(x, z, normal);
  37208. return normal;
  37209. };
  37210. /**
  37211. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37212. * at the ground coordinates (x, z) expressed in the World system.
  37213. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37214. * Not pertinent if the ground is rotated.
  37215. */
  37216. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37217. // express x and y in the ground local system
  37218. x -= this.position.x;
  37219. z -= this.position.z;
  37220. x /= this.scaling.x;
  37221. z /= this.scaling.z;
  37222. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37223. return;
  37224. }
  37225. if (!this._heightQuads || this._heightQuads.length == 0) {
  37226. this._initHeightQuads();
  37227. this._computeHeightQuads();
  37228. }
  37229. var facet = this._getFacetAt(x, z);
  37230. ref.x = facet.x;
  37231. ref.y = facet.y;
  37232. ref.z = facet.z;
  37233. };
  37234. /**
  37235. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37236. * if the ground has been updated.
  37237. * This can be used in the render loop
  37238. */
  37239. GroundMesh.prototype.updateCoordinateHeights = function () {
  37240. if (!this._heightQuads || this._heightQuads.length == 0) {
  37241. this._initHeightQuads();
  37242. }
  37243. this._computeHeightQuads();
  37244. };
  37245. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37246. GroundMesh.prototype._getFacetAt = function (x, z) {
  37247. // retrieve col and row from x, z coordinates in the ground local system
  37248. var subdivisionsX = this._subdivisionsX;
  37249. var subdivisionsY = this._subdivisionsY;
  37250. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37251. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37252. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37253. var facet;
  37254. if (z < quad.slope.x * x + quad.slope.y) {
  37255. facet = quad.facet1;
  37256. }
  37257. else {
  37258. facet = quad.facet2;
  37259. }
  37260. return facet;
  37261. };
  37262. // Creates and populates the heightMap array with "facet" elements :
  37263. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37264. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37265. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37266. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37267. GroundMesh.prototype._initHeightQuads = function () {
  37268. var subdivisionsX = this._subdivisionsX;
  37269. var subdivisionsY = this._subdivisionsY;
  37270. this._heightQuads = new Array();
  37271. for (var row = 0; row < subdivisionsY; row++) {
  37272. for (var col = 0; col < subdivisionsX; col++) {
  37273. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37274. this._heightQuads[row * subdivisionsX + col] = quad;
  37275. }
  37276. }
  37277. };
  37278. // Compute each quad element values and update the the heightMap array :
  37279. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37280. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37281. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37282. GroundMesh.prototype._computeHeightQuads = function () {
  37283. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37284. var v1 = BABYLON.Tmp.Vector3[3];
  37285. var v2 = BABYLON.Tmp.Vector3[2];
  37286. var v3 = BABYLON.Tmp.Vector3[1];
  37287. var v4 = BABYLON.Tmp.Vector3[0];
  37288. var v1v2 = BABYLON.Tmp.Vector3[4];
  37289. var v1v3 = BABYLON.Tmp.Vector3[5];
  37290. var v1v4 = BABYLON.Tmp.Vector3[6];
  37291. var norm1 = BABYLON.Tmp.Vector3[7];
  37292. var norm2 = BABYLON.Tmp.Vector3[8];
  37293. var i = 0;
  37294. var j = 0;
  37295. var k = 0;
  37296. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37297. var h = 0;
  37298. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37299. var d2 = 0;
  37300. var subdivisionsX = this._subdivisionsX;
  37301. var subdivisionsY = this._subdivisionsY;
  37302. for (var row = 0; row < subdivisionsY; row++) {
  37303. for (var col = 0; col < subdivisionsX; col++) {
  37304. i = col * 3;
  37305. j = row * (subdivisionsX + 1) * 3;
  37306. k = (row + 1) * (subdivisionsX + 1) * 3;
  37307. v1.x = positions[j + i];
  37308. v1.y = positions[j + i + 1];
  37309. v1.z = positions[j + i + 2];
  37310. v2.x = positions[j + i + 3];
  37311. v2.y = positions[j + i + 4];
  37312. v2.z = positions[j + i + 5];
  37313. v3.x = positions[k + i];
  37314. v3.y = positions[k + i + 1];
  37315. v3.z = positions[k + i + 2];
  37316. v4.x = positions[k + i + 3];
  37317. v4.y = positions[k + i + 4];
  37318. v4.z = positions[k + i + 5];
  37319. // 2D slope V1V4
  37320. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37321. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37322. // facet equations :
  37323. // we compute each facet normal vector
  37324. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37325. // we compute the value d by applying the equation to v1 which belongs to the plane
  37326. // then we store the facet equation in a Vector4
  37327. v2.subtractToRef(v1, v1v2);
  37328. v3.subtractToRef(v1, v1v3);
  37329. v4.subtractToRef(v1, v1v4);
  37330. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37331. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37332. norm1.normalize();
  37333. norm2.normalize();
  37334. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37335. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37336. var quad = this._heightQuads[row * subdivisionsX + col];
  37337. quad.slope.copyFromFloats(cd, h);
  37338. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37339. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37340. }
  37341. }
  37342. };
  37343. return GroundMesh;
  37344. }(BABYLON.Mesh));
  37345. BABYLON.GroundMesh = GroundMesh;
  37346. })(BABYLON || (BABYLON = {}));
  37347. //# sourceMappingURL=babylon.groundMesh.js.map
  37348. var BABYLON;
  37349. (function (BABYLON) {
  37350. var LinesMesh = (function (_super) {
  37351. __extends(LinesMesh, _super);
  37352. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37353. if (parent === void 0) { parent = null; }
  37354. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  37355. this.color = new BABYLON.Color3(1, 1, 1);
  37356. this.alpha = 1;
  37357. this._positionBuffer = {};
  37358. if (source) {
  37359. this.color = source.color.clone();
  37360. this.alpha = source.alpha;
  37361. }
  37362. this._intersectionThreshold = 0.1;
  37363. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37364. attributes: [BABYLON.VertexBuffer.PositionKind],
  37365. uniforms: ["worldViewProjection", "color"],
  37366. needAlphaBlending: true
  37367. });
  37368. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37369. }
  37370. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37371. /**
  37372. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37373. * This margin is expressed in world space coordinates, so its value may vary.
  37374. * Default value is 0.1
  37375. * @returns the intersection Threshold value.
  37376. */
  37377. get: function () {
  37378. return this._intersectionThreshold;
  37379. },
  37380. /**
  37381. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37382. * This margin is expressed in world space coordinates, so its value may vary.
  37383. * @param value the new threshold to apply
  37384. */
  37385. set: function (value) {
  37386. if (this._intersectionThreshold === value) {
  37387. return;
  37388. }
  37389. this._intersectionThreshold = value;
  37390. if (this.geometry) {
  37391. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37392. }
  37393. },
  37394. enumerable: true,
  37395. configurable: true
  37396. });
  37397. Object.defineProperty(LinesMesh.prototype, "material", {
  37398. get: function () {
  37399. return this._colorShader;
  37400. },
  37401. enumerable: true,
  37402. configurable: true
  37403. });
  37404. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37405. get: function () {
  37406. return false;
  37407. },
  37408. enumerable: true,
  37409. configurable: true
  37410. });
  37411. LinesMesh.prototype.createInstance = function (name) {
  37412. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37413. return null;
  37414. };
  37415. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37416. var engine = this.getScene().getEngine();
  37417. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37418. // VBOs
  37419. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37420. // Color
  37421. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37422. };
  37423. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37424. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37425. return;
  37426. }
  37427. var engine = this.getScene().getEngine();
  37428. // Draw order
  37429. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37430. };
  37431. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37432. this._colorShader.dispose();
  37433. _super.prototype.dispose.call(this, doNotRecurse);
  37434. };
  37435. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37436. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37437. };
  37438. return LinesMesh;
  37439. }(BABYLON.Mesh));
  37440. BABYLON.LinesMesh = LinesMesh;
  37441. })(BABYLON || (BABYLON = {}));
  37442. //# sourceMappingURL=babylon.linesMesh.js.map
  37443. var BABYLON;
  37444. (function (BABYLON) {
  37445. var DefaultLoadingScreen = (function () {
  37446. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37447. var _this = this;
  37448. if (_loadingText === void 0) { _loadingText = ""; }
  37449. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37450. this._renderingCanvas = _renderingCanvas;
  37451. this._loadingText = _loadingText;
  37452. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37453. // Resize
  37454. this._resizeLoadingUI = function () {
  37455. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37456. _this._loadingDiv.style.position = "absolute";
  37457. _this._loadingDiv.style.left = canvasRect.left + "px";
  37458. _this._loadingDiv.style.top = canvasRect.top + "px";
  37459. _this._loadingDiv.style.width = canvasRect.width + "px";
  37460. _this._loadingDiv.style.height = canvasRect.height + "px";
  37461. };
  37462. }
  37463. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37464. var _this = this;
  37465. if (this._loadingDiv) {
  37466. // Do not add a loading screen if there is already one
  37467. return;
  37468. }
  37469. this._loadingDiv = document.createElement("div");
  37470. this._loadingDiv.id = "babylonjsLoadingDiv";
  37471. this._loadingDiv.style.opacity = "0";
  37472. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37473. // Loading text
  37474. this._loadingTextDiv = document.createElement("div");
  37475. this._loadingTextDiv.style.position = "absolute";
  37476. this._loadingTextDiv.style.left = "0";
  37477. this._loadingTextDiv.style.top = "50%";
  37478. this._loadingTextDiv.style.marginTop = "80px";
  37479. this._loadingTextDiv.style.width = "100%";
  37480. this._loadingTextDiv.style.height = "20px";
  37481. this._loadingTextDiv.style.fontFamily = "Arial";
  37482. this._loadingTextDiv.style.fontSize = "14px";
  37483. this._loadingTextDiv.style.color = "white";
  37484. this._loadingTextDiv.style.textAlign = "center";
  37485. this._loadingTextDiv.innerHTML = "Loading";
  37486. this._loadingDiv.appendChild(this._loadingTextDiv);
  37487. //set the predefined text
  37488. this._loadingTextDiv.innerHTML = this._loadingText;
  37489. // Loading img
  37490. var imgBack = new Image();
  37491. 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==";
  37492. imgBack.style.position = "absolute";
  37493. imgBack.style.left = "50%";
  37494. imgBack.style.top = "50%";
  37495. imgBack.style.marginLeft = "-50px";
  37496. imgBack.style.marginTop = "-50px";
  37497. imgBack.style.transition = "transform 1.0s ease";
  37498. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37499. var deg = 360;
  37500. var onTransitionEnd = function () {
  37501. deg += 360;
  37502. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37503. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37504. };
  37505. imgBack.addEventListener("transitionend", onTransitionEnd);
  37506. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37507. this._loadingDiv.appendChild(imgBack);
  37508. // front image
  37509. var imgFront = new Image();
  37510. 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=";
  37511. imgFront.style.position = "absolute";
  37512. imgFront.style.left = "50%";
  37513. imgFront.style.top = "50%";
  37514. imgFront.style.marginLeft = "-50px";
  37515. imgFront.style.marginTop = "-50px";
  37516. this._loadingDiv.appendChild(imgFront);
  37517. this._resizeLoadingUI();
  37518. window.addEventListener("resize", this._resizeLoadingUI);
  37519. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37520. document.body.appendChild(this._loadingDiv);
  37521. setTimeout(function () {
  37522. _this._loadingDiv.style.opacity = "1";
  37523. imgBack.style.transform = "rotateZ(360deg)";
  37524. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37525. }, 0);
  37526. };
  37527. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37528. var _this = this;
  37529. if (!this._loadingDiv) {
  37530. return;
  37531. }
  37532. var onTransitionEnd = function () {
  37533. if (!_this._loadingDiv) {
  37534. return;
  37535. }
  37536. document.body.removeChild(_this._loadingDiv);
  37537. window.removeEventListener("resize", _this._resizeLoadingUI);
  37538. _this._loadingDiv = null;
  37539. };
  37540. this._loadingDiv.style.opacity = "0";
  37541. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37542. };
  37543. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37544. set: function (text) {
  37545. this._loadingText = text;
  37546. if (this._loadingTextDiv) {
  37547. this._loadingTextDiv.innerHTML = this._loadingText;
  37548. }
  37549. },
  37550. enumerable: true,
  37551. configurable: true
  37552. });
  37553. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37554. get: function () {
  37555. return this._loadingDivBackgroundColor;
  37556. },
  37557. set: function (color) {
  37558. this._loadingDivBackgroundColor = color;
  37559. if (!this._loadingDiv) {
  37560. return;
  37561. }
  37562. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. return DefaultLoadingScreen;
  37568. }());
  37569. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37570. })(BABYLON || (BABYLON = {}));
  37571. //# sourceMappingURL=babylon.loadingScreen.js.map
  37572. var BABYLON;
  37573. (function (BABYLON) {
  37574. var AudioEngine = (function () {
  37575. function AudioEngine() {
  37576. this._audioContext = null;
  37577. this._audioContextInitialized = false;
  37578. this.canUseWebAudio = false;
  37579. this.WarnedWebAudioUnsupported = false;
  37580. this.unlocked = false;
  37581. this.isMP3supported = false;
  37582. this.isOGGsupported = false;
  37583. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37584. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37585. this.canUseWebAudio = true;
  37586. }
  37587. var audioElem = document.createElement('audio');
  37588. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37589. this.isMP3supported = true;
  37590. }
  37591. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37592. this.isOGGsupported = true;
  37593. }
  37594. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37595. this._unlockiOSaudio();
  37596. }
  37597. else {
  37598. this.unlocked = true;
  37599. }
  37600. }
  37601. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37602. get: function () {
  37603. if (!this._audioContextInitialized) {
  37604. this._initializeAudioContext();
  37605. }
  37606. return this._audioContext;
  37607. },
  37608. enumerable: true,
  37609. configurable: true
  37610. });
  37611. AudioEngine.prototype._unlockiOSaudio = function () {
  37612. var _this = this;
  37613. var unlockaudio = function () {
  37614. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37615. var source = _this.audioContext.createBufferSource();
  37616. source.buffer = buffer;
  37617. source.connect(_this.audioContext.destination);
  37618. source.start(0);
  37619. setTimeout(function () {
  37620. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37621. _this.unlocked = true;
  37622. window.removeEventListener('touchend', unlockaudio, false);
  37623. if (_this.onAudioUnlocked) {
  37624. _this.onAudioUnlocked();
  37625. }
  37626. }
  37627. }, 0);
  37628. };
  37629. window.addEventListener('touchend', unlockaudio, false);
  37630. };
  37631. AudioEngine.prototype._initializeAudioContext = function () {
  37632. try {
  37633. if (this.canUseWebAudio) {
  37634. this._audioContext = new AudioContext();
  37635. // create a global volume gain node
  37636. this.masterGain = this._audioContext.createGain();
  37637. this.masterGain.gain.value = 1;
  37638. this.masterGain.connect(this._audioContext.destination);
  37639. this._audioContextInitialized = true;
  37640. }
  37641. }
  37642. catch (e) {
  37643. this.canUseWebAudio = false;
  37644. BABYLON.Tools.Error("Web Audio: " + e.message);
  37645. }
  37646. };
  37647. AudioEngine.prototype.dispose = function () {
  37648. if (this.canUseWebAudio && this._audioContextInitialized) {
  37649. if (this._connectedAnalyser) {
  37650. this._connectedAnalyser.stopDebugCanvas();
  37651. this._connectedAnalyser.dispose();
  37652. this.masterGain.disconnect();
  37653. this.masterGain.connect(this._audioContext.destination);
  37654. this._connectedAnalyser = null;
  37655. }
  37656. this.masterGain.gain.value = 1;
  37657. }
  37658. this.WarnedWebAudioUnsupported = false;
  37659. };
  37660. AudioEngine.prototype.getGlobalVolume = function () {
  37661. if (this.canUseWebAudio && this._audioContextInitialized) {
  37662. return this.masterGain.gain.value;
  37663. }
  37664. else {
  37665. return -1;
  37666. }
  37667. };
  37668. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37669. if (this.canUseWebAudio && this._audioContextInitialized) {
  37670. this.masterGain.gain.value = newVolume;
  37671. }
  37672. };
  37673. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37674. if (this._connectedAnalyser) {
  37675. this._connectedAnalyser.stopDebugCanvas();
  37676. }
  37677. if (this.canUseWebAudio && this._audioContextInitialized) {
  37678. this._connectedAnalyser = analyser;
  37679. this.masterGain.disconnect();
  37680. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37681. }
  37682. };
  37683. return AudioEngine;
  37684. }());
  37685. BABYLON.AudioEngine = AudioEngine;
  37686. })(BABYLON || (BABYLON = {}));
  37687. //# sourceMappingURL=babylon.audioEngine.js.map
  37688. var BABYLON;
  37689. (function (BABYLON) {
  37690. var Sound = (function () {
  37691. /**
  37692. * Create a sound and attach it to a scene
  37693. * @param name Name of your sound
  37694. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37695. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37696. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37697. */
  37698. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37699. var _this = this;
  37700. this.autoplay = false;
  37701. this.loop = false;
  37702. this.useCustomAttenuation = false;
  37703. this.spatialSound = false;
  37704. this.refDistance = 1;
  37705. this.rolloffFactor = 1;
  37706. this.maxDistance = 100;
  37707. this.distanceModel = "linear";
  37708. this._panningModel = "equalpower";
  37709. this._playbackRate = 1;
  37710. this._streaming = false;
  37711. this._startTime = 0;
  37712. this._startOffset = 0;
  37713. this._position = BABYLON.Vector3.Zero();
  37714. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37715. this._volume = 1;
  37716. this._isLoaded = false;
  37717. this._isReadyToPlay = false;
  37718. this.isPlaying = false;
  37719. this.isPaused = false;
  37720. this._isDirectional = false;
  37721. // Used if you'd like to create a directional sound.
  37722. // If not set, the sound will be omnidirectional
  37723. this._coneInnerAngle = 360;
  37724. this._coneOuterAngle = 360;
  37725. this._coneOuterGain = 0;
  37726. this._isOutputConnected = false;
  37727. this._urlType = "Unknown";
  37728. this.name = name;
  37729. this._scene = scene;
  37730. this._readyToPlayCallback = readyToPlayCallback;
  37731. // Default custom attenuation function is a linear attenuation
  37732. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37733. if (currentDistance < maxDistance) {
  37734. return currentVolume * (1 - currentDistance / maxDistance);
  37735. }
  37736. else {
  37737. return 0;
  37738. }
  37739. };
  37740. if (options) {
  37741. this.autoplay = options.autoplay || false;
  37742. this.loop = options.loop || false;
  37743. // if volume === 0, we need another way to check this option
  37744. if (options.volume !== undefined) {
  37745. this._volume = options.volume;
  37746. }
  37747. this.spatialSound = options.spatialSound || false;
  37748. this.maxDistance = options.maxDistance || 100;
  37749. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37750. this.rolloffFactor = options.rolloffFactor || 1;
  37751. this.refDistance = options.refDistance || 1;
  37752. this.distanceModel = options.distanceModel || "linear";
  37753. this._playbackRate = options.playbackRate || 1;
  37754. this._streaming = options.streaming || false;
  37755. }
  37756. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37757. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37758. this._soundGain.gain.value = this._volume;
  37759. this._inputAudioNode = this._soundGain;
  37760. this._ouputAudioNode = this._soundGain;
  37761. if (this.spatialSound) {
  37762. this._createSpatialParameters();
  37763. }
  37764. this._scene.mainSoundTrack.AddSound(this);
  37765. var validParameter = true;
  37766. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37767. if (urlOrArrayBuffer) {
  37768. if (typeof (urlOrArrayBuffer) === "string")
  37769. this._urlType = "String";
  37770. if (Array.isArray(urlOrArrayBuffer))
  37771. this._urlType = "Array";
  37772. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37773. this._urlType = "ArrayBuffer";
  37774. var urls = [];
  37775. var codecSupportedFound = false;
  37776. switch (this._urlType) {
  37777. case "ArrayBuffer":
  37778. if (urlOrArrayBuffer.byteLength > 0) {
  37779. codecSupportedFound = true;
  37780. this._soundLoaded(urlOrArrayBuffer);
  37781. }
  37782. break;
  37783. case "String":
  37784. urls.push(urlOrArrayBuffer);
  37785. case "Array":
  37786. if (urls.length === 0)
  37787. urls = urlOrArrayBuffer;
  37788. // If we found a supported format, we load it immediately and stop the loop
  37789. for (var i = 0; i < urls.length; i++) {
  37790. var url = urls[i];
  37791. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37792. codecSupportedFound = true;
  37793. }
  37794. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37795. codecSupportedFound = true;
  37796. }
  37797. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37798. codecSupportedFound = true;
  37799. }
  37800. if (codecSupportedFound) {
  37801. // Loading sound using XHR2
  37802. if (!this._streaming) {
  37803. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37804. }
  37805. else {
  37806. this._htmlAudioElement = new Audio(url);
  37807. this._htmlAudioElement.controls = false;
  37808. this._htmlAudioElement.loop = this.loop;
  37809. this._htmlAudioElement.crossOrigin = "anonymous";
  37810. this._htmlAudioElement.preload = "auto";
  37811. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37812. _this._isReadyToPlay = true;
  37813. if (_this.autoplay) {
  37814. _this.play();
  37815. }
  37816. if (_this._readyToPlayCallback) {
  37817. _this._readyToPlayCallback();
  37818. }
  37819. });
  37820. document.body.appendChild(this._htmlAudioElement);
  37821. }
  37822. break;
  37823. }
  37824. }
  37825. break;
  37826. default:
  37827. validParameter = false;
  37828. break;
  37829. }
  37830. if (!validParameter) {
  37831. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37832. }
  37833. else {
  37834. if (!codecSupportedFound) {
  37835. this._isReadyToPlay = true;
  37836. // Simulating a ready to play event to avoid breaking code path
  37837. if (this._readyToPlayCallback) {
  37838. window.setTimeout(function () {
  37839. _this._readyToPlayCallback();
  37840. }, 1000);
  37841. }
  37842. }
  37843. }
  37844. }
  37845. }
  37846. else {
  37847. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37848. this._scene.mainSoundTrack.AddSound(this);
  37849. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37850. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37851. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37852. }
  37853. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37854. if (this._readyToPlayCallback) {
  37855. window.setTimeout(function () {
  37856. _this._readyToPlayCallback();
  37857. }, 1000);
  37858. }
  37859. }
  37860. }
  37861. Sound.prototype.dispose = function () {
  37862. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37863. if (this.isPlaying) {
  37864. this.stop();
  37865. }
  37866. this._isReadyToPlay = false;
  37867. if (this.soundTrackId === -1) {
  37868. this._scene.mainSoundTrack.RemoveSound(this);
  37869. }
  37870. else {
  37871. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37872. }
  37873. if (this._soundGain) {
  37874. this._soundGain.disconnect();
  37875. this._soundGain = null;
  37876. }
  37877. if (this._soundPanner) {
  37878. this._soundPanner.disconnect();
  37879. this._soundPanner = null;
  37880. }
  37881. if (this._soundSource) {
  37882. this._soundSource.disconnect();
  37883. this._soundSource = null;
  37884. }
  37885. this._audioBuffer = null;
  37886. if (this._htmlAudioElement) {
  37887. this._htmlAudioElement.pause();
  37888. this._htmlAudioElement.src = "";
  37889. document.body.removeChild(this._htmlAudioElement);
  37890. }
  37891. if (this._connectedMesh) {
  37892. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37893. this._connectedMesh = null;
  37894. }
  37895. }
  37896. };
  37897. Sound.prototype._soundLoaded = function (audioData) {
  37898. var _this = this;
  37899. this._isLoaded = true;
  37900. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37901. _this._audioBuffer = buffer;
  37902. _this._isReadyToPlay = true;
  37903. if (_this.autoplay) {
  37904. _this.play();
  37905. }
  37906. if (_this._readyToPlayCallback) {
  37907. _this._readyToPlayCallback();
  37908. }
  37909. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37910. };
  37911. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37912. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37913. this._audioBuffer = audioBuffer;
  37914. this._isReadyToPlay = true;
  37915. }
  37916. };
  37917. Sound.prototype.updateOptions = function (options) {
  37918. if (options) {
  37919. this.loop = options.loop || this.loop;
  37920. this.maxDistance = options.maxDistance || this.maxDistance;
  37921. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37922. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37923. this.refDistance = options.refDistance || this.refDistance;
  37924. this.distanceModel = options.distanceModel || this.distanceModel;
  37925. this._playbackRate = options.playbackRate || this._playbackRate;
  37926. this._updateSpatialParameters();
  37927. if (this.isPlaying) {
  37928. if (this._streaming) {
  37929. this._htmlAudioElement.playbackRate = this._playbackRate;
  37930. }
  37931. else {
  37932. this._soundSource.playbackRate.value = this._playbackRate;
  37933. }
  37934. }
  37935. }
  37936. };
  37937. Sound.prototype._createSpatialParameters = function () {
  37938. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37939. if (this._scene.headphone) {
  37940. this._panningModel = "HRTF";
  37941. }
  37942. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37943. this._updateSpatialParameters();
  37944. this._soundPanner.connect(this._ouputAudioNode);
  37945. this._inputAudioNode = this._soundPanner;
  37946. }
  37947. };
  37948. Sound.prototype._updateSpatialParameters = function () {
  37949. if (this.spatialSound) {
  37950. if (this.useCustomAttenuation) {
  37951. // Tricks to disable in a way embedded Web Audio attenuation
  37952. this._soundPanner.distanceModel = "linear";
  37953. this._soundPanner.maxDistance = Number.MAX_VALUE;
  37954. this._soundPanner.refDistance = 1;
  37955. this._soundPanner.rolloffFactor = 1;
  37956. this._soundPanner.panningModel = this._panningModel;
  37957. }
  37958. else {
  37959. this._soundPanner.distanceModel = this.distanceModel;
  37960. this._soundPanner.maxDistance = this.maxDistance;
  37961. this._soundPanner.refDistance = this.refDistance;
  37962. this._soundPanner.rolloffFactor = this.rolloffFactor;
  37963. this._soundPanner.panningModel = this._panningModel;
  37964. }
  37965. }
  37966. };
  37967. Sound.prototype.switchPanningModelToHRTF = function () {
  37968. this._panningModel = "HRTF";
  37969. this._switchPanningModel();
  37970. };
  37971. Sound.prototype.switchPanningModelToEqualPower = function () {
  37972. this._panningModel = "equalpower";
  37973. this._switchPanningModel();
  37974. };
  37975. Sound.prototype._switchPanningModel = function () {
  37976. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37977. this._soundPanner.panningModel = this._panningModel;
  37978. }
  37979. };
  37980. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  37981. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37982. if (this._isOutputConnected) {
  37983. this._ouputAudioNode.disconnect();
  37984. }
  37985. this._ouputAudioNode.connect(soundTrackAudioNode);
  37986. this._isOutputConnected = true;
  37987. }
  37988. };
  37989. /**
  37990. * Transform this sound into a directional source
  37991. * @param coneInnerAngle Size of the inner cone in degree
  37992. * @param coneOuterAngle Size of the outer cone in degree
  37993. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  37994. */
  37995. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  37996. if (coneOuterAngle < coneInnerAngle) {
  37997. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  37998. return;
  37999. }
  38000. this._coneInnerAngle = coneInnerAngle;
  38001. this._coneOuterAngle = coneOuterAngle;
  38002. this._coneOuterGain = coneOuterGain;
  38003. this._isDirectional = true;
  38004. if (this.isPlaying && this.loop) {
  38005. this.stop();
  38006. this.play();
  38007. }
  38008. };
  38009. Sound.prototype.setPosition = function (newPosition) {
  38010. this._position = newPosition;
  38011. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38012. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38013. }
  38014. };
  38015. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38016. this._localDirection = newLocalDirection;
  38017. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38018. this._updateDirection();
  38019. }
  38020. };
  38021. Sound.prototype._updateDirection = function () {
  38022. var mat = this._connectedMesh.getWorldMatrix();
  38023. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38024. direction.normalize();
  38025. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38026. };
  38027. Sound.prototype.updateDistanceFromListener = function () {
  38028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38029. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38030. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38031. }
  38032. };
  38033. Sound.prototype.setAttenuationFunction = function (callback) {
  38034. this._customAttenuationFunction = callback;
  38035. };
  38036. /**
  38037. * Play the sound
  38038. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38039. * @param offset (optional) Start the sound setting it at a specific time
  38040. */
  38041. Sound.prototype.play = function (time, offset) {
  38042. var _this = this;
  38043. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38044. try {
  38045. if (this._startOffset < 0) {
  38046. time = -this._startOffset;
  38047. this._startOffset = 0;
  38048. }
  38049. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38050. if (!this._soundSource || !this._streamingSource) {
  38051. if (this.spatialSound) {
  38052. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38053. if (this._isDirectional) {
  38054. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38055. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38056. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38057. if (this._connectedMesh) {
  38058. this._updateDirection();
  38059. }
  38060. else {
  38061. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38062. }
  38063. }
  38064. }
  38065. }
  38066. if (this._streaming) {
  38067. if (!this._streamingSource) {
  38068. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38069. this._htmlAudioElement.onended = function () { _this._onended(); };
  38070. this._htmlAudioElement.playbackRate = this._playbackRate;
  38071. }
  38072. this._streamingSource.disconnect();
  38073. this._streamingSource.connect(this._inputAudioNode);
  38074. this._htmlAudioElement.play();
  38075. }
  38076. else {
  38077. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38078. this._soundSource.buffer = this._audioBuffer;
  38079. this._soundSource.connect(this._inputAudioNode);
  38080. this._soundSource.loop = this.loop;
  38081. this._soundSource.playbackRate.value = this._playbackRate;
  38082. this._soundSource.onended = function () { _this._onended(); };
  38083. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38084. }
  38085. this._startTime = startTime;
  38086. this.isPlaying = true;
  38087. this.isPaused = false;
  38088. }
  38089. catch (ex) {
  38090. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38091. }
  38092. }
  38093. };
  38094. Sound.prototype._onended = function () {
  38095. this.isPlaying = false;
  38096. if (this.onended) {
  38097. this.onended();
  38098. }
  38099. };
  38100. /**
  38101. * Stop the sound
  38102. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38103. */
  38104. Sound.prototype.stop = function (time) {
  38105. if (this.isPlaying) {
  38106. if (this._streaming) {
  38107. this._htmlAudioElement.pause();
  38108. // Test needed for Firefox or it will generate an Invalid State Error
  38109. if (this._htmlAudioElement.currentTime > 0) {
  38110. this._htmlAudioElement.currentTime = 0;
  38111. }
  38112. }
  38113. else {
  38114. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38115. this._soundSource.stop(stopTime);
  38116. this._soundSource.onended = null;
  38117. if (!this.isPaused) {
  38118. this._startOffset = 0;
  38119. }
  38120. }
  38121. this.isPlaying = false;
  38122. }
  38123. };
  38124. Sound.prototype.pause = function () {
  38125. if (this.isPlaying) {
  38126. this.isPaused = true;
  38127. if (this._streaming) {
  38128. this._htmlAudioElement.pause();
  38129. }
  38130. else {
  38131. this.stop(0);
  38132. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38133. }
  38134. }
  38135. };
  38136. Sound.prototype.setVolume = function (newVolume, time) {
  38137. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38138. if (time) {
  38139. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38140. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38141. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38142. }
  38143. else {
  38144. this._soundGain.gain.value = newVolume;
  38145. }
  38146. }
  38147. this._volume = newVolume;
  38148. };
  38149. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38150. this._playbackRate = newPlaybackRate;
  38151. if (this.isPlaying) {
  38152. if (this._streaming) {
  38153. this._htmlAudioElement.playbackRate = this._playbackRate;
  38154. }
  38155. else {
  38156. this._soundSource.playbackRate.value = this._playbackRate;
  38157. }
  38158. }
  38159. };
  38160. Sound.prototype.getVolume = function () {
  38161. return this._volume;
  38162. };
  38163. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38164. var _this = this;
  38165. if (this._connectedMesh) {
  38166. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38167. this._registerFunc = null;
  38168. }
  38169. this._connectedMesh = meshToConnectTo;
  38170. if (!this.spatialSound) {
  38171. this.spatialSound = true;
  38172. this._createSpatialParameters();
  38173. if (this.isPlaying && this.loop) {
  38174. this.stop();
  38175. this.play();
  38176. }
  38177. }
  38178. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38179. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38180. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38181. };
  38182. Sound.prototype.detachFromMesh = function () {
  38183. if (this._connectedMesh) {
  38184. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38185. this._registerFunc = null;
  38186. this._connectedMesh = null;
  38187. }
  38188. };
  38189. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38190. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38192. this._updateDirection();
  38193. }
  38194. };
  38195. Sound.prototype.clone = function () {
  38196. var _this = this;
  38197. if (!this._streaming) {
  38198. var setBufferAndRun = function () {
  38199. if (_this._isReadyToPlay) {
  38200. clonedSound._audioBuffer = _this.getAudioBuffer();
  38201. clonedSound._isReadyToPlay = true;
  38202. if (clonedSound.autoplay) {
  38203. clonedSound.play();
  38204. }
  38205. }
  38206. else {
  38207. window.setTimeout(setBufferAndRun, 300);
  38208. }
  38209. };
  38210. var currentOptions = {
  38211. autoplay: this.autoplay, loop: this.loop,
  38212. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38213. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38214. refDistance: this.refDistance, distanceModel: this.distanceModel
  38215. };
  38216. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38217. if (this.useCustomAttenuation) {
  38218. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38219. }
  38220. clonedSound.setPosition(this._position);
  38221. clonedSound.setPlaybackRate(this._playbackRate);
  38222. setBufferAndRun();
  38223. return clonedSound;
  38224. }
  38225. else {
  38226. return null;
  38227. }
  38228. };
  38229. Sound.prototype.getAudioBuffer = function () {
  38230. return this._audioBuffer;
  38231. };
  38232. Sound.prototype.serialize = function () {
  38233. var serializationObject = {
  38234. name: this.name,
  38235. url: this.name,
  38236. autoplay: this.autoplay,
  38237. loop: this.loop,
  38238. volume: this._volume,
  38239. spatialSound: this.spatialSound,
  38240. maxDistance: this.maxDistance,
  38241. rolloffFactor: this.rolloffFactor,
  38242. refDistance: this.refDistance,
  38243. distanceModel: this.distanceModel,
  38244. playbackRate: this._playbackRate,
  38245. panningModel: this._panningModel,
  38246. soundTrackId: this.soundTrackId
  38247. };
  38248. if (this.spatialSound) {
  38249. if (this._connectedMesh)
  38250. serializationObject.connectedMeshId = this._connectedMesh.id;
  38251. serializationObject.position = this._position.asArray();
  38252. serializationObject.refDistance = this.refDistance;
  38253. serializationObject.distanceModel = this.distanceModel;
  38254. serializationObject.isDirectional = this._isDirectional;
  38255. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38256. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38257. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38258. serializationObject.coneOuterGain = this._coneOuterGain;
  38259. }
  38260. return serializationObject;
  38261. };
  38262. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38263. var soundName = parsedSound.name;
  38264. var soundUrl;
  38265. if (parsedSound.url) {
  38266. soundUrl = rootUrl + parsedSound.url;
  38267. }
  38268. else {
  38269. soundUrl = rootUrl + soundName;
  38270. }
  38271. var options = {
  38272. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38273. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38274. rolloffFactor: parsedSound.rolloffFactor,
  38275. refDistance: parsedSound.refDistance,
  38276. distanceModel: parsedSound.distanceModel,
  38277. playbackRate: parsedSound.playbackRate
  38278. };
  38279. var newSound;
  38280. if (!sourceSound) {
  38281. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38282. scene._addPendingData(newSound);
  38283. }
  38284. else {
  38285. var setBufferAndRun = function () {
  38286. if (sourceSound._isReadyToPlay) {
  38287. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38288. newSound._isReadyToPlay = true;
  38289. if (newSound.autoplay) {
  38290. newSound.play();
  38291. }
  38292. }
  38293. else {
  38294. window.setTimeout(setBufferAndRun, 300);
  38295. }
  38296. };
  38297. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38298. setBufferAndRun();
  38299. }
  38300. if (parsedSound.position) {
  38301. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38302. newSound.setPosition(soundPosition);
  38303. }
  38304. if (parsedSound.isDirectional) {
  38305. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38306. if (parsedSound.localDirectionToMesh) {
  38307. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38308. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38309. }
  38310. }
  38311. if (parsedSound.connectedMeshId) {
  38312. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38313. if (connectedMesh) {
  38314. newSound.attachToMesh(connectedMesh);
  38315. }
  38316. }
  38317. return newSound;
  38318. };
  38319. return Sound;
  38320. }());
  38321. BABYLON.Sound = Sound;
  38322. })(BABYLON || (BABYLON = {}));
  38323. //# sourceMappingURL=babylon.sound.js.map
  38324. var BABYLON;
  38325. (function (BABYLON) {
  38326. var SoundTrack = (function () {
  38327. function SoundTrack(scene, options) {
  38328. this.id = -1;
  38329. this._isMainTrack = false;
  38330. this._isInitialized = false;
  38331. this._scene = scene;
  38332. this.soundCollection = new Array();
  38333. this._options = options;
  38334. if (!this._isMainTrack) {
  38335. this._scene.soundTracks.push(this);
  38336. this.id = this._scene.soundTracks.length - 1;
  38337. }
  38338. }
  38339. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38340. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38341. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38342. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38343. if (this._options) {
  38344. if (this._options.volume) {
  38345. this._outputAudioNode.gain.value = this._options.volume;
  38346. }
  38347. if (this._options.mainTrack) {
  38348. this._isMainTrack = this._options.mainTrack;
  38349. }
  38350. }
  38351. this._isInitialized = true;
  38352. }
  38353. };
  38354. SoundTrack.prototype.dispose = function () {
  38355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38356. if (this._connectedAnalyser) {
  38357. this._connectedAnalyser.stopDebugCanvas();
  38358. }
  38359. while (this.soundCollection.length) {
  38360. this.soundCollection[0].dispose();
  38361. }
  38362. if (this._outputAudioNode) {
  38363. this._outputAudioNode.disconnect();
  38364. }
  38365. this._outputAudioNode = null;
  38366. }
  38367. };
  38368. SoundTrack.prototype.AddSound = function (sound) {
  38369. if (!this._isInitialized) {
  38370. this._initializeSoundTrackAudioGraph();
  38371. }
  38372. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38373. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38374. }
  38375. if (sound.soundTrackId) {
  38376. if (sound.soundTrackId === -1) {
  38377. this._scene.mainSoundTrack.RemoveSound(sound);
  38378. }
  38379. else {
  38380. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38381. }
  38382. }
  38383. this.soundCollection.push(sound);
  38384. sound.soundTrackId = this.id;
  38385. };
  38386. SoundTrack.prototype.RemoveSound = function (sound) {
  38387. var index = this.soundCollection.indexOf(sound);
  38388. if (index !== -1) {
  38389. this.soundCollection.splice(index, 1);
  38390. }
  38391. };
  38392. SoundTrack.prototype.setVolume = function (newVolume) {
  38393. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38394. this._outputAudioNode.gain.value = newVolume;
  38395. }
  38396. };
  38397. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38399. for (var i = 0; i < this.soundCollection.length; i++) {
  38400. this.soundCollection[i].switchPanningModelToHRTF();
  38401. }
  38402. }
  38403. };
  38404. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38405. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38406. for (var i = 0; i < this.soundCollection.length; i++) {
  38407. this.soundCollection[i].switchPanningModelToEqualPower();
  38408. }
  38409. }
  38410. };
  38411. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38412. if (this._connectedAnalyser) {
  38413. this._connectedAnalyser.stopDebugCanvas();
  38414. }
  38415. this._connectedAnalyser = analyser;
  38416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38417. this._outputAudioNode.disconnect();
  38418. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38419. }
  38420. };
  38421. return SoundTrack;
  38422. }());
  38423. BABYLON.SoundTrack = SoundTrack;
  38424. })(BABYLON || (BABYLON = {}));
  38425. //# sourceMappingURL=babylon.soundtrack.js.map
  38426. var BABYLON;
  38427. (function (BABYLON) {
  38428. /**
  38429. * Special Glow Blur post process only blurring the alpha channel
  38430. * It enforces keeping the most luminous color in the color channel.
  38431. */
  38432. var GlowBlurPostProcess = (function (_super) {
  38433. __extends(GlowBlurPostProcess, _super);
  38434. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38435. var _this = this;
  38436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38437. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  38438. this.direction = direction;
  38439. this.blurWidth = blurWidth;
  38440. this.onApplyObservable.add(function (effect) {
  38441. effect.setFloat2("screenSize", _this.width, _this.height);
  38442. effect.setVector2("direction", _this.direction);
  38443. effect.setFloat("blurWidth", _this.blurWidth);
  38444. });
  38445. }
  38446. return GlowBlurPostProcess;
  38447. }(BABYLON.PostProcess));
  38448. /**
  38449. * The highlight layer Helps adding a glow effect around a mesh.
  38450. *
  38451. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38452. * glowy meshes to your scene.
  38453. *
  38454. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38455. */
  38456. var HighlightLayer = (function () {
  38457. /**
  38458. * Instantiates a new highlight Layer and references it to the scene..
  38459. * @param name The name of the layer
  38460. * @param scene The scene to use the layer in
  38461. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38462. */
  38463. function HighlightLayer(name, scene, options) {
  38464. this._vertexBuffers = {};
  38465. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38466. this._meshes = {};
  38467. this._maxSize = 0;
  38468. this._shouldRender = false;
  38469. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38470. this._excludedMeshes = {};
  38471. /**
  38472. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38473. */
  38474. this.innerGlow = true;
  38475. /**
  38476. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38477. */
  38478. this.outerGlow = true;
  38479. /**
  38480. * Specifies wether the highlight layer is enabled or not.
  38481. */
  38482. this.isEnabled = true;
  38483. /**
  38484. * An event triggered when the highlight layer has been disposed.
  38485. * @type {BABYLON.Observable}
  38486. */
  38487. this.onDisposeObservable = new BABYLON.Observable();
  38488. /**
  38489. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38490. * @type {BABYLON.Observable}
  38491. */
  38492. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38493. /**
  38494. * An event triggered when the highlight layer is being blurred.
  38495. * @type {BABYLON.Observable}
  38496. */
  38497. this.onBeforeBlurObservable = new BABYLON.Observable();
  38498. /**
  38499. * An event triggered when the highlight layer has been blurred.
  38500. * @type {BABYLON.Observable}
  38501. */
  38502. this.onAfterBlurObservable = new BABYLON.Observable();
  38503. /**
  38504. * An event triggered when the glowing blurred texture is being merged in the scene.
  38505. * @type {BABYLON.Observable}
  38506. */
  38507. this.onBeforeComposeObservable = new BABYLON.Observable();
  38508. /**
  38509. * An event triggered when the glowing blurred texture has been merged in the scene.
  38510. * @type {BABYLON.Observable}
  38511. */
  38512. this.onAfterComposeObservable = new BABYLON.Observable();
  38513. /**
  38514. * An event triggered when the highlight layer changes its size.
  38515. * @type {BABYLON.Observable}
  38516. */
  38517. this.onSizeChangedObservable = new BABYLON.Observable();
  38518. this._scene = scene;
  38519. var engine = scene.getEngine();
  38520. this._engine = engine;
  38521. this._maxSize = this._engine.getCaps().maxTextureSize;
  38522. this._scene.highlightLayers.push(this);
  38523. // Warn on stencil.
  38524. if (!this._engine.isStencilEnable) {
  38525. 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 }");
  38526. }
  38527. // Adapt options
  38528. this._options = options || {
  38529. mainTextureRatio: 0.25,
  38530. blurTextureSizeRatio: 0.5,
  38531. blurHorizontalSize: 1,
  38532. blurVerticalSize: 1,
  38533. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38534. };
  38535. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38536. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38537. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38538. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38539. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38540. // VBO
  38541. var vertices = [];
  38542. vertices.push(1, 1);
  38543. vertices.push(-1, 1);
  38544. vertices.push(-1, -1);
  38545. vertices.push(1, -1);
  38546. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38547. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38548. // Indices
  38549. var indices = [];
  38550. indices.push(0);
  38551. indices.push(1);
  38552. indices.push(2);
  38553. indices.push(0);
  38554. indices.push(2);
  38555. indices.push(3);
  38556. this._indexBuffer = engine.createIndexBuffer(indices);
  38557. // Effect
  38558. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38559. // Render target
  38560. this.setMainTextureSize();
  38561. // Create Textures and post processes
  38562. this.createTextureAndPostProcesses();
  38563. }
  38564. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38565. /**
  38566. * Gets the horizontal size of the blur.
  38567. */
  38568. get: function () {
  38569. return this._horizontalBlurPostprocess.blurWidth;
  38570. },
  38571. /**
  38572. * Specifies the horizontal size of the blur.
  38573. */
  38574. set: function (value) {
  38575. this._horizontalBlurPostprocess.blurWidth = value;
  38576. },
  38577. enumerable: true,
  38578. configurable: true
  38579. });
  38580. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38581. /**
  38582. * Gets the vertical size of the blur.
  38583. */
  38584. get: function () {
  38585. return this._verticalBlurPostprocess.blurWidth;
  38586. },
  38587. /**
  38588. * Specifies the vertical size of the blur.
  38589. */
  38590. set: function (value) {
  38591. this._verticalBlurPostprocess.blurWidth = value;
  38592. },
  38593. enumerable: true,
  38594. configurable: true
  38595. });
  38596. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38597. /**
  38598. * Gets the camera attached to the layer.
  38599. */
  38600. get: function () {
  38601. return this._options.camera;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. /**
  38607. * Creates the render target textures and post processes used in the highlight layer.
  38608. */
  38609. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38610. var _this = this;
  38611. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38612. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38613. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38614. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38615. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38616. width: this._mainTextureDesiredSize.width,
  38617. height: this._mainTextureDesiredSize.height
  38618. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38619. this._mainTexture.activeCamera = this._options.camera;
  38620. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38621. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38622. this._mainTexture.anisotropicFilteringLevel = 1;
  38623. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38624. this._mainTexture.renderParticles = false;
  38625. this._mainTexture.renderList = null;
  38626. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38627. width: blurTextureWidth,
  38628. height: blurTextureHeight
  38629. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38630. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38631. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38632. this._blurTexture.anisotropicFilteringLevel = 16;
  38633. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38634. this._blurTexture.renderParticles = false;
  38635. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38636. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38637. effect.setTexture("textureSampler", _this._mainTexture);
  38638. });
  38639. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38640. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38641. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38642. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38643. });
  38644. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38645. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38646. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38647. });
  38648. }
  38649. else {
  38650. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38651. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38652. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38653. });
  38654. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38655. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38656. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38657. });
  38658. }
  38659. this._mainTexture.onAfterUnbindObservable.add(function () {
  38660. _this.onBeforeBlurObservable.notifyObservers(_this);
  38661. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38662. _this.onAfterBlurObservable.notifyObservers(_this);
  38663. });
  38664. // Custom render function
  38665. var renderSubMesh = function (subMesh) {
  38666. var mesh = subMesh.getRenderingMesh();
  38667. var scene = _this._scene;
  38668. var engine = scene.getEngine();
  38669. // Culling
  38670. engine.setState(subMesh.getMaterial().backFaceCulling);
  38671. // Managing instances
  38672. var batch = mesh._getInstancesRenderList(subMesh._id);
  38673. if (batch.mustReturn) {
  38674. return;
  38675. }
  38676. // Excluded Mesh
  38677. if (_this._excludedMeshes[mesh.id]) {
  38678. return;
  38679. }
  38680. ;
  38681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38682. var highlightLayerMesh = _this._meshes[mesh.id];
  38683. var material = subMesh.getMaterial();
  38684. var emissiveTexture = null;
  38685. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38686. emissiveTexture = material.emissiveTexture;
  38687. }
  38688. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38689. engine.enableEffect(_this._glowMapGenerationEffect);
  38690. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38691. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38692. if (highlightLayerMesh) {
  38693. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38694. }
  38695. else {
  38696. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38697. }
  38698. // Alpha test
  38699. if (material && material.needAlphaTesting()) {
  38700. var alphaTexture = material.getAlphaTestTexture();
  38701. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38702. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38703. }
  38704. // Glow emissive only
  38705. if (emissiveTexture) {
  38706. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38707. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38708. }
  38709. // Bones
  38710. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38711. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38712. }
  38713. // Draw
  38714. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38715. }
  38716. else {
  38717. // Need to reset refresh rate of the shadowMap
  38718. _this._mainTexture.resetRefreshCounter();
  38719. }
  38720. };
  38721. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38722. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38723. var index;
  38724. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38725. renderSubMesh(opaqueSubMeshes.data[index]);
  38726. }
  38727. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38728. renderSubMesh(alphaTestSubMeshes.data[index]);
  38729. }
  38730. for (index = 0; index < transparentSubMeshes.length; index++) {
  38731. renderSubMesh(transparentSubMeshes.data[index]);
  38732. }
  38733. };
  38734. this._mainTexture.onClearObservable.add(function (engine) {
  38735. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38736. });
  38737. };
  38738. /**
  38739. * Checks for the readiness of the element composing the layer.
  38740. * @param subMesh the mesh to check for
  38741. * @param useInstances specify wether or not to use instances to render the mesh
  38742. * @param emissiveTexture the associated emissive texture used to generate the glow
  38743. * @return true if ready otherwise, false
  38744. */
  38745. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38746. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38747. return false;
  38748. }
  38749. var defines = [];
  38750. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38751. var mesh = subMesh.getMesh();
  38752. var material = subMesh.getMaterial();
  38753. var uv1 = false;
  38754. var uv2 = false;
  38755. // Alpha test
  38756. if (material && material.needAlphaTesting()) {
  38757. var alphaTexture = material.getAlphaTestTexture();
  38758. if (alphaTexture) {
  38759. defines.push("#define ALPHATEST");
  38760. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38761. alphaTexture.coordinatesIndex === 1) {
  38762. defines.push("#define DIFFUSEUV2");
  38763. uv2 = true;
  38764. }
  38765. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38766. defines.push("#define DIFFUSEUV1");
  38767. uv1 = true;
  38768. }
  38769. }
  38770. }
  38771. // Emissive
  38772. if (emissiveTexture) {
  38773. defines.push("#define EMISSIVE");
  38774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38775. emissiveTexture.coordinatesIndex === 1) {
  38776. defines.push("#define EMISSIVEUV2");
  38777. uv2 = true;
  38778. }
  38779. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38780. defines.push("#define EMISSIVEUV1");
  38781. uv1 = true;
  38782. }
  38783. }
  38784. if (uv1) {
  38785. attribs.push(BABYLON.VertexBuffer.UVKind);
  38786. defines.push("#define UV1");
  38787. }
  38788. if (uv2) {
  38789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38790. defines.push("#define UV2");
  38791. }
  38792. // Bones
  38793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38796. if (mesh.numBoneInfluencers > 4) {
  38797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38799. }
  38800. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38801. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38802. }
  38803. else {
  38804. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38805. }
  38806. // Instances
  38807. if (useInstances) {
  38808. defines.push("#define INSTANCES");
  38809. attribs.push("world0");
  38810. attribs.push("world1");
  38811. attribs.push("world2");
  38812. attribs.push("world3");
  38813. }
  38814. // Get correct effect
  38815. var join = defines.join("\n");
  38816. if (this._cachedDefines !== join) {
  38817. this._cachedDefines = join;
  38818. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38819. }
  38820. return this._glowMapGenerationEffect.isReady();
  38821. };
  38822. /**
  38823. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38824. */
  38825. HighlightLayer.prototype.render = function () {
  38826. var currentEffect = this._glowMapMergeEffect;
  38827. // Check
  38828. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38829. return;
  38830. var engine = this._scene.getEngine();
  38831. this.onBeforeComposeObservable.notifyObservers(this);
  38832. // Render
  38833. engine.enableEffect(currentEffect);
  38834. engine.setState(false);
  38835. // Cache
  38836. var previousStencilBuffer = engine.getStencilBuffer();
  38837. var previousStencilFunction = engine.getStencilFunction();
  38838. var previousStencilMask = engine.getStencilMask();
  38839. var previousAlphaMode = engine.getAlphaMode();
  38840. // Texture
  38841. currentEffect.setTexture("textureSampler", this._blurTexture);
  38842. // VBOs
  38843. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38844. // Draw order
  38845. engine.setAlphaMode(this._options.alphaBlendingMode);
  38846. engine.setStencilMask(0x00);
  38847. engine.setStencilBuffer(true);
  38848. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38849. if (this.outerGlow) {
  38850. currentEffect.setFloat("offset", 0);
  38851. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38852. engine.draw(true, 0, 6);
  38853. }
  38854. if (this.innerGlow) {
  38855. currentEffect.setFloat("offset", 1);
  38856. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38857. engine.draw(true, 0, 6);
  38858. }
  38859. // Restore Cache
  38860. engine.setStencilFunction(previousStencilFunction);
  38861. engine.setStencilMask(previousStencilMask);
  38862. engine.setAlphaMode(previousAlphaMode);
  38863. engine.setStencilBuffer(previousStencilBuffer);
  38864. this.onAfterComposeObservable.notifyObservers(this);
  38865. // Handle size changes.
  38866. var size = this._mainTexture.getSize();
  38867. this.setMainTextureSize();
  38868. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38869. // Recreate RTT and post processes on size change.
  38870. this.onSizeChangedObservable.notifyObservers(this);
  38871. this.disposeTextureAndPostProcesses();
  38872. this.createTextureAndPostProcesses();
  38873. }
  38874. };
  38875. /**
  38876. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38877. * @param mesh The mesh to exclude from the highlight layer
  38878. */
  38879. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38880. var meshExcluded = this._excludedMeshes[mesh.id];
  38881. if (!meshExcluded) {
  38882. this._excludedMeshes[mesh.id] = {
  38883. mesh: mesh,
  38884. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38885. mesh.getEngine().setStencilBuffer(false);
  38886. }),
  38887. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38888. mesh.getEngine().setStencilBuffer(true);
  38889. }),
  38890. };
  38891. }
  38892. };
  38893. /**
  38894. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38895. * @param mesh The mesh to highlight
  38896. */
  38897. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38898. var meshExcluded = this._excludedMeshes[mesh.id];
  38899. if (meshExcluded) {
  38900. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38901. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38902. }
  38903. this._excludedMeshes[mesh.id] = undefined;
  38904. };
  38905. /**
  38906. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38907. * @param mesh The mesh to highlight
  38908. * @param color The color of the highlight
  38909. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38910. */
  38911. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38912. var _this = this;
  38913. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38914. var meshHighlight = this._meshes[mesh.id];
  38915. if (meshHighlight) {
  38916. meshHighlight.color = color;
  38917. }
  38918. else {
  38919. this._meshes[mesh.id] = {
  38920. mesh: mesh,
  38921. color: color,
  38922. // Lambda required for capture due to Observable this context
  38923. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38924. if (_this._excludedMeshes[mesh.id]) {
  38925. _this.defaultStencilReference(mesh);
  38926. }
  38927. else {
  38928. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38929. }
  38930. }),
  38931. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38932. glowEmissiveOnly: glowEmissiveOnly
  38933. };
  38934. }
  38935. this._shouldRender = true;
  38936. };
  38937. /**
  38938. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38939. * @param mesh The mesh to highlight
  38940. */
  38941. HighlightLayer.prototype.removeMesh = function (mesh) {
  38942. var meshHighlight = this._meshes[mesh.id];
  38943. if (meshHighlight) {
  38944. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38945. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38946. }
  38947. this._meshes[mesh.id] = undefined;
  38948. this._shouldRender = false;
  38949. for (var meshHighlightToCheck in this._meshes) {
  38950. if (meshHighlightToCheck) {
  38951. this._shouldRender = true;
  38952. break;
  38953. }
  38954. }
  38955. };
  38956. /**
  38957. * Returns true if the layer contains information to display, otherwise false.
  38958. */
  38959. HighlightLayer.prototype.shouldRender = function () {
  38960. return this.isEnabled && this._shouldRender;
  38961. };
  38962. /**
  38963. * Sets the main texture desired size which is the closest power of two
  38964. * of the engine canvas size.
  38965. */
  38966. HighlightLayer.prototype.setMainTextureSize = function () {
  38967. if (this._options.mainTextureFixedSize) {
  38968. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  38969. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  38970. }
  38971. else {
  38972. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  38973. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  38974. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  38975. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  38976. }
  38977. };
  38978. /**
  38979. * Force the stencil to the normal expected value for none glowing parts
  38980. */
  38981. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  38982. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  38983. };
  38984. /**
  38985. * Dispose only the render target textures and post process.
  38986. */
  38987. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  38988. this._blurTexture.dispose();
  38989. this._mainTexture.dispose();
  38990. this._downSamplePostprocess.dispose();
  38991. this._horizontalBlurPostprocess.dispose();
  38992. this._verticalBlurPostprocess.dispose();
  38993. };
  38994. /**
  38995. * Dispose the highlight layer and free resources.
  38996. */
  38997. HighlightLayer.prototype.dispose = function () {
  38998. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38999. if (vertexBuffer) {
  39000. vertexBuffer.dispose();
  39001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39002. }
  39003. if (this._indexBuffer) {
  39004. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39005. this._indexBuffer = null;
  39006. }
  39007. // Clean textures and post processes
  39008. this.disposeTextureAndPostProcesses();
  39009. // Clean mesh references
  39010. for (var id in this._meshes) {
  39011. var meshHighlight = this._meshes[id];
  39012. if (meshHighlight && meshHighlight.mesh) {
  39013. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39014. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39015. }
  39016. }
  39017. this._meshes = null;
  39018. for (var id in this._excludedMeshes) {
  39019. var meshHighlight = this._excludedMeshes[id];
  39020. if (meshHighlight) {
  39021. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39022. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39023. }
  39024. }
  39025. this._excludedMeshes = null;
  39026. // Remove from scene
  39027. var index = this._scene.highlightLayers.indexOf(this, 0);
  39028. if (index > -1) {
  39029. this._scene.highlightLayers.splice(index, 1);
  39030. }
  39031. // Callback
  39032. this.onDisposeObservable.notifyObservers(this);
  39033. this.onDisposeObservable.clear();
  39034. this.onBeforeRenderMainTextureObservable.clear();
  39035. this.onBeforeBlurObservable.clear();
  39036. this.onBeforeComposeObservable.clear();
  39037. this.onAfterComposeObservable.clear();
  39038. this.onSizeChangedObservable.clear();
  39039. };
  39040. /**
  39041. * The neutral color used during the preparation of the glow effect.
  39042. * This is black by default as the blend operation is a blend operation.
  39043. */
  39044. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39045. /**
  39046. * Stencil value used for glowing meshes.
  39047. */
  39048. HighlightLayer.glowingMeshStencilReference = 0x02;
  39049. /**
  39050. * Stencil value used for the other meshes in the scene.
  39051. */
  39052. HighlightLayer.normalMeshStencilReference = 0x01;
  39053. return HighlightLayer;
  39054. }());
  39055. BABYLON.HighlightLayer = HighlightLayer;
  39056. })(BABYLON || (BABYLON = {}));
  39057. //# sourceMappingURL=babylon.highlightlayer.js.map
  39058. var BABYLON;
  39059. (function (BABYLON) {
  39060. var SIMDVector3 = (function () {
  39061. function SIMDVector3() {
  39062. }
  39063. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39064. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39065. };
  39066. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39067. var m = transformation.m;
  39068. var m0 = SIMD.Float32x4.load(m, 0);
  39069. var m1 = SIMD.Float32x4.load(m, 4);
  39070. var m2 = SIMD.Float32x4.load(m, 8);
  39071. var m3 = SIMD.Float32x4.load(m, 12);
  39072. 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));
  39073. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39074. result.x = SIMD.Float32x4.extractLane(r, 0);
  39075. result.y = SIMD.Float32x4.extractLane(r, 1);
  39076. result.z = SIMD.Float32x4.extractLane(r, 2);
  39077. };
  39078. return SIMDVector3;
  39079. }());
  39080. var SIMDMatrix = (function () {
  39081. function SIMDMatrix() {
  39082. }
  39083. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39084. var tm = this.m;
  39085. var om = other.m;
  39086. var m0 = SIMD.Float32x4.load(om, 0);
  39087. var m1 = SIMD.Float32x4.load(om, 4);
  39088. var m2 = SIMD.Float32x4.load(om, 8);
  39089. var m3 = SIMD.Float32x4.load(om, 12);
  39090. for (var i = 0; i < 16; i += 4) {
  39091. 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)))));
  39092. }
  39093. return this;
  39094. };
  39095. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39096. var src = this.m;
  39097. var dest = other.m;
  39098. // Load the 4 rows
  39099. var src0 = SIMD.Float32x4.load(src, 0);
  39100. var src1 = SIMD.Float32x4.load(src, 4);
  39101. var src2 = SIMD.Float32x4.load(src, 8);
  39102. var src3 = SIMD.Float32x4.load(src, 12);
  39103. // Transpose the source matrix. Sort of. Not a true transpose operation
  39104. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39105. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39106. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39107. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39108. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39109. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39110. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39111. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39112. // This is a true transposition, but it will lead to an incorrect result
  39113. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39114. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39115. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39116. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39117. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39118. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39119. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39120. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39121. // ----
  39122. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39123. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39124. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39125. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39126. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39127. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39128. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39129. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39130. // ----
  39131. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39132. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39133. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39134. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39135. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39136. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39137. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39138. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39139. // ----
  39140. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39141. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39142. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39143. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39144. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39145. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39146. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39147. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39148. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39149. // ----
  39150. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39151. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39152. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39153. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39154. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39155. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39156. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39157. // ----
  39158. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39159. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39160. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39161. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39162. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39163. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39164. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39165. // ----
  39166. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39167. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39168. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39169. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39170. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39171. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39172. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39173. // Compute determinant
  39174. var det = SIMD.Float32x4.mul(row0, minor0);
  39175. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39176. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39177. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39178. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39179. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39180. // These shuffles aren't necessary if the faulty transposition is done
  39181. // up at the top of this function.
  39182. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39183. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39184. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39185. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39186. // Compute final values by multiplying with 1/det
  39187. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39188. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39189. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39190. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39191. return this;
  39192. };
  39193. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39194. var out = result.m;
  39195. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39196. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39197. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39198. // cc.kmVec3Subtract(f, pCenter, pEye);
  39199. var f = SIMD.Float32x4.sub(center, eye);
  39200. // cc.kmVec3Normalize(f, f);
  39201. var tmp = SIMD.Float32x4.mul(f, f);
  39202. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39203. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39204. // cc.kmVec3Assign(up, pUp);
  39205. // cc.kmVec3Normalize(up, up);
  39206. tmp = SIMD.Float32x4.mul(up, up);
  39207. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39208. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39209. // cc.kmVec3Cross(s, f, up);
  39210. 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)));
  39211. // cc.kmVec3Normalize(s, s);
  39212. tmp = SIMD.Float32x4.mul(s, s);
  39213. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39214. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39215. // cc.kmVec3Cross(u, s, f);
  39216. 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)));
  39217. // cc.kmVec3Normalize(s, s);
  39218. tmp = SIMD.Float32x4.mul(s, s);
  39219. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39220. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39221. var zero = SIMD.Float32x4.splat(0.0);
  39222. s = SIMD.Float32x4.neg(s);
  39223. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39224. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39225. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39226. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39227. 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);
  39228. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39229. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39230. 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)))));
  39231. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39232. 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)))));
  39233. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39234. 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)))));
  39235. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39236. 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)))));
  39237. };
  39238. return SIMDMatrix;
  39239. }());
  39240. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39241. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39242. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39243. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39244. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39245. var SIMDHelper = (function () {
  39246. function SIMDHelper() {
  39247. }
  39248. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39249. get: function () {
  39250. return SIMDHelper._isEnabled;
  39251. },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. SIMDHelper.DisableSIMD = function () {
  39256. // Replace functions
  39257. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39258. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39259. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39260. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39261. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39262. SIMDHelper._isEnabled = false;
  39263. };
  39264. SIMDHelper.EnableSIMD = function () {
  39265. if (self.SIMD === undefined) {
  39266. return;
  39267. }
  39268. // check if polyfills needed
  39269. if (!self.Math.fround) {
  39270. self.Math.fround = (function (array) { return function (x) {
  39271. return array[0] = x, array[0];
  39272. }; })(new Float32Array(1));
  39273. }
  39274. if (!self.Math.imul) {
  39275. self.Math.imul = function (a, b) {
  39276. var ah = (a >>> 16) & 0xffff;
  39277. var al = a & 0xffff;
  39278. var bh = (b >>> 16) & 0xffff;
  39279. var bl = b & 0xffff;
  39280. // the shift by 0 fixes the sign on the high part
  39281. // the final |0 converts the unsigned value into a signed value
  39282. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39283. };
  39284. }
  39285. // Replace functions
  39286. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39287. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39288. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39289. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39291. SIMDHelper._isEnabled = true;
  39292. };
  39293. SIMDHelper._isEnabled = false;
  39294. return SIMDHelper;
  39295. }());
  39296. BABYLON.SIMDHelper = SIMDHelper;
  39297. })(BABYLON || (BABYLON = {}));
  39298. //# sourceMappingURL=babylon.math.SIMD.js.map
  39299. var BABYLON;
  39300. (function (BABYLON) {
  39301. /**
  39302. * This class describe a rectangle that were added to the map.
  39303. * You have access to its coordinates either in pixel or normalized (UV)
  39304. */
  39305. var PackedRect = (function () {
  39306. function PackedRect(root, parent, pos, size) {
  39307. this._pos = pos;
  39308. this._size = size;
  39309. this._root = root;
  39310. this._parent = parent;
  39311. this._contentSize = null;
  39312. this._bottomNode = null;
  39313. this._leftNode = null;
  39314. this._initialSize = null;
  39315. this._rightNode = null;
  39316. }
  39317. Object.defineProperty(PackedRect.prototype, "pos", {
  39318. /**
  39319. * @returns the position of this node into the map
  39320. */
  39321. get: function () {
  39322. return this._pos;
  39323. },
  39324. enumerable: true,
  39325. configurable: true
  39326. });
  39327. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39328. /**
  39329. * @returns the size of the rectangle this node handles
  39330. */
  39331. get: function () {
  39332. return this._contentSize;
  39333. },
  39334. enumerable: true,
  39335. configurable: true
  39336. });
  39337. Object.defineProperty(PackedRect.prototype, "UVs", {
  39338. /**
  39339. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39340. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39341. */
  39342. get: function () {
  39343. return this.getUVsForCustomSize(this._root._size);
  39344. },
  39345. enumerable: true,
  39346. configurable: true
  39347. });
  39348. /**
  39349. * 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.
  39350. * This method will return the UVs for this part by given the custom size of what you really use
  39351. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39352. */
  39353. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39354. var mainWidth = this._root._size.width;
  39355. var mainHeight = this._root._size.height;
  39356. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39357. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39358. var uvs = new Array();
  39359. uvs.push(topLeft);
  39360. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39361. uvs.push(rightBottom);
  39362. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39363. return uvs;
  39364. };
  39365. /**
  39366. * Free this rectangle from the map.
  39367. * Call this method when you no longer need the rectangle to be in the map.
  39368. */
  39369. PackedRect.prototype.freeContent = function () {
  39370. if (!this.contentSize) {
  39371. return;
  39372. }
  39373. this._contentSize = null;
  39374. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39375. this.attemptDefrag();
  39376. };
  39377. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39378. get: function () {
  39379. return this._contentSize != null || this._leftNode != null;
  39380. },
  39381. enumerable: true,
  39382. configurable: true
  39383. });
  39384. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39385. var node = this.findNode(contentSize);
  39386. // Not enough space...
  39387. if (!node) {
  39388. return null;
  39389. }
  39390. node.splitNode(contentSize);
  39391. return node;
  39392. };
  39393. PackedRect.prototype.findNode = function (size) {
  39394. var resNode = null;
  39395. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39396. if (this.isUsed) {
  39397. if (this._leftNode) {
  39398. resNode = this._leftNode.findNode(size);
  39399. }
  39400. if (!resNode && this._rightNode) {
  39401. resNode = this._rightNode.findNode(size);
  39402. }
  39403. if (!resNode && this._bottomNode) {
  39404. resNode = this._bottomNode.findNode(size);
  39405. }
  39406. }
  39407. else if (this._initialSize) {
  39408. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39409. resNode = this;
  39410. }
  39411. else {
  39412. return null;
  39413. }
  39414. }
  39415. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39416. resNode = this;
  39417. }
  39418. return resNode;
  39419. };
  39420. PackedRect.prototype.splitNode = function (contentSize) {
  39421. // 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)
  39422. if (!this._contentSize && this._initialSize) {
  39423. this._contentSize = contentSize.clone();
  39424. 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));
  39425. return this._leftNode.splitNode(contentSize);
  39426. }
  39427. else {
  39428. this._contentSize = contentSize.clone();
  39429. this._initialSize = contentSize.clone();
  39430. if (contentSize.width !== this._size.width) {
  39431. 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));
  39432. }
  39433. if (contentSize.height !== this._size.height) {
  39434. 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));
  39435. }
  39436. return this;
  39437. }
  39438. };
  39439. PackedRect.prototype.attemptDefrag = function () {
  39440. if (!this.isUsed && this.isRecursiveFree) {
  39441. this.clearNode();
  39442. if (this._parent) {
  39443. this._parent.attemptDefrag();
  39444. }
  39445. }
  39446. };
  39447. PackedRect.prototype.clearNode = function () {
  39448. this._initialSize = null;
  39449. this._rightNode = null;
  39450. this._bottomNode = null;
  39451. };
  39452. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39453. get: function () {
  39454. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39455. },
  39456. enumerable: true,
  39457. configurable: true
  39458. });
  39459. PackedRect.prototype.evalFreeSize = function (size) {
  39460. var levelSize = 0;
  39461. if (!this.isUsed) {
  39462. if (this._initialSize) {
  39463. levelSize = this._initialSize.surface;
  39464. }
  39465. else {
  39466. levelSize = this._size.surface;
  39467. }
  39468. }
  39469. if (this._rightNode) {
  39470. levelSize += this._rightNode.evalFreeSize(0);
  39471. }
  39472. if (this._bottomNode) {
  39473. levelSize += this._bottomNode.evalFreeSize(0);
  39474. }
  39475. return levelSize + size;
  39476. };
  39477. return PackedRect;
  39478. }());
  39479. BABYLON.PackedRect = PackedRect;
  39480. /**
  39481. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39482. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39483. * 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.
  39484. */
  39485. var RectPackingMap = (function (_super) {
  39486. __extends(RectPackingMap, _super);
  39487. /**
  39488. * Create an instance of the object with a dimension using the given size
  39489. * @param size The dimension of the rectangle that will contain all the sub ones.
  39490. */
  39491. function RectPackingMap(size) {
  39492. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  39493. this._root = this;
  39494. }
  39495. /**
  39496. * Add a rectangle, finding the best location to store it into the map
  39497. * @param size the dimension of the rectangle to store
  39498. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39499. */
  39500. RectPackingMap.prototype.addRect = function (size) {
  39501. var node = this.findAndSplitNode(size);
  39502. return node;
  39503. };
  39504. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39505. /**
  39506. * Return the current space free normalized between [0;1]
  39507. * @returns {}
  39508. */
  39509. get: function () {
  39510. var freeSize = 0;
  39511. freeSize = this.evalFreeSize(freeSize);
  39512. return freeSize / (this._size.width * this._size.height);
  39513. },
  39514. enumerable: true,
  39515. configurable: true
  39516. });
  39517. return RectPackingMap;
  39518. }(PackedRect));
  39519. BABYLON.RectPackingMap = RectPackingMap;
  39520. })(BABYLON || (BABYLON = {}));
  39521. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39522. var BABYLON;
  39523. (function (BABYLON) {
  39524. var DynamicFloatArrayElementInfo = (function () {
  39525. function DynamicFloatArrayElementInfo() {
  39526. }
  39527. return DynamicFloatArrayElementInfo;
  39528. }());
  39529. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39530. /**
  39531. * 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.
  39532. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39533. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39534. * 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.
  39535. * 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.
  39536. * 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".
  39537. */
  39538. var DynamicFloatArray = (function () {
  39539. /**
  39540. * Construct an instance of the dynamic float array
  39541. * @param stride size of one element in float (i.e. not bytes!)
  39542. * @param initialElementCount the number of available entries at construction
  39543. */
  39544. function DynamicFloatArray(stride, initialElementCount) {
  39545. this.compareValueOffset = null;
  39546. this.sortingAscending = true;
  39547. this._stride = stride;
  39548. this.buffer = new Float32Array(stride * initialElementCount);
  39549. this._lastUsed = 0;
  39550. this._firstFree = 0;
  39551. this._allEntries = new Array(initialElementCount);
  39552. this._freeEntries = new Array(initialElementCount);
  39553. for (var i = 0; i < initialElementCount; i++) {
  39554. var element = new DynamicFloatArrayElementInfo();
  39555. element.offset = i * stride;
  39556. this._allEntries[i] = element;
  39557. this._freeEntries[initialElementCount - i - 1] = element;
  39558. }
  39559. }
  39560. /**
  39561. * Allocate an element in the array.
  39562. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39563. * Beware, this offset may change when you call pack()
  39564. */
  39565. DynamicFloatArray.prototype.allocElement = function () {
  39566. if (this._freeEntries.length === 0) {
  39567. this._growBuffer();
  39568. }
  39569. var el = this._freeEntries.pop();
  39570. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39571. if (el.offset === this._firstFree) {
  39572. if (this._freeEntries.length > 0) {
  39573. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39574. }
  39575. else {
  39576. this._firstFree += this._stride;
  39577. }
  39578. }
  39579. return el;
  39580. };
  39581. /**
  39582. * Free the element corresponding to the given element info
  39583. * @param elInfo the element that describe the allocated element
  39584. */
  39585. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39586. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39587. this._freeEntries.push(elInfo);
  39588. };
  39589. /**
  39590. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39591. * 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().
  39592. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39593. */
  39594. DynamicFloatArray.prototype.pack = function () {
  39595. // no free slot? no need to pack
  39596. if (this._freeEntries.length === 0) {
  39597. return this.buffer;
  39598. }
  39599. // If the buffer is already packed the last used will always be lower than the first free
  39600. // 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.
  39601. if (this._lastUsed < this._firstFree) {
  39602. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39603. return elementsBuffer_1;
  39604. }
  39605. var s = this._stride;
  39606. // 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
  39607. var lastFree = new DynamicFloatArrayElementInfo();
  39608. lastFree.offset = this.totalElementCount * s;
  39609. this._freeEntries.push(lastFree);
  39610. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39611. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39612. var firstFreeSlotOffset = sortedFree[0].offset;
  39613. var freeZoneSize = 1;
  39614. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39615. var prevOffset = sortedFree[0].offset;
  39616. for (var i = 1; i < sortedFree.length; i++) {
  39617. // 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
  39618. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39619. break;
  39620. }
  39621. var curFree = sortedFree[i];
  39622. var curOffset = curFree.offset;
  39623. // Compute the distance between this offset and the previous
  39624. var distance = curOffset - prevOffset;
  39625. // If the distance is the stride size, they are adjacent, it good, move to the next
  39626. if (distance === s) {
  39627. // Free zone is one element bigger
  39628. ++freeZoneSize;
  39629. // as we're about to iterate to the next, the cur becomes the previous...
  39630. prevOffset = curOffset;
  39631. continue;
  39632. }
  39633. // Distance is bigger, which means there's x element between the previous free and this one
  39634. var usedRange = (distance / s) - 1;
  39635. // Two cases the free zone is smaller than the data to move or bigger
  39636. // Copy what can fit in the free zone
  39637. var curMoveOffset = curOffset - s;
  39638. var copyCount = Math.min(freeZoneSize, usedRange);
  39639. for (var j = 0; j < copyCount; j++) {
  39640. var freeI = firstFreeSlotOffset / s;
  39641. var curI = curMoveOffset / s;
  39642. var moveEl = sortedAll[curI];
  39643. this._moveElement(moveEl, firstFreeSlotOffset);
  39644. var replacedEl = sortedAll[freeI];
  39645. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39646. replacedEl.offset = curMoveOffset;
  39647. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39648. sortedAll[freeI] = moveEl;
  39649. sortedAll[curI] = replacedEl;
  39650. curMoveOffset -= s;
  39651. firstFreeSlotOffset += s;
  39652. }
  39653. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39654. if (freeZoneSize <= usedRange) {
  39655. firstFreeSlotOffset = curMoveOffset + s;
  39656. freeZoneSize = 1 + copyCount;
  39657. }
  39658. else {
  39659. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39660. }
  39661. // as we're about to iterate to the next, the cur becomes the previous...
  39662. prevOffset = curOffset;
  39663. }
  39664. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39665. this._lastUsed = firstFreeSlotOffset - s;
  39666. this._firstFree = firstFreeSlotOffset;
  39667. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39668. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39669. this._allEntries = sortedAll;
  39670. return elementsBuffer;
  39671. };
  39672. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39673. for (var i = 0; i < this._stride; i++) {
  39674. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39675. }
  39676. element.offset = destOffset;
  39677. };
  39678. DynamicFloatArray.prototype._growBuffer = function () {
  39679. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39680. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39681. var newBuffer = new Float32Array(newElCount * this._stride);
  39682. newBuffer.set(this.buffer);
  39683. var curCount = this.totalElementCount;
  39684. var addedCount = newElCount - this.totalElementCount;
  39685. for (var i = 0; i < addedCount; i++) {
  39686. var element = new DynamicFloatArrayElementInfo();
  39687. element.offset = (curCount + i) * this.stride;
  39688. this._allEntries.push(element);
  39689. this._freeEntries[addedCount - i - 1] = element;
  39690. }
  39691. this._firstFree = curCount * this.stride;
  39692. this.buffer = newBuffer;
  39693. };
  39694. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39695. /**
  39696. * Get the total count of entries that can fit in the current buffer
  39697. * @returns the elements count
  39698. */
  39699. get: function () {
  39700. return this._allEntries.length;
  39701. },
  39702. enumerable: true,
  39703. configurable: true
  39704. });
  39705. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39706. /**
  39707. * Get the count of free entries that can still be allocated without resizing the buffer
  39708. * @returns the free elements count
  39709. */
  39710. get: function () {
  39711. return this._freeEntries.length;
  39712. },
  39713. enumerable: true,
  39714. configurable: true
  39715. });
  39716. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39717. /**
  39718. * Get the count of allocated elements
  39719. * @returns the allocated elements count
  39720. */
  39721. get: function () {
  39722. return this._allEntries.length - this._freeEntries.length;
  39723. },
  39724. enumerable: true,
  39725. configurable: true
  39726. });
  39727. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39728. /**
  39729. * Return the size of one element in float
  39730. * @returns the size in float
  39731. */
  39732. get: function () {
  39733. return this._stride;
  39734. },
  39735. enumerable: true,
  39736. configurable: true
  39737. });
  39738. DynamicFloatArray.prototype.sort = function () {
  39739. var _this = this;
  39740. if (!this.compareValueOffset) {
  39741. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39742. }
  39743. var count = this.usedElementCount;
  39744. // Do we have to (re)create the sort table?
  39745. if (!this._sortTable || this._sortTable.length < count) {
  39746. // 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...
  39747. var newCount = Math.min(this.totalElementCount, count * 2);
  39748. this._sortTable = new Array(newCount);
  39749. }
  39750. if (!this._sortedTable || this._sortedTable.length !== count) {
  39751. this._sortedTable = new Array(count);
  39752. }
  39753. // Because, you know...
  39754. this.pack();
  39755. //let stride = this.stride;
  39756. //for (let i = 0; i < count; i++) {
  39757. // let si = this._sortTable[i];
  39758. // if (!si) {
  39759. // si = new SortInfo();
  39760. // this._sortTable[i] = si;
  39761. // }
  39762. // si.entry = this._allEntries[i];
  39763. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39764. // si.swapedOffset = null;
  39765. // this._sortedTable[i] = si;
  39766. //}
  39767. var curOffset = 0;
  39768. var stride = this.stride;
  39769. for (var i = 0; i < count; i++, curOffset += stride) {
  39770. var si = this._sortTable[i];
  39771. if (!si) {
  39772. si = new SortInfo();
  39773. this._sortTable[i] = si;
  39774. }
  39775. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39776. si.offset = curOffset;
  39777. si.swapedOffset = null;
  39778. this._sortedTable[i] = si;
  39779. }
  39780. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39781. if (this.sortingAscending) {
  39782. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39783. }
  39784. else {
  39785. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39786. }
  39787. var swapElements = function (src, dst) {
  39788. for (var i = 0; i < stride; i++) {
  39789. var tps = _this.buffer[dst + i];
  39790. _this.buffer[dst + i] = _this.buffer[src + i];
  39791. _this.buffer[src + i] = tps;
  39792. }
  39793. };
  39794. // 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:
  39795. // 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),
  39796. // and I still want something with a good algorithm complexity.
  39797. // 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,
  39798. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39799. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39800. // 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
  39801. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39802. // 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
  39803. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39804. for (var i = 0; i < count; i++) {
  39805. // Get the element to move
  39806. var sourceSI = this._sortedTable[i];
  39807. var destSI = this._sortTable[i];
  39808. var sourceOff = sourceSI.offset;
  39809. // If the source changed location, find the new one
  39810. if (sourceSI.swapedOffset) {
  39811. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39812. var curSI = sourceSI;
  39813. while (curSI.swapedOffset) {
  39814. curSI = this._sortTable[curSI.swapedOffset / stride];
  39815. }
  39816. // Finally get the right location
  39817. sourceOff = curSI.offset;
  39818. }
  39819. // Tag the element being replaced with its new location
  39820. destSI.swapedOffset = sourceOff;
  39821. // Swap elements (only if needed)
  39822. if (sourceOff !== destSI.offset) {
  39823. swapElements(sourceOff, destSI.offset);
  39824. }
  39825. // Update the offset in the corresponding DFAE
  39826. //sourceSI.entry.offset = destSI.entry.offset;
  39827. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39828. }
  39829. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39830. return true;
  39831. };
  39832. return DynamicFloatArray;
  39833. }());
  39834. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39835. var SortInfo = (function () {
  39836. function SortInfo() {
  39837. this.compareData = this.offset = this.swapedOffset = null;
  39838. }
  39839. return SortInfo;
  39840. }());
  39841. })(BABYLON || (BABYLON = {}));
  39842. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39843. var BABYLON;
  39844. (function (BABYLON) {
  39845. /**
  39846. * This class given information about a given character.
  39847. */
  39848. var CharInfo = (function () {
  39849. function CharInfo() {
  39850. }
  39851. return CharInfo;
  39852. }());
  39853. BABYLON.CharInfo = CharInfo;
  39854. var FontTexture = (function (_super) {
  39855. __extends(FontTexture, _super);
  39856. /**
  39857. * Create a new instance of the FontTexture class
  39858. * @param name the name of the texture
  39859. * @param font the font to use, use the W3C CSS notation
  39860. * @param scene the scene that owns the texture
  39861. * @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
  39862. * @param samplingMode the texture sampling mode
  39863. * @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.
  39864. */
  39865. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39866. if (maxCharCount === void 0) { maxCharCount = 200; }
  39867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39868. if (superSample === void 0) { superSample = false; }
  39869. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39870. _super.call(this, null, scene, true, false, samplingMode);
  39871. this._charInfos = {};
  39872. this._curCharCount = 0;
  39873. this._lastUpdateCharCount = -1;
  39874. this._usedCounter = 1;
  39875. this.name = name;
  39876. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39877. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39878. this._sdfScale = 8;
  39879. this._signedDistanceField = signedDistanceField;
  39880. this._superSample = false;
  39881. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39882. if (superSample || signedDistanceField) {
  39883. var sfont = this.getSuperSampleFont(font);
  39884. if (sfont) {
  39885. this._superSample = true;
  39886. font = sfont;
  39887. }
  39888. }
  39889. // First canvas creation to determine the size of the texture to create
  39890. this._canvas = document.createElement("canvas");
  39891. this._context = this._canvas.getContext("2d");
  39892. this._context.font = font;
  39893. this._context.fillStyle = "white";
  39894. this._context.textBaseline = "top";
  39895. this._cachedFontId = null;
  39896. var res = this.getFontHeight(font);
  39897. this._lineHeightSuper = res.height + 4;
  39898. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39899. this._offset = res.offset - 1;
  39900. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39901. this._yMargin = this._xMargin;
  39902. var maxCharWidth = this._context.measureText("W").width;
  39903. this._spaceWidthSuper = this._context.measureText(" ").width;
  39904. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39905. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39906. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39907. var edge = Math.sqrt(totalEstSurface);
  39908. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39909. // Create the texture that will store the font characters
  39910. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39911. var textureSize = this.getSize();
  39912. this.hasAlpha = this._signedDistanceField === false;
  39913. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39914. this._canvas = document.createElement("canvas");
  39915. this._canvas.width = textureSize.width;
  39916. this._canvas.height = textureSize.height;
  39917. this._context = this._canvas.getContext("2d");
  39918. this._context.textBaseline = "top";
  39919. this._context.font = font;
  39920. this._context.fillStyle = "white";
  39921. this._context.imageSmoothingEnabled = false;
  39922. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39923. // 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
  39924. // 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)
  39925. // So you can see this context as an intermediate one, because it is.
  39926. if (this._signedDistanceField) {
  39927. var sdfC = document.createElement("canvas");
  39928. var s = this._sdfScale;
  39929. sdfC.width = maxCharWidth * s;
  39930. sdfC.height = this._lineHeightSuper * s;
  39931. var sdfCtx = sdfC.getContext("2d");
  39932. sdfCtx.scale(s, s);
  39933. sdfCtx.textBaseline = "top";
  39934. sdfCtx.font = font;
  39935. sdfCtx.fillStyle = "white";
  39936. sdfCtx.imageSmoothingEnabled = false;
  39937. this._sdfCanvas = sdfC;
  39938. this._sdfContext = sdfCtx;
  39939. }
  39940. this._currentFreePosition = BABYLON.Vector2.Zero();
  39941. // Add the basic ASCII based characters
  39942. for (var i = 0x20; i < 0x7F; i++) {
  39943. var c = String.fromCharCode(i);
  39944. this.getChar(c);
  39945. }
  39946. this.update();
  39947. }
  39948. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39949. get: function () {
  39950. return this._superSample;
  39951. },
  39952. enumerable: true,
  39953. configurable: true
  39954. });
  39955. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  39956. get: function () {
  39957. return this._signedDistanceField;
  39958. },
  39959. enumerable: true,
  39960. configurable: true
  39961. });
  39962. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  39963. get: function () {
  39964. return this._spaceWidth;
  39965. },
  39966. enumerable: true,
  39967. configurable: true
  39968. });
  39969. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  39970. get: function () {
  39971. return this._lineHeight;
  39972. },
  39973. enumerable: true,
  39974. configurable: true
  39975. });
  39976. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39977. if (supersample === void 0) { supersample = false; }
  39978. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39979. var s = scene;
  39980. if (!s.__fontTextureCache__) {
  39981. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  39982. }
  39983. var dic = s.__fontTextureCache__;
  39984. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39985. var ft = dic.get(lfn);
  39986. if (ft) {
  39987. ++ft._usedCounter;
  39988. return ft;
  39989. }
  39990. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  39991. ft._cachedFontId = lfn;
  39992. dic.add(lfn, ft);
  39993. return ft;
  39994. };
  39995. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39996. if (supersample === void 0) { supersample = false; }
  39997. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39998. var s = scene;
  39999. var dic = s.__fontTextureCache__;
  40000. if (!dic) {
  40001. return;
  40002. }
  40003. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40004. var font = dic.get(lfn);
  40005. if (--font._usedCounter === 0) {
  40006. dic.remove(lfn);
  40007. font.dispose();
  40008. }
  40009. };
  40010. /**
  40011. * Make sure the given char is present in the font map.
  40012. * @param char the character to get or add
  40013. * @return the CharInfo instance corresponding to the given character
  40014. */
  40015. FontTexture.prototype.getChar = function (char) {
  40016. if (char.length !== 1) {
  40017. return null;
  40018. }
  40019. var info = this._charInfos[char];
  40020. if (info) {
  40021. return info;
  40022. }
  40023. info = new CharInfo();
  40024. var measure = this._context.measureText(char);
  40025. var textureSize = this.getSize();
  40026. // we reached the end of the current line?
  40027. var width = Math.round(measure.width);
  40028. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40029. this._currentFreePosition.x = 0;
  40030. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40031. // No more room?
  40032. if (this._currentFreePosition.y > textureSize.height) {
  40033. return this.getChar("!");
  40034. }
  40035. }
  40036. // 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)
  40037. if (this._signedDistanceField) {
  40038. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40039. this._sdfContext.fillText(char, 0, -this._offset);
  40040. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40041. var res = this._computeSDFChar(data);
  40042. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40043. }
  40044. else {
  40045. // Draw the character in the HTML canvas
  40046. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40047. }
  40048. // Fill the CharInfo object
  40049. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40050. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40051. if (this._signedDistanceField) {
  40052. var off = 1 / textureSize.width;
  40053. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40054. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40055. }
  40056. info.charWidth = this._superSample ? (width / 2) : width;
  40057. // Add the info structure
  40058. this._charInfos[char] = info;
  40059. this._curCharCount++;
  40060. // Set the next position
  40061. this._currentFreePosition.x += width + this._xMargin;
  40062. return info;
  40063. };
  40064. FontTexture.prototype._computeSDFChar = function (source) {
  40065. var scl = this._sdfScale;
  40066. var sw = source.width;
  40067. var sh = source.height;
  40068. var dw = sw / scl;
  40069. var dh = sh / scl;
  40070. var roffx = 0;
  40071. var roffy = 0;
  40072. // We shouldn't look beyond half of the biggest between width and height
  40073. var radius = scl;
  40074. var br = radius - 1;
  40075. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40076. var sx = dx * scl;
  40077. var sy = dy * scl;
  40078. // Looking out of the area? return true to make the test going on
  40079. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40080. return true;
  40081. }
  40082. // Get the pixel we want
  40083. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40084. var res = (val > 0) === lookVis;
  40085. if (!res) {
  40086. roffx = offX;
  40087. roffy = offY;
  40088. }
  40089. return res;
  40090. };
  40091. var lookupArea = function (dx, dy, lookVis) {
  40092. // 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
  40093. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40094. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40095. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40096. lookupSrc(dx, dy, br, 0, lookVis)) {
  40097. return 0;
  40098. }
  40099. for (var i = 1; i <= radius; i++) {
  40100. // Quick test N, S, W, E
  40101. 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)) {
  40102. return i * i; // Squared Distance is simple to compute in this case
  40103. }
  40104. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40105. for (var j = 1; j <= i; j++) {
  40106. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40107. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40108. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40109. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40110. // We found the nearest texel having and opposite state, store the squared length
  40111. var res_1 = (i * i) + (j * j);
  40112. var count = 1;
  40113. // 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
  40114. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40115. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40116. ++count;
  40117. }
  40118. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40119. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40120. ++count;
  40121. }
  40122. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40123. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40124. ++count;
  40125. }
  40126. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40127. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40128. ++count;
  40129. }
  40130. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40131. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40132. ++count;
  40133. }
  40134. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40135. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40136. ++count;
  40137. }
  40138. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40139. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40140. ++count;
  40141. }
  40142. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40143. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40144. ++count;
  40145. }
  40146. // Compute the average based on the accumulated distance
  40147. return res_1 / count;
  40148. }
  40149. }
  40150. }
  40151. return 0;
  40152. };
  40153. var tmp = new Array(dw * dh);
  40154. for (var y = 0; y < dh; y++) {
  40155. for (var x = 0; x < dw; x++) {
  40156. var curState = lookupSrc(x, y, 0, 0, true);
  40157. var d = lookupArea(x, y, curState);
  40158. if (d === 0) {
  40159. d = radius * radius * 2;
  40160. }
  40161. tmp[(y * dw) + x] = curState ? d : -d;
  40162. }
  40163. }
  40164. var res = this._context.createImageData(dw, dh);
  40165. var size = dw * dh;
  40166. for (var j = 0; j < size; j++) {
  40167. var d = tmp[j];
  40168. var sign = (d < 0) ? -1 : 1;
  40169. d = Math.sqrt(Math.abs(d)) * sign;
  40170. d *= 127.5 / radius;
  40171. d += 127.5;
  40172. if (d < 0) {
  40173. d = 0;
  40174. }
  40175. else if (d > 255) {
  40176. d = 255;
  40177. }
  40178. d += 0.5;
  40179. res.data[j * 4 + 0] = d;
  40180. res.data[j * 4 + 1] = d;
  40181. res.data[j * 4 + 2] = d;
  40182. res.data[j * 4 + 3] = 255;
  40183. }
  40184. return res;
  40185. };
  40186. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40187. if (tabulationSize === void 0) { tabulationSize = 4; }
  40188. var maxWidth = 0;
  40189. var curWidth = 0;
  40190. var lineCount = 1;
  40191. var charxpos = 0;
  40192. // Parse each char of the string
  40193. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40194. var char = text_1[_i];
  40195. // Next line feed?
  40196. if (char === "\n") {
  40197. maxWidth = Math.max(maxWidth, curWidth);
  40198. charxpos = 0;
  40199. curWidth = 0;
  40200. ++lineCount;
  40201. continue;
  40202. }
  40203. // Tabulation ?
  40204. if (char === "\t") {
  40205. var nextPos = charxpos + tabulationSize;
  40206. nextPos = nextPos - (nextPos % tabulationSize);
  40207. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40208. charxpos = nextPos;
  40209. continue;
  40210. }
  40211. if (char < " ") {
  40212. continue;
  40213. }
  40214. curWidth += this.getChar(char).charWidth;
  40215. ++charxpos;
  40216. }
  40217. maxWidth = Math.max(maxWidth, curWidth);
  40218. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40219. };
  40220. FontTexture.prototype.getSuperSampleFont = function (font) {
  40221. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40222. 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*$/;
  40223. var res = font.toLocaleLowerCase().match(regex);
  40224. if (res == null) {
  40225. return null;
  40226. }
  40227. var size = parseInt(res[4]);
  40228. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40229. var newFont = "";
  40230. for (var j = 1; j < res.length; j++) {
  40231. if (res[j] != null) {
  40232. newFont += res[j] + " ";
  40233. }
  40234. }
  40235. return newFont;
  40236. };
  40237. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40238. FontTexture.prototype.getFontHeight = function (font) {
  40239. var fontDraw = document.createElement("canvas");
  40240. var ctx = fontDraw.getContext('2d');
  40241. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40242. ctx.textBaseline = 'top';
  40243. ctx.fillStyle = 'white';
  40244. ctx.font = font;
  40245. ctx.fillText('jH|', 0, 0);
  40246. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40247. var start = -1;
  40248. var end = -1;
  40249. for (var row = 0; row < fontDraw.height; row++) {
  40250. for (var column = 0; column < fontDraw.width; column++) {
  40251. var index = (row * fontDraw.width + column) * 4;
  40252. if (pixels[index] === 0) {
  40253. if (column === fontDraw.width - 1 && start !== -1) {
  40254. end = row;
  40255. row = fontDraw.height;
  40256. break;
  40257. }
  40258. continue;
  40259. }
  40260. else {
  40261. if (start === -1) {
  40262. start = row;
  40263. }
  40264. break;
  40265. }
  40266. }
  40267. }
  40268. return { height: (end - start) + 1, offset: start - 1 };
  40269. };
  40270. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40271. get: function () {
  40272. return false;
  40273. },
  40274. enumerable: true,
  40275. configurable: true
  40276. });
  40277. FontTexture.prototype.getContext = function () {
  40278. return this._context;
  40279. };
  40280. /**
  40281. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40282. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40283. */
  40284. FontTexture.prototype.update = function () {
  40285. // Update only if there's new char added since the previous update
  40286. if (this._lastUpdateCharCount < this._curCharCount) {
  40287. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40288. this._lastUpdateCharCount = this._curCharCount;
  40289. }
  40290. };
  40291. // cloning should be prohibited, there's no point to duplicate this texture at all
  40292. FontTexture.prototype.clone = function () {
  40293. return null;
  40294. };
  40295. /**
  40296. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40297. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40298. */
  40299. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40300. ++this._usedCounter;
  40301. };
  40302. /**
  40303. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40304. */
  40305. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40306. var s = this.getScene();
  40307. var dic = s.__fontTextureCache__;
  40308. if (!dic) {
  40309. return;
  40310. }
  40311. if (--this._usedCounter === 0) {
  40312. dic.remove(this._cachedFontId);
  40313. this.dispose();
  40314. }
  40315. };
  40316. return FontTexture;
  40317. }(BABYLON.Texture));
  40318. BABYLON.FontTexture = FontTexture;
  40319. })(BABYLON || (BABYLON = {}));
  40320. //# sourceMappingURL=babylon.fontTexture.js.map
  40321. var BABYLON;
  40322. (function (BABYLON) {
  40323. var MapTexture = (function (_super) {
  40324. __extends(MapTexture, _super);
  40325. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40327. if (useMipMap === void 0) { useMipMap = false; }
  40328. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  40329. this.name = name;
  40330. this._size = size;
  40331. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40332. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40333. // Create the rectPackMap that will allocate portion of the texture
  40334. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40335. // Create the texture that will store the content
  40336. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40337. }
  40338. /**
  40339. * Allocate a rectangle of a given size in the texture map
  40340. * @param size the size of the rectangle to allocation
  40341. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40342. */
  40343. MapTexture.prototype.allocateRect = function (size) {
  40344. return this._rectPackingMap.addRect(size);
  40345. };
  40346. /**
  40347. * Free a given rectangle from the texture map
  40348. * @param rectInfo the instance corresponding to the rect to free.
  40349. */
  40350. MapTexture.prototype.freeRect = function (rectInfo) {
  40351. if (rectInfo) {
  40352. rectInfo.freeContent();
  40353. }
  40354. };
  40355. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40356. /**
  40357. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40358. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40359. * @returns {}
  40360. */
  40361. get: function () {
  40362. return this._rectPackingMap.freeSpace;
  40363. },
  40364. enumerable: true,
  40365. configurable: true
  40366. });
  40367. /**
  40368. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40369. * 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.
  40370. * Don't forget to call unbindTexture when you're done rendering
  40371. * @param rect the zone to render to
  40372. * @param clear true to clear the portion's color/depth data
  40373. */
  40374. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40375. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40376. };
  40377. /**
  40378. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40379. * 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.
  40380. * Don't forget to call unbindTexture when you're done rendering
  40381. * @param pos the position into the texture
  40382. * @param size the portion to fit the clip space to
  40383. * @param clear true to clear the portion's color/depth data
  40384. */
  40385. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40386. var engine = this.getScene().getEngine();
  40387. engine.bindFramebuffer(this._texture);
  40388. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40389. if (clear) {
  40390. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40391. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40392. }
  40393. };
  40394. /**
  40395. * Unbind the texture map from the rendering engine.
  40396. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40397. * @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.
  40398. */
  40399. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40400. // Dump ?
  40401. if (dumpForDebug) {
  40402. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40403. }
  40404. var engine = this.getScene().getEngine();
  40405. if (this._replacedViewport) {
  40406. engine.setViewport(this._replacedViewport);
  40407. this._replacedViewport = null;
  40408. }
  40409. engine.unBindFramebuffer(this._texture);
  40410. };
  40411. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40412. get: function () {
  40413. return false;
  40414. },
  40415. enumerable: true,
  40416. configurable: true
  40417. });
  40418. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40419. // Anyway, there's not much point to use this method for this kind of texture I guess
  40420. MapTexture.prototype.clone = function () {
  40421. return null;
  40422. };
  40423. return MapTexture;
  40424. }(BABYLON.Texture));
  40425. BABYLON.MapTexture = MapTexture;
  40426. })(BABYLON || (BABYLON = {}));
  40427. //# sourceMappingURL=babylon.mapTexture.js.map
  40428. var BABYLON;
  40429. (function (BABYLON) {
  40430. var ShaderMaterial = (function (_super) {
  40431. __extends(ShaderMaterial, _super);
  40432. function ShaderMaterial(name, scene, shaderPath, options) {
  40433. _super.call(this, name, scene);
  40434. this._textures = {};
  40435. this._textureArrays = {};
  40436. this._floats = {};
  40437. this._floatsArrays = {};
  40438. this._colors3 = {};
  40439. this._colors4 = {};
  40440. this._vectors2 = {};
  40441. this._vectors3 = {};
  40442. this._vectors4 = {};
  40443. this._matrices = {};
  40444. this._matrices3x3 = {};
  40445. this._matrices2x2 = {};
  40446. this._vectors3Arrays = {};
  40447. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40448. this._shaderPath = shaderPath;
  40449. options.needAlphaBlending = options.needAlphaBlending || false;
  40450. options.needAlphaTesting = options.needAlphaTesting || false;
  40451. options.attributes = options.attributes || ["position", "normal", "uv"];
  40452. options.uniforms = options.uniforms || ["worldViewProjection"];
  40453. options.samplers = options.samplers || [];
  40454. options.defines = options.defines || [];
  40455. this._options = options;
  40456. }
  40457. ShaderMaterial.prototype.getClassName = function () {
  40458. return "ShaderMaterial";
  40459. };
  40460. ShaderMaterial.prototype.needAlphaBlending = function () {
  40461. return this._options.needAlphaBlending;
  40462. };
  40463. ShaderMaterial.prototype.needAlphaTesting = function () {
  40464. return this._options.needAlphaTesting;
  40465. };
  40466. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40467. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40468. this._options.uniforms.push(uniformName);
  40469. }
  40470. };
  40471. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40472. if (this._options.samplers.indexOf(name) === -1) {
  40473. this._options.samplers.push(name);
  40474. }
  40475. this._textures[name] = texture;
  40476. return this;
  40477. };
  40478. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40479. if (this._options.samplers.indexOf(name) === -1) {
  40480. this._options.samplers.push(name);
  40481. }
  40482. this._checkUniform(name);
  40483. this._textureArrays[name] = textures;
  40484. return this;
  40485. };
  40486. ShaderMaterial.prototype.setFloat = function (name, value) {
  40487. this._checkUniform(name);
  40488. this._floats[name] = value;
  40489. return this;
  40490. };
  40491. ShaderMaterial.prototype.setFloats = function (name, value) {
  40492. this._checkUniform(name);
  40493. this._floatsArrays[name] = value;
  40494. return this;
  40495. };
  40496. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40497. this._checkUniform(name);
  40498. this._colors3[name] = value;
  40499. return this;
  40500. };
  40501. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40502. this._checkUniform(name);
  40503. this._colors4[name] = value;
  40504. return this;
  40505. };
  40506. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40507. this._checkUniform(name);
  40508. this._vectors2[name] = value;
  40509. return this;
  40510. };
  40511. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40512. this._checkUniform(name);
  40513. this._vectors3[name] = value;
  40514. return this;
  40515. };
  40516. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40517. this._checkUniform(name);
  40518. this._vectors4[name] = value;
  40519. return this;
  40520. };
  40521. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40522. this._checkUniform(name);
  40523. this._matrices[name] = value;
  40524. return this;
  40525. };
  40526. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40527. this._checkUniform(name);
  40528. this._matrices3x3[name] = value;
  40529. return this;
  40530. };
  40531. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40532. this._checkUniform(name);
  40533. this._matrices2x2[name] = value;
  40534. return this;
  40535. };
  40536. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40537. this._checkUniform(name);
  40538. this._vectors3Arrays[name] = value;
  40539. return this;
  40540. };
  40541. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40542. if (!mesh) {
  40543. return true;
  40544. }
  40545. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40546. return false;
  40547. }
  40548. return false;
  40549. };
  40550. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40551. var scene = this.getScene();
  40552. var engine = scene.getEngine();
  40553. if (!this.checkReadyOnEveryCall) {
  40554. if (this._renderId === scene.getRenderId()) {
  40555. if (this._checkCache(scene, mesh, useInstances)) {
  40556. return true;
  40557. }
  40558. }
  40559. }
  40560. // Instances
  40561. var defines = [];
  40562. var fallbacks = new BABYLON.EffectFallbacks();
  40563. if (useInstances) {
  40564. defines.push("#define INSTANCES");
  40565. }
  40566. for (var index = 0; index < this._options.defines.length; index++) {
  40567. defines.push(this._options.defines[index]);
  40568. }
  40569. // Bones
  40570. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40571. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40572. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40573. fallbacks.addCPUSkinningFallback(0, mesh);
  40574. }
  40575. // Alpha test
  40576. if (engine.getAlphaTesting()) {
  40577. defines.push("#define ALPHATEST");
  40578. }
  40579. var previousEffect = this._effect;
  40580. var join = defines.join("\n");
  40581. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40582. if (!this._effect.isReady()) {
  40583. return false;
  40584. }
  40585. if (previousEffect !== this._effect) {
  40586. scene.resetCachedMaterial();
  40587. }
  40588. this._renderId = scene.getRenderId();
  40589. return true;
  40590. };
  40591. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40592. var scene = this.getScene();
  40593. if (this._options.uniforms.indexOf("world") !== -1) {
  40594. this._effect.setMatrix("world", world);
  40595. }
  40596. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40597. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40598. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40599. }
  40600. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40601. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40602. }
  40603. };
  40604. ShaderMaterial.prototype.bind = function (world, mesh) {
  40605. // Std values
  40606. this.bindOnlyWorldMatrix(world);
  40607. if (this.getScene().getCachedMaterial() !== this) {
  40608. if (this._options.uniforms.indexOf("view") !== -1) {
  40609. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40610. }
  40611. if (this._options.uniforms.indexOf("projection") !== -1) {
  40612. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40613. }
  40614. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40615. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40616. }
  40617. // Bones
  40618. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40619. var name;
  40620. // Texture
  40621. for (name in this._textures) {
  40622. this._effect.setTexture(name, this._textures[name]);
  40623. }
  40624. // Texture arrays
  40625. for (name in this._textureArrays) {
  40626. this._effect.setTextureArray(name, this._textureArrays[name]);
  40627. }
  40628. // Float
  40629. for (name in this._floats) {
  40630. this._effect.setFloat(name, this._floats[name]);
  40631. }
  40632. // Float s
  40633. for (name in this._floatsArrays) {
  40634. this._effect.setArray(name, this._floatsArrays[name]);
  40635. }
  40636. // Color3
  40637. for (name in this._colors3) {
  40638. this._effect.setColor3(name, this._colors3[name]);
  40639. }
  40640. // Color4
  40641. for (name in this._colors4) {
  40642. var color = this._colors4[name];
  40643. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40644. }
  40645. // Vector2
  40646. for (name in this._vectors2) {
  40647. this._effect.setVector2(name, this._vectors2[name]);
  40648. }
  40649. // Vector3
  40650. for (name in this._vectors3) {
  40651. this._effect.setVector3(name, this._vectors3[name]);
  40652. }
  40653. // Vector4
  40654. for (name in this._vectors4) {
  40655. this._effect.setVector4(name, this._vectors4[name]);
  40656. }
  40657. // Matrix
  40658. for (name in this._matrices) {
  40659. this._effect.setMatrix(name, this._matrices[name]);
  40660. }
  40661. // Matrix 3x3
  40662. for (name in this._matrices3x3) {
  40663. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40664. }
  40665. // Matrix 2x2
  40666. for (name in this._matrices2x2) {
  40667. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40668. }
  40669. // Vector3Array
  40670. for (name in this._vectors3Arrays) {
  40671. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40672. }
  40673. }
  40674. _super.prototype.bind.call(this, world, mesh);
  40675. };
  40676. ShaderMaterial.prototype.clone = function (name) {
  40677. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40678. return newShaderMaterial;
  40679. };
  40680. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40681. if (forceDisposeTextures) {
  40682. var name;
  40683. for (name in this._textures) {
  40684. this._textures[name].dispose();
  40685. }
  40686. for (name in this._textureArrays) {
  40687. var array = this._textureArrays[name];
  40688. for (var index = 0; index < array.length; index++) {
  40689. array[index].dispose();
  40690. }
  40691. }
  40692. }
  40693. this._textures = {};
  40694. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40695. };
  40696. ShaderMaterial.prototype.serialize = function () {
  40697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40698. serializationObject.customType = "BABYLON.ShaderMaterial";
  40699. serializationObject.options = this._options;
  40700. serializationObject.shaderPath = this._shaderPath;
  40701. var name;
  40702. // Texture
  40703. serializationObject.textures = {};
  40704. for (name in this._textures) {
  40705. serializationObject.textures[name] = this._textures[name].serialize();
  40706. }
  40707. // Texture arrays
  40708. serializationObject.textureArrays = {};
  40709. for (name in this._textureArrays) {
  40710. serializationObject.textureArrays[name] = [];
  40711. var array = this._textureArrays[name];
  40712. for (var index = 0; index < array.length; index++) {
  40713. serializationObject.textureArrays[name].push(array[index].serialize());
  40714. }
  40715. }
  40716. // Float
  40717. serializationObject.floats = {};
  40718. for (name in this._floats) {
  40719. serializationObject.floats[name] = this._floats[name];
  40720. }
  40721. // Float s
  40722. serializationObject.floatArrays = {};
  40723. for (name in this._floatsArrays) {
  40724. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40725. }
  40726. // Color3
  40727. serializationObject.colors3 = {};
  40728. for (name in this._colors3) {
  40729. serializationObject.colors3[name] = this._colors3[name].asArray();
  40730. }
  40731. // Color4
  40732. serializationObject.colors4 = {};
  40733. for (name in this._colors4) {
  40734. serializationObject.colors4[name] = this._colors4[name].asArray();
  40735. }
  40736. // Vector2
  40737. serializationObject.vectors2 = {};
  40738. for (name in this._vectors2) {
  40739. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40740. }
  40741. // Vector3
  40742. serializationObject.vectors3 = {};
  40743. for (name in this._vectors3) {
  40744. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40745. }
  40746. // Vector4
  40747. serializationObject.vectors4 = {};
  40748. for (name in this._vectors4) {
  40749. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40750. }
  40751. // Matrix
  40752. serializationObject.matrices = {};
  40753. for (name in this._matrices) {
  40754. serializationObject.matrices[name] = this._matrices[name].asArray();
  40755. }
  40756. // Matrix 3x3
  40757. serializationObject.matrices3x3 = {};
  40758. for (name in this._matrices3x3) {
  40759. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40760. }
  40761. // Matrix 2x2
  40762. serializationObject.matrices2x2 = {};
  40763. for (name in this._matrices2x2) {
  40764. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40765. }
  40766. // Vector3Array
  40767. serializationObject.vectors3Arrays = {};
  40768. for (name in this._vectors3Arrays) {
  40769. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40770. }
  40771. return serializationObject;
  40772. };
  40773. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40774. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40775. var name;
  40776. // Texture
  40777. for (name in source.textures) {
  40778. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40779. }
  40780. // Texture arrays
  40781. for (name in source.textureArrays) {
  40782. var array = source.textureArrays[name];
  40783. var textureArray = new Array();
  40784. for (var index = 0; index < array.length; index++) {
  40785. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40786. }
  40787. material.setTextureArray(name, textureArray);
  40788. }
  40789. // Float
  40790. for (name in source.floats) {
  40791. material.setFloat(name, source.floats[name]);
  40792. }
  40793. // Float s
  40794. for (name in source.floatsArrays) {
  40795. material.setFloats(name, source.floatsArrays[name]);
  40796. }
  40797. // Color3
  40798. for (name in source.colors3) {
  40799. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40800. }
  40801. // Color4
  40802. for (name in source.colors4) {
  40803. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40804. }
  40805. // Vector2
  40806. for (name in source.vectors2) {
  40807. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40808. }
  40809. // Vector3
  40810. for (name in source.vectors3) {
  40811. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40812. }
  40813. // Vector4
  40814. for (name in source.vectors4) {
  40815. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40816. }
  40817. // Matrix
  40818. for (name in source.matrices) {
  40819. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40820. }
  40821. // Matrix 3x3
  40822. for (name in source.matrices3x3) {
  40823. material.setMatrix3x3(name, source.matrices3x3[name]);
  40824. }
  40825. // Matrix 2x2
  40826. for (name in source.matrices2x2) {
  40827. material.setMatrix2x2(name, source.matrices2x2[name]);
  40828. }
  40829. // Vector3Array
  40830. for (name in source.vectors3Arrays) {
  40831. material.setArray3(name, source.vectors3Arrays[name]);
  40832. }
  40833. return material;
  40834. };
  40835. return ShaderMaterial;
  40836. }(BABYLON.Material));
  40837. BABYLON.ShaderMaterial = ShaderMaterial;
  40838. })(BABYLON || (BABYLON = {}));
  40839. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40840. var BABYLON;
  40841. (function (BABYLON) {
  40842. var Internals;
  40843. (function (Internals) {
  40844. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40845. // All values and structures referenced from:
  40846. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40847. var DDS_MAGIC = 0x20534444;
  40848. 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;
  40849. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40850. 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;
  40851. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40852. function FourCCToInt32(value) {
  40853. return value.charCodeAt(0) +
  40854. (value.charCodeAt(1) << 8) +
  40855. (value.charCodeAt(2) << 16) +
  40856. (value.charCodeAt(3) << 24);
  40857. }
  40858. function Int32ToFourCC(value) {
  40859. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40860. }
  40861. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40862. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40863. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40864. var headerLengthInt = 31; // The header length in 32 bit ints
  40865. // Offsets into the header array
  40866. var off_magic = 0;
  40867. var off_size = 1;
  40868. var off_flags = 2;
  40869. var off_height = 3;
  40870. var off_width = 4;
  40871. var off_mipmapCount = 7;
  40872. var off_pfFlags = 20;
  40873. var off_pfFourCC = 21;
  40874. var off_RGBbpp = 22;
  40875. var off_RMask = 23;
  40876. var off_GMask = 24;
  40877. var off_BMask = 25;
  40878. var off_AMask = 26;
  40879. var off_caps1 = 27;
  40880. var off_caps2 = 28;
  40881. ;
  40882. var DDSTools = (function () {
  40883. function DDSTools() {
  40884. }
  40885. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40886. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40887. var mipmapCount = 1;
  40888. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40889. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40890. }
  40891. return {
  40892. width: header[off_width],
  40893. height: header[off_height],
  40894. mipmapCount: mipmapCount,
  40895. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40896. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40897. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40898. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40899. };
  40900. };
  40901. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40902. var byteArray = new Uint8Array(dataLength);
  40903. var srcData = new Uint8Array(arrayBuffer);
  40904. var index = 0;
  40905. for (var y = height - 1; y >= 0; y--) {
  40906. for (var x = 0; x < width; x++) {
  40907. var srcPos = dataOffset + (x + y * width) * 4;
  40908. byteArray[index + 2] = srcData[srcPos];
  40909. byteArray[index + 1] = srcData[srcPos + 1];
  40910. byteArray[index] = srcData[srcPos + 2];
  40911. byteArray[index + 3] = srcData[srcPos + 3];
  40912. index += 4;
  40913. }
  40914. }
  40915. return byteArray;
  40916. };
  40917. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40918. var byteArray = new Uint8Array(dataLength);
  40919. var srcData = new Uint8Array(arrayBuffer);
  40920. var index = 0;
  40921. for (var y = height - 1; y >= 0; y--) {
  40922. for (var x = 0; x < width; x++) {
  40923. var srcPos = dataOffset + (x + y * width) * 3;
  40924. byteArray[index + 2] = srcData[srcPos];
  40925. byteArray[index + 1] = srcData[srcPos + 1];
  40926. byteArray[index] = srcData[srcPos + 2];
  40927. index += 3;
  40928. }
  40929. }
  40930. return byteArray;
  40931. };
  40932. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40933. var byteArray = new Uint8Array(dataLength);
  40934. var srcData = new Uint8Array(arrayBuffer);
  40935. var index = 0;
  40936. for (var y = height - 1; y >= 0; y--) {
  40937. for (var x = 0; x < width; x++) {
  40938. var srcPos = dataOffset + (x + y * width);
  40939. byteArray[index] = srcData[srcPos];
  40940. index++;
  40941. }
  40942. }
  40943. return byteArray;
  40944. };
  40945. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40946. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40947. if (header[off_magic] != DDS_MAGIC) {
  40948. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40949. return;
  40950. }
  40951. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40952. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40953. return;
  40954. }
  40955. if (info.isFourCC) {
  40956. fourCC = header[off_pfFourCC];
  40957. switch (fourCC) {
  40958. case FOURCC_DXT1:
  40959. blockBytes = 8;
  40960. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40961. break;
  40962. case FOURCC_DXT3:
  40963. blockBytes = 16;
  40964. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40965. break;
  40966. case FOURCC_DXT5:
  40967. blockBytes = 16;
  40968. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40969. break;
  40970. default:
  40971. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40972. return;
  40973. }
  40974. }
  40975. mipmapCount = 1;
  40976. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40977. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40978. }
  40979. var bpp = header[off_RGBbpp];
  40980. for (var face = 0; face < faces; face++) {
  40981. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40982. width = header[off_width];
  40983. height = header[off_height];
  40984. dataOffset = header[off_size] + 4;
  40985. for (i = 0; i < mipmapCount; ++i) {
  40986. if (info.isRGB) {
  40987. if (bpp === 24) {
  40988. dataLength = width * height * 3;
  40989. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40990. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40991. }
  40992. else {
  40993. dataLength = width * height * 4;
  40994. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40995. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40996. }
  40997. }
  40998. else if (info.isLuminance) {
  40999. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41000. var unpaddedRowSize = width;
  41001. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41002. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41003. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41004. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41005. }
  41006. else {
  41007. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41008. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41009. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41010. }
  41011. dataOffset += dataLength;
  41012. width *= 0.5;
  41013. height *= 0.5;
  41014. width = Math.max(1.0, width);
  41015. height = Math.max(1.0, height);
  41016. }
  41017. }
  41018. };
  41019. return DDSTools;
  41020. }());
  41021. Internals.DDSTools = DDSTools;
  41022. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41023. })(BABYLON || (BABYLON = {}));
  41024. //# sourceMappingURL=babylon.tools.dds.js.map
  41025. var BABYLON;
  41026. (function (BABYLON) {
  41027. var CannonJSPlugin = (function () {
  41028. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41029. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41030. if (iterations === void 0) { iterations = 10; }
  41031. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41032. this.name = "CannonJSPlugin";
  41033. this._physicsMaterials = [];
  41034. this._fixedTimeStep = 1 / 60;
  41035. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41036. this._currentCollisionGroup = 2;
  41037. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41038. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41039. this._tmpPosition = BABYLON.Vector3.Zero();
  41040. this._tmpQuaternion = new BABYLON.Quaternion();
  41041. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41042. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41043. this._tmpUnityRotation = new BABYLON.Quaternion();
  41044. if (!this.isSupported()) {
  41045. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41046. return;
  41047. }
  41048. this.world = new CANNON.World();
  41049. this.world.broadphase = new CANNON.NaiveBroadphase();
  41050. this.world.solver.iterations = iterations;
  41051. }
  41052. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41053. this.world.gravity.copy(gravity);
  41054. };
  41055. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41056. this._fixedTimeStep = timeStep;
  41057. };
  41058. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41059. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41060. };
  41061. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41062. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41063. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41064. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41065. };
  41066. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41067. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41068. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41069. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41070. };
  41071. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41072. //parent-child relationship. Does this impostor has a parent impostor?
  41073. if (impostor.parent) {
  41074. if (impostor.physicsBody) {
  41075. this.removePhysicsBody(impostor);
  41076. //TODO is that needed?
  41077. impostor.forceUpdate();
  41078. }
  41079. return;
  41080. }
  41081. //should a new body be created for this impostor?
  41082. if (impostor.isBodyInitRequired()) {
  41083. var shape = this._createShape(impostor);
  41084. //unregister events, if body is being changed
  41085. var oldBody = impostor.physicsBody;
  41086. if (oldBody) {
  41087. this.removePhysicsBody(impostor);
  41088. }
  41089. //create the body and material
  41090. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41091. var bodyCreationObject = {
  41092. mass: impostor.getParam("mass"),
  41093. material: material
  41094. };
  41095. // A simple extend, in case native options were used.
  41096. var nativeOptions = impostor.getParam("nativeOptions");
  41097. for (var key in nativeOptions) {
  41098. if (nativeOptions.hasOwnProperty(key)) {
  41099. bodyCreationObject[key] = nativeOptions[key];
  41100. }
  41101. }
  41102. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41103. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41104. this.world.addEventListener("preStep", impostor.beforeStep);
  41105. this.world.addEventListener("postStep", impostor.afterStep);
  41106. impostor.physicsBody.addShape(shape);
  41107. this.world.add(impostor.physicsBody);
  41108. //try to keep the body moving in the right direction by taking old properties.
  41109. //Should be tested!
  41110. if (oldBody) {
  41111. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41112. impostor.physicsBody[param].copy(oldBody[param]);
  41113. });
  41114. }
  41115. this._processChildMeshes(impostor);
  41116. }
  41117. //now update the body's transformation
  41118. this._updatePhysicsBodyTransformation(impostor);
  41119. };
  41120. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41121. var _this = this;
  41122. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41123. if (meshChildren.length) {
  41124. var processMesh = function (localPosition, mesh) {
  41125. var childImpostor = mesh.getPhysicsImpostor();
  41126. if (childImpostor) {
  41127. var parent = childImpostor.parent;
  41128. if (parent !== mainImpostor) {
  41129. var localPosition = mesh.position;
  41130. if (childImpostor.physicsBody) {
  41131. _this.removePhysicsBody(childImpostor);
  41132. childImpostor.physicsBody = null;
  41133. }
  41134. childImpostor.parent = mainImpostor;
  41135. childImpostor.resetUpdateFlags();
  41136. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41137. //Add the mass of the children.
  41138. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41139. }
  41140. }
  41141. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41142. };
  41143. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41144. }
  41145. };
  41146. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41147. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41148. this.world.removeEventListener("preStep", impostor.beforeStep);
  41149. this.world.removeEventListener("postStep", impostor.afterStep);
  41150. this.world.remove(impostor.physicsBody);
  41151. };
  41152. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41153. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41154. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41155. if (!mainBody || !connectedBody) {
  41156. return;
  41157. }
  41158. var constraint;
  41159. var jointData = impostorJoint.joint.jointData;
  41160. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41161. var constraintData = {
  41162. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41163. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41164. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41165. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41166. maxForce: jointData.nativeParams.maxForce,
  41167. collideConnected: !!jointData.collision
  41168. };
  41169. //Not needed, Cannon has a collideConnected flag
  41170. /*if (!jointData.collision) {
  41171. //add 1st body to a collision group of its own, if it is not in 1
  41172. if (mainBody.collisionFilterGroup === 1) {
  41173. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41174. this._currentCollisionGroup <<= 1;
  41175. }
  41176. if (connectedBody.collisionFilterGroup === 1) {
  41177. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41178. this._currentCollisionGroup <<= 1;
  41179. }
  41180. //add their mask to the collisionFilterMask of each other:
  41181. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41182. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41183. }*/
  41184. switch (impostorJoint.joint.type) {
  41185. case BABYLON.PhysicsJoint.HingeJoint:
  41186. case BABYLON.PhysicsJoint.Hinge2Joint:
  41187. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41188. break;
  41189. case BABYLON.PhysicsJoint.DistanceJoint:
  41190. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41191. break;
  41192. case BABYLON.PhysicsJoint.SpringJoint:
  41193. var springData = jointData;
  41194. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41195. restLength: springData.length,
  41196. stiffness: springData.stiffness,
  41197. damping: springData.damping,
  41198. localAnchorA: constraintData.pivotA,
  41199. localAnchorB: constraintData.pivotB
  41200. });
  41201. break;
  41202. case BABYLON.PhysicsJoint.LockJoint:
  41203. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41204. break;
  41205. case BABYLON.PhysicsJoint.PointToPointJoint:
  41206. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41207. default:
  41208. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41209. break;
  41210. }
  41211. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41212. constraint.collideConnected = !!jointData.collision;
  41213. impostorJoint.joint.physicsJoint = constraint;
  41214. //don't add spring as constraint, as it is not one.
  41215. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41216. this.world.addConstraint(constraint);
  41217. }
  41218. else {
  41219. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41220. constraint.applyForce();
  41221. });
  41222. }
  41223. };
  41224. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41225. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41226. };
  41227. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41228. var index;
  41229. var mat;
  41230. for (index = 0; index < this._physicsMaterials.length; index++) {
  41231. mat = this._physicsMaterials[index];
  41232. if (mat.friction === friction && mat.restitution === restitution) {
  41233. return mat;
  41234. }
  41235. }
  41236. var currentMat = new CANNON.Material(name);
  41237. currentMat.friction = friction;
  41238. currentMat.restitution = restitution;
  41239. this._physicsMaterials.push(currentMat);
  41240. return currentMat;
  41241. };
  41242. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41243. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41244. };
  41245. CannonJSPlugin.prototype._createShape = function (impostor) {
  41246. var object = impostor.object;
  41247. var returnValue;
  41248. var extendSize = impostor.getObjectExtendSize();
  41249. switch (impostor.type) {
  41250. case BABYLON.PhysicsEngine.SphereImpostor:
  41251. var radiusX = extendSize.x;
  41252. var radiusY = extendSize.y;
  41253. var radiusZ = extendSize.z;
  41254. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41255. break;
  41256. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41257. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41258. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41259. break;
  41260. case BABYLON.PhysicsImpostor.BoxImpostor:
  41261. var box = extendSize.scale(0.5);
  41262. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41263. break;
  41264. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41265. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41266. returnValue = new CANNON.Plane();
  41267. break;
  41268. case BABYLON.PhysicsImpostor.MeshImpostor:
  41269. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41270. var rawFaces = object.getIndices ? object.getIndices() : [];
  41271. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41272. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41273. break;
  41274. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41275. returnValue = this._createHeightmap(object);
  41276. break;
  41277. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41278. returnValue = new CANNON.Particle();
  41279. break;
  41280. }
  41281. return returnValue;
  41282. };
  41283. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41284. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41285. var matrix = [];
  41286. //For now pointDepth will not be used and will be automatically calculated.
  41287. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41288. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41289. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41290. var elementSize = dim * 2 / arraySize;
  41291. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41292. for (var i = 0; i < pos.length; i = i + 3) {
  41293. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41294. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41295. var y = pos[i + 1] + minY;
  41296. if (!matrix[x]) {
  41297. matrix[x] = [];
  41298. }
  41299. if (!matrix[x][z]) {
  41300. matrix[x][z] = y;
  41301. }
  41302. matrix[x][z] = Math.max(y, matrix[x][z]);
  41303. }
  41304. for (var x = 0; x <= arraySize; ++x) {
  41305. if (!matrix[x]) {
  41306. var loc = 1;
  41307. while (!matrix[(x + loc) % arraySize]) {
  41308. loc++;
  41309. }
  41310. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41311. }
  41312. for (var z = 0; z <= arraySize; ++z) {
  41313. if (!matrix[x][z]) {
  41314. var loc = 1;
  41315. var newValue;
  41316. while (newValue === undefined) {
  41317. newValue = matrix[x][(z + loc++) % arraySize];
  41318. }
  41319. matrix[x][z] = newValue;
  41320. }
  41321. }
  41322. }
  41323. var shape = new CANNON.Heightfield(matrix, {
  41324. elementSize: elementSize
  41325. });
  41326. //For future reference, needed for body transformation
  41327. shape.minY = minY;
  41328. return shape;
  41329. };
  41330. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41331. var object = impostor.object;
  41332. //make sure it is updated...
  41333. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41334. // The delta between the mesh position and the mesh bounding box center
  41335. var center = impostor.getObjectCenter();
  41336. var extendSize = impostor.getObjectExtendSize();
  41337. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41338. this._tmpPosition.copyFrom(center);
  41339. var quaternion = object.rotationQuaternion;
  41340. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41341. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41342. //-90 DEG in X, precalculated
  41343. quaternion = quaternion.multiply(this._minus90X);
  41344. //Invert! (Precalculated, 90 deg in X)
  41345. //No need to clone. this will never change.
  41346. impostor.setDeltaRotation(this._plus90X);
  41347. }
  41348. //If it is a heightfield, if should be centered.
  41349. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41350. var mesh = object;
  41351. //calculate the correct body position:
  41352. var rotationQuaternion = mesh.rotationQuaternion;
  41353. mesh.rotationQuaternion = this._tmpUnityRotation;
  41354. mesh.computeWorldMatrix(true);
  41355. //get original center with no rotation
  41356. var c = center.clone();
  41357. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41358. //rotation is back
  41359. mesh.rotationQuaternion = rotationQuaternion;
  41360. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41361. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41362. mesh.setPivotMatrix(p);
  41363. mesh.computeWorldMatrix(true);
  41364. //calculate the translation
  41365. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41366. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41367. //add it inverted to the delta
  41368. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41369. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41370. mesh.setPivotMatrix(oldPivot);
  41371. mesh.computeWorldMatrix(true);
  41372. }
  41373. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41374. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41375. this._tmpPosition.copyFrom(object.position);
  41376. }
  41377. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41378. //Now update the impostor object
  41379. impostor.physicsBody.position.copy(this._tmpPosition);
  41380. impostor.physicsBody.quaternion.copy(quaternion);
  41381. };
  41382. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41383. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41384. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41385. };
  41386. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41387. impostor.physicsBody.position.copy(newPosition);
  41388. impostor.physicsBody.quaternion.copy(newRotation);
  41389. };
  41390. CannonJSPlugin.prototype.isSupported = function () {
  41391. return window.CANNON !== undefined;
  41392. };
  41393. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41394. impostor.physicsBody.velocity.copy(velocity);
  41395. };
  41396. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41397. impostor.physicsBody.angularVelocity.copy(velocity);
  41398. };
  41399. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41400. var v = impostor.physicsBody.velocity;
  41401. if (!v)
  41402. return null;
  41403. return new BABYLON.Vector3(v.x, v.y, v.z);
  41404. };
  41405. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41406. var v = impostor.physicsBody.angularVelocity;
  41407. if (!v)
  41408. return null;
  41409. return new BABYLON.Vector3(v.x, v.y, v.z);
  41410. };
  41411. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41412. impostor.physicsBody.mass = mass;
  41413. impostor.physicsBody.updateMassProperties();
  41414. };
  41415. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41416. impostor.physicsBody.sleep();
  41417. };
  41418. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41419. impostor.physicsBody.wakeUp();
  41420. };
  41421. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41422. joint.physicsJoint.distance = maxDistance;
  41423. };
  41424. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41425. if (!motorIndex) {
  41426. joint.physicsJoint.enableMotor();
  41427. }
  41428. };
  41429. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41430. if (!motorIndex) {
  41431. joint.physicsJoint.disableMotor();
  41432. }
  41433. };
  41434. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41435. if (!motorIndex) {
  41436. joint.physicsJoint.enableMotor();
  41437. joint.physicsJoint.setMotorSpeed(speed);
  41438. if (maxForce) {
  41439. this.setLimit(joint, maxForce);
  41440. }
  41441. }
  41442. };
  41443. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41444. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41445. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41446. };
  41447. CannonJSPlugin.prototype.dispose = function () {
  41448. //nothing to do, actually.
  41449. };
  41450. return CannonJSPlugin;
  41451. }());
  41452. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41453. })(BABYLON || (BABYLON = {}));
  41454. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41455. var BABYLON;
  41456. (function (BABYLON) {
  41457. var OimoJSPlugin = (function () {
  41458. function OimoJSPlugin(iterations) {
  41459. this.name = "OimoJSPlugin";
  41460. this._tmpImpostorsArray = [];
  41461. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41462. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41463. this.world.worldscale(1);
  41464. this.world.clear();
  41465. //making sure no stats are calculated
  41466. this.world.isNoStat = true;
  41467. }
  41468. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41469. this.world.gravity.copy(gravity);
  41470. };
  41471. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41472. this.world.timeStep = timeStep;
  41473. };
  41474. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41475. var _this = this;
  41476. impostors.forEach(function (impostor) {
  41477. impostor.beforeStep();
  41478. });
  41479. this.world.step();
  41480. impostors.forEach(function (impostor) {
  41481. impostor.afterStep();
  41482. //update the ordered impostors array
  41483. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41484. });
  41485. //check for collisions
  41486. var contact = this.world.contacts;
  41487. while (contact !== null) {
  41488. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41489. contact = contact.next;
  41490. continue;
  41491. }
  41492. //is this body colliding with any other? get the impostor
  41493. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41494. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41495. if (!mainImpostor || !collidingImpostor) {
  41496. contact = contact.next;
  41497. continue;
  41498. }
  41499. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41500. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41501. contact = contact.next;
  41502. }
  41503. };
  41504. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41505. var mass = impostor.physicsBody.massInfo.mass;
  41506. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41507. };
  41508. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41509. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41510. this.applyImpulse(impostor, force, contactPoint);
  41511. };
  41512. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41513. var _this = this;
  41514. //parent-child relationship. Does this impostor has a parent impostor?
  41515. if (impostor.parent) {
  41516. if (impostor.physicsBody) {
  41517. this.removePhysicsBody(impostor);
  41518. //TODO is that needed?
  41519. impostor.forceUpdate();
  41520. }
  41521. return;
  41522. }
  41523. if (impostor.isBodyInitRequired()) {
  41524. var bodyConfig = {
  41525. name: impostor.uniqueId,
  41526. //Oimo must have mass, also for static objects.
  41527. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41528. size: [],
  41529. type: [],
  41530. pos: [],
  41531. rot: [],
  41532. move: impostor.getParam("mass") !== 0,
  41533. //Supporting older versions of Oimo
  41534. world: this.world
  41535. };
  41536. var impostors = [impostor];
  41537. var addToArray = function (parent) {
  41538. if (!parent.getChildMeshes)
  41539. return;
  41540. parent.getChildMeshes().forEach(function (m) {
  41541. if (m.physicsImpostor) {
  41542. impostors.push(m.physicsImpostor);
  41543. m.physicsImpostor._init();
  41544. }
  41545. });
  41546. };
  41547. addToArray(impostor.object);
  41548. var checkWithEpsilon_1 = function (value) {
  41549. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41550. };
  41551. impostors.forEach(function (i) {
  41552. //get the correct bounding box
  41553. var oldQuaternion = i.object.rotationQuaternion;
  41554. var rot = new OIMO.Euler().setFromQuaternion({
  41555. x: impostor.object.rotationQuaternion.x,
  41556. y: impostor.object.rotationQuaternion.y,
  41557. z: impostor.object.rotationQuaternion.z,
  41558. s: impostor.object.rotationQuaternion.w
  41559. });
  41560. var extendSize = i.getObjectExtendSize();
  41561. if (i === impostor) {
  41562. var center = impostor.getObjectCenter();
  41563. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41564. //Can also use Array.prototype.push.apply
  41565. bodyConfig.pos.push(center.x);
  41566. bodyConfig.pos.push(center.y);
  41567. bodyConfig.pos.push(center.z);
  41568. //tmp solution
  41569. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41570. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41571. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41572. }
  41573. else {
  41574. bodyConfig.pos.push(i.object.position.x);
  41575. bodyConfig.pos.push(i.object.position.y);
  41576. bodyConfig.pos.push(i.object.position.z);
  41577. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41578. bodyConfig.rot.push(0);
  41579. bodyConfig.rot.push(0);
  41580. bodyConfig.rot.push(0);
  41581. }
  41582. // register mesh
  41583. switch (i.type) {
  41584. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41585. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41586. case BABYLON.PhysicsImpostor.SphereImpostor:
  41587. var radiusX = extendSize.x;
  41588. var radiusY = extendSize.y;
  41589. var radiusZ = extendSize.z;
  41590. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41591. bodyConfig.type.push('sphere');
  41592. //due to the way oimo works with compounds, add 3 times
  41593. bodyConfig.size.push(size);
  41594. bodyConfig.size.push(size);
  41595. bodyConfig.size.push(size);
  41596. break;
  41597. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41598. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41599. var sizeY = checkWithEpsilon_1(extendSize.y);
  41600. bodyConfig.type.push('cylinder');
  41601. bodyConfig.size.push(sizeX);
  41602. bodyConfig.size.push(sizeY);
  41603. //due to the way oimo works with compounds, add one more value.
  41604. bodyConfig.size.push(sizeY);
  41605. break;
  41606. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41607. case BABYLON.PhysicsImpostor.BoxImpostor:
  41608. default:
  41609. var sizeX = checkWithEpsilon_1(extendSize.x);
  41610. var sizeY = checkWithEpsilon_1(extendSize.y);
  41611. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41612. bodyConfig.type.push('box');
  41613. bodyConfig.size.push(sizeX);
  41614. bodyConfig.size.push(sizeY);
  41615. bodyConfig.size.push(sizeZ);
  41616. break;
  41617. }
  41618. //actually not needed, but hey...
  41619. i.object.rotationQuaternion = oldQuaternion;
  41620. });
  41621. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41622. }
  41623. else {
  41624. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41625. }
  41626. impostor.setDeltaPosition(this._tmpPositionVector);
  41627. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41628. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41629. };
  41630. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41631. //impostor.physicsBody.dispose();
  41632. //Same as : (older oimo versions)
  41633. this.world.removeRigidBody(impostor.physicsBody);
  41634. };
  41635. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41636. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41637. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41638. if (!mainBody || !connectedBody) {
  41639. return;
  41640. }
  41641. var jointData = impostorJoint.joint.jointData;
  41642. var options = jointData.nativeParams || {};
  41643. var type;
  41644. var nativeJointData = {
  41645. body1: mainBody,
  41646. body2: connectedBody,
  41647. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41648. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41649. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41650. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41651. min: options.min,
  41652. max: options.max,
  41653. collision: options.collision || jointData.collision,
  41654. spring: options.spring,
  41655. //supporting older version of Oimo
  41656. world: this.world
  41657. };
  41658. switch (impostorJoint.joint.type) {
  41659. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41660. type = "jointBall";
  41661. break;
  41662. case BABYLON.PhysicsJoint.SpringJoint:
  41663. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41664. var springData = jointData;
  41665. nativeJointData.min = springData.length || nativeJointData.min;
  41666. //Max should also be set, just make sure it is at least min
  41667. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41668. case BABYLON.PhysicsJoint.DistanceJoint:
  41669. type = "jointDistance";
  41670. nativeJointData.max = jointData.maxDistance;
  41671. break;
  41672. case BABYLON.PhysicsJoint.PrismaticJoint:
  41673. type = "jointPrisme";
  41674. break;
  41675. case BABYLON.PhysicsJoint.SliderJoint:
  41676. type = "jointSlide";
  41677. break;
  41678. case BABYLON.PhysicsJoint.WheelJoint:
  41679. type = "jointWheel";
  41680. break;
  41681. case BABYLON.PhysicsJoint.HingeJoint:
  41682. default:
  41683. type = "jointHinge";
  41684. break;
  41685. }
  41686. nativeJointData.type = type;
  41687. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41688. };
  41689. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41690. //Bug in Oimo prevents us from disposing a joint in the playground
  41691. //joint.joint.physicsJoint.dispose();
  41692. //So we will bruteforce it!
  41693. try {
  41694. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41695. }
  41696. catch (e) {
  41697. BABYLON.Tools.Warn(e);
  41698. }
  41699. };
  41700. OimoJSPlugin.prototype.isSupported = function () {
  41701. return OIMO !== undefined;
  41702. };
  41703. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41704. if (!impostor.physicsBody.sleeping) {
  41705. //TODO check that
  41706. if (impostor.physicsBody.shapes.next) {
  41707. var parentShape = this._getLastShape(impostor.physicsBody);
  41708. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41709. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41710. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41711. }
  41712. else {
  41713. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41714. }
  41715. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41716. impostor.object.rotationQuaternion.normalize();
  41717. }
  41718. };
  41719. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41720. var body = impostor.physicsBody;
  41721. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41722. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41723. body.syncShapes();
  41724. body.awake();
  41725. };
  41726. OimoJSPlugin.prototype._getLastShape = function (body) {
  41727. var lastShape = body.shapes;
  41728. while (lastShape.next) {
  41729. lastShape = lastShape.next;
  41730. }
  41731. return lastShape;
  41732. };
  41733. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41734. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41735. };
  41736. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41737. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41738. };
  41739. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41740. var v = impostor.physicsBody.linearVelocity;
  41741. if (!v)
  41742. return null;
  41743. return new BABYLON.Vector3(v.x, v.y, v.z);
  41744. };
  41745. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41746. var v = impostor.physicsBody.angularVelocity;
  41747. if (!v)
  41748. return null;
  41749. return new BABYLON.Vector3(v.x, v.y, v.z);
  41750. };
  41751. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41752. var staticBody = mass === 0;
  41753. //this will actually set the body's density and not its mass.
  41754. //But this is how oimo treats the mass variable.
  41755. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41756. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41757. };
  41758. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41759. impostor.physicsBody.sleep();
  41760. };
  41761. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41762. impostor.physicsBody.awake();
  41763. };
  41764. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41765. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41766. if (minDistance !== void 0) {
  41767. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41768. }
  41769. };
  41770. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41771. //TODO separate rotational and transational motors.
  41772. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41773. if (motor) {
  41774. motor.setMotor(speed, maxForce);
  41775. }
  41776. };
  41777. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41778. //TODO separate rotational and transational motors.
  41779. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41780. if (motor) {
  41781. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41782. }
  41783. };
  41784. OimoJSPlugin.prototype.dispose = function () {
  41785. this.world.clear();
  41786. };
  41787. return OimoJSPlugin;
  41788. }());
  41789. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41790. })(BABYLON || (BABYLON = {}));
  41791. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41792. var BABYLON;
  41793. (function (BABYLON) {
  41794. var DisplayPassPostProcess = (function (_super) {
  41795. __extends(DisplayPassPostProcess, _super);
  41796. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41797. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  41798. }
  41799. return DisplayPassPostProcess;
  41800. }(BABYLON.PostProcess));
  41801. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41802. })(BABYLON || (BABYLON = {}));
  41803. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41804. var BABYLON;
  41805. (function (BABYLON) {
  41806. var SimplificationSettings = (function () {
  41807. function SimplificationSettings(quality, distance, optimizeMesh) {
  41808. this.quality = quality;
  41809. this.distance = distance;
  41810. this.optimizeMesh = optimizeMesh;
  41811. }
  41812. return SimplificationSettings;
  41813. }());
  41814. BABYLON.SimplificationSettings = SimplificationSettings;
  41815. var SimplificationQueue = (function () {
  41816. function SimplificationQueue() {
  41817. this.running = false;
  41818. this._simplificationArray = [];
  41819. }
  41820. SimplificationQueue.prototype.addTask = function (task) {
  41821. this._simplificationArray.push(task);
  41822. };
  41823. SimplificationQueue.prototype.executeNext = function () {
  41824. var task = this._simplificationArray.pop();
  41825. if (task) {
  41826. this.running = true;
  41827. this.runSimplification(task);
  41828. }
  41829. else {
  41830. this.running = false;
  41831. }
  41832. };
  41833. SimplificationQueue.prototype.runSimplification = function (task) {
  41834. var _this = this;
  41835. if (task.parallelProcessing) {
  41836. //parallel simplifier
  41837. task.settings.forEach(function (setting) {
  41838. var simplifier = _this.getSimplifier(task);
  41839. simplifier.simplify(setting, function (newMesh) {
  41840. task.mesh.addLODLevel(setting.distance, newMesh);
  41841. newMesh.isVisible = true;
  41842. //check if it is the last
  41843. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41844. //all done, run the success callback.
  41845. task.successCallback();
  41846. }
  41847. _this.executeNext();
  41848. });
  41849. });
  41850. }
  41851. else {
  41852. //single simplifier.
  41853. var simplifier = this.getSimplifier(task);
  41854. var runDecimation = function (setting, callback) {
  41855. simplifier.simplify(setting, function (newMesh) {
  41856. task.mesh.addLODLevel(setting.distance, newMesh);
  41857. newMesh.isVisible = true;
  41858. //run the next quality level
  41859. callback();
  41860. });
  41861. };
  41862. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41863. runDecimation(task.settings[loop.index], function () {
  41864. loop.executeNext();
  41865. });
  41866. }, function () {
  41867. //execution ended, run the success callback.
  41868. if (task.successCallback) {
  41869. task.successCallback();
  41870. }
  41871. _this.executeNext();
  41872. });
  41873. }
  41874. };
  41875. SimplificationQueue.prototype.getSimplifier = function (task) {
  41876. switch (task.simplificationType) {
  41877. case SimplificationType.QUADRATIC:
  41878. default:
  41879. return new QuadraticErrorSimplification(task.mesh);
  41880. }
  41881. };
  41882. return SimplificationQueue;
  41883. }());
  41884. BABYLON.SimplificationQueue = SimplificationQueue;
  41885. /**
  41886. * The implemented types of simplification.
  41887. * At the moment only Quadratic Error Decimation is implemented.
  41888. */
  41889. (function (SimplificationType) {
  41890. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41891. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41892. var SimplificationType = BABYLON.SimplificationType;
  41893. var DecimationTriangle = (function () {
  41894. function DecimationTriangle(vertices) {
  41895. this.vertices = vertices;
  41896. this.error = new Array(4);
  41897. this.deleted = false;
  41898. this.isDirty = false;
  41899. this.deletePending = false;
  41900. this.borderFactor = 0;
  41901. }
  41902. return DecimationTriangle;
  41903. }());
  41904. BABYLON.DecimationTriangle = DecimationTriangle;
  41905. var DecimationVertex = (function () {
  41906. function DecimationVertex(position, id) {
  41907. this.position = position;
  41908. this.id = id;
  41909. this.isBorder = true;
  41910. this.q = new QuadraticMatrix();
  41911. this.triangleCount = 0;
  41912. this.triangleStart = 0;
  41913. this.originalOffsets = [];
  41914. }
  41915. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41916. this.position.copyFrom(newPosition);
  41917. };
  41918. return DecimationVertex;
  41919. }());
  41920. BABYLON.DecimationVertex = DecimationVertex;
  41921. var QuadraticMatrix = (function () {
  41922. function QuadraticMatrix(data) {
  41923. this.data = new Array(10);
  41924. for (var i = 0; i < 10; ++i) {
  41925. if (data && data[i]) {
  41926. this.data[i] = data[i];
  41927. }
  41928. else {
  41929. this.data[i] = 0;
  41930. }
  41931. }
  41932. }
  41933. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41934. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41935. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41936. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41937. return det;
  41938. };
  41939. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41940. for (var i = 0; i < 10; ++i) {
  41941. this.data[i] += matrix.data[i];
  41942. }
  41943. };
  41944. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41945. for (var i = 0; i < 10; ++i) {
  41946. this.data[i] += data[i];
  41947. }
  41948. };
  41949. QuadraticMatrix.prototype.add = function (matrix) {
  41950. var m = new QuadraticMatrix();
  41951. for (var i = 0; i < 10; ++i) {
  41952. m.data[i] = this.data[i] + matrix.data[i];
  41953. }
  41954. return m;
  41955. };
  41956. QuadraticMatrix.FromData = function (a, b, c, d) {
  41957. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41958. };
  41959. //returning an array to avoid garbage collection
  41960. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41961. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41962. };
  41963. return QuadraticMatrix;
  41964. }());
  41965. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41966. var Reference = (function () {
  41967. function Reference(vertexId, triangleId) {
  41968. this.vertexId = vertexId;
  41969. this.triangleId = triangleId;
  41970. }
  41971. return Reference;
  41972. }());
  41973. BABYLON.Reference = Reference;
  41974. /**
  41975. * An implementation of the Quadratic Error simplification algorithm.
  41976. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41977. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41978. * @author RaananW
  41979. */
  41980. var QuadraticErrorSimplification = (function () {
  41981. function QuadraticErrorSimplification(_mesh) {
  41982. this._mesh = _mesh;
  41983. this.initialized = false;
  41984. this.syncIterations = 5000;
  41985. this.aggressiveness = 7;
  41986. this.decimationIterations = 100;
  41987. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41988. }
  41989. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41990. var _this = this;
  41991. this.initDecimatedMesh();
  41992. //iterating through the submeshes array, one after the other.
  41993. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41994. _this.initWithMesh(loop.index, function () {
  41995. _this.runDecimation(settings, loop.index, function () {
  41996. loop.executeNext();
  41997. });
  41998. }, settings.optimizeMesh);
  41999. }, function () {
  42000. setTimeout(function () {
  42001. successCallback(_this._reconstructedMesh);
  42002. }, 0);
  42003. });
  42004. };
  42005. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42006. var _this = this;
  42007. var gCount = 0;
  42008. triangle.vertices.forEach(function (vertex) {
  42009. var count = 0;
  42010. var vPos = vertex.position;
  42011. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42012. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42013. ++count;
  42014. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42015. ++count;
  42016. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42017. ++count;
  42018. if (count > 1) {
  42019. ++gCount;
  42020. }
  42021. ;
  42022. });
  42023. if (gCount > 1) {
  42024. console.log(triangle, gCount);
  42025. }
  42026. return gCount > 1;
  42027. };
  42028. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42029. var _this = this;
  42030. var targetCount = ~~(this.triangles.length * settings.quality);
  42031. var deletedTriangles = 0;
  42032. var triangleCount = this.triangles.length;
  42033. var iterationFunction = function (iteration, callback) {
  42034. setTimeout(function () {
  42035. if (iteration % 5 === 0) {
  42036. _this.updateMesh(iteration === 0);
  42037. }
  42038. for (var i = 0; i < _this.triangles.length; ++i) {
  42039. _this.triangles[i].isDirty = false;
  42040. }
  42041. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42042. var trianglesIterator = function (i) {
  42043. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42044. var t = _this.triangles[tIdx];
  42045. if (!t)
  42046. return;
  42047. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42048. return;
  42049. }
  42050. for (var j = 0; j < 3; ++j) {
  42051. if (t.error[j] < threshold) {
  42052. var deleted0 = [];
  42053. var deleted1 = [];
  42054. var v0 = t.vertices[j];
  42055. var v1 = t.vertices[(j + 1) % 3];
  42056. if (v0.isBorder || v1.isBorder)
  42057. continue;
  42058. var p = BABYLON.Vector3.Zero();
  42059. var n = BABYLON.Vector3.Zero();
  42060. var uv = BABYLON.Vector2.Zero();
  42061. var color = new BABYLON.Color4(0, 0, 0, 1);
  42062. _this.calculateError(v0, v1, p, n, uv, color);
  42063. var delTr = [];
  42064. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42065. continue;
  42066. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42067. continue;
  42068. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42069. continue;
  42070. var uniqueArray = [];
  42071. delTr.forEach(function (deletedT) {
  42072. if (uniqueArray.indexOf(deletedT) === -1) {
  42073. deletedT.deletePending = true;
  42074. uniqueArray.push(deletedT);
  42075. }
  42076. });
  42077. if (uniqueArray.length % 2 !== 0) {
  42078. continue;
  42079. }
  42080. v0.q = v1.q.add(v0.q);
  42081. v0.updatePosition(p);
  42082. var tStart = _this.references.length;
  42083. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42084. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42085. var tCount = _this.references.length - tStart;
  42086. if (tCount <= v0.triangleCount) {
  42087. if (tCount) {
  42088. for (var c = 0; c < tCount; c++) {
  42089. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42090. }
  42091. }
  42092. }
  42093. else {
  42094. v0.triangleStart = tStart;
  42095. }
  42096. v0.triangleCount = tCount;
  42097. break;
  42098. }
  42099. }
  42100. };
  42101. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42102. }, 0);
  42103. };
  42104. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42105. if (triangleCount - deletedTriangles <= targetCount)
  42106. loop.breakLoop();
  42107. else {
  42108. iterationFunction(loop.index, function () {
  42109. loop.executeNext();
  42110. });
  42111. }
  42112. }, function () {
  42113. setTimeout(function () {
  42114. //reconstruct this part of the mesh
  42115. _this.reconstructMesh(submeshIndex);
  42116. successCallback();
  42117. }, 0);
  42118. });
  42119. };
  42120. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42121. var _this = this;
  42122. this.vertices = [];
  42123. this.triangles = [];
  42124. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42125. var indices = this._mesh.getIndices();
  42126. var submesh = this._mesh.subMeshes[submeshIndex];
  42127. var findInVertices = function (positionToSearch) {
  42128. if (optimizeMesh) {
  42129. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42130. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42131. return _this.vertices[ii];
  42132. }
  42133. }
  42134. }
  42135. return null;
  42136. };
  42137. var vertexReferences = [];
  42138. var vertexInit = function (i) {
  42139. var offset = i + submesh.verticesStart;
  42140. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42141. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42142. vertex.originalOffsets.push(offset);
  42143. if (vertex.id === _this.vertices.length) {
  42144. _this.vertices.push(vertex);
  42145. }
  42146. vertexReferences.push(vertex.id);
  42147. };
  42148. //var totalVertices = mesh.getTotalVertices();
  42149. var totalVertices = submesh.verticesCount;
  42150. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42151. var indicesInit = function (i) {
  42152. var offset = (submesh.indexStart / 3) + i;
  42153. var pos = (offset * 3);
  42154. var i0 = indices[pos + 0];
  42155. var i1 = indices[pos + 1];
  42156. var i2 = indices[pos + 2];
  42157. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42158. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42159. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42160. var triangle = new DecimationTriangle([v0, v1, v2]);
  42161. triangle.originalOffset = pos;
  42162. _this.triangles.push(triangle);
  42163. };
  42164. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42165. _this.init(callback);
  42166. });
  42167. });
  42168. };
  42169. QuadraticErrorSimplification.prototype.init = function (callback) {
  42170. var _this = this;
  42171. var triangleInit1 = function (i) {
  42172. var t = _this.triangles[i];
  42173. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42174. for (var j = 0; j < 3; j++) {
  42175. 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))));
  42176. }
  42177. };
  42178. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42179. var triangleInit2 = function (i) {
  42180. var t = _this.triangles[i];
  42181. for (var j = 0; j < 3; ++j) {
  42182. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42183. }
  42184. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42185. };
  42186. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42187. _this.initialized = true;
  42188. callback();
  42189. });
  42190. });
  42191. };
  42192. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42193. var newTriangles = [];
  42194. var i;
  42195. for (i = 0; i < this.vertices.length; ++i) {
  42196. this.vertices[i].triangleCount = 0;
  42197. }
  42198. var t;
  42199. var j;
  42200. for (i = 0; i < this.triangles.length; ++i) {
  42201. if (!this.triangles[i].deleted) {
  42202. t = this.triangles[i];
  42203. for (j = 0; j < 3; ++j) {
  42204. t.vertices[j].triangleCount = 1;
  42205. }
  42206. newTriangles.push(t);
  42207. }
  42208. }
  42209. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42210. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42211. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42212. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42213. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42214. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42215. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42216. var vertexCount = 0;
  42217. for (i = 0; i < this.vertices.length; ++i) {
  42218. var vertex = this.vertices[i];
  42219. vertex.id = vertexCount;
  42220. if (vertex.triangleCount) {
  42221. vertex.originalOffsets.forEach(function (originalOffset) {
  42222. newPositionData.push(vertex.position.x);
  42223. newPositionData.push(vertex.position.y);
  42224. newPositionData.push(vertex.position.z);
  42225. newNormalData.push(normalData[originalOffset * 3]);
  42226. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42227. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42228. if (uvs && uvs.length) {
  42229. newUVsData.push(uvs[(originalOffset * 2)]);
  42230. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42231. }
  42232. else if (colorsData && colorsData.length) {
  42233. newColorsData.push(colorsData[(originalOffset * 4)]);
  42234. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42235. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42236. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42237. }
  42238. ++vertexCount;
  42239. });
  42240. }
  42241. }
  42242. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42243. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42244. var submeshesArray = this._reconstructedMesh.subMeshes;
  42245. this._reconstructedMesh.subMeshes = [];
  42246. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42247. var originalIndices = this._mesh.getIndices();
  42248. for (i = 0; i < newTriangles.length; ++i) {
  42249. t = newTriangles[i]; //now get the new referencing point for each vertex
  42250. [0, 1, 2].forEach(function (idx) {
  42251. var id = originalIndices[t.originalOffset + idx];
  42252. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42253. if (offset < 0)
  42254. offset = 0;
  42255. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42256. });
  42257. }
  42258. //overwriting the old vertex buffers and indices.
  42259. this._reconstructedMesh.setIndices(newIndicesArray);
  42260. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42261. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42262. if (newUVsData.length > 0)
  42263. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42264. if (newColorsData.length > 0)
  42265. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42266. //create submesh
  42267. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42268. if (submeshIndex > 0) {
  42269. this._reconstructedMesh.subMeshes = [];
  42270. submeshesArray.forEach(function (submesh) {
  42271. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42272. });
  42273. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42274. }
  42275. };
  42276. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42277. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42278. this._reconstructedMesh.material = this._mesh.material;
  42279. this._reconstructedMesh.parent = this._mesh.parent;
  42280. this._reconstructedMesh.isVisible = false;
  42281. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42282. };
  42283. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42284. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42285. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42286. if (t.deleted)
  42287. continue;
  42288. var s = this.references[vertex1.triangleStart + i].vertexId;
  42289. var v1 = t.vertices[(s + 1) % 3];
  42290. var v2 = t.vertices[(s + 2) % 3];
  42291. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42292. deletedArray[i] = true;
  42293. delTr.push(t);
  42294. continue;
  42295. }
  42296. var d1 = v1.position.subtract(point);
  42297. d1 = d1.normalize();
  42298. var d2 = v2.position.subtract(point);
  42299. d2 = d2.normalize();
  42300. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42301. return true;
  42302. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42303. deletedArray[i] = false;
  42304. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42305. return true;
  42306. }
  42307. return false;
  42308. };
  42309. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42310. var newDeleted = deletedTriangles;
  42311. for (var i = 0; i < vertex.triangleCount; ++i) {
  42312. var ref = this.references[vertex.triangleStart + i];
  42313. var t = this.triangles[ref.triangleId];
  42314. if (t.deleted)
  42315. continue;
  42316. if (deletedArray[i] && t.deletePending) {
  42317. t.deleted = true;
  42318. newDeleted++;
  42319. continue;
  42320. }
  42321. t.vertices[ref.vertexId] = origVertex;
  42322. t.isDirty = true;
  42323. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42324. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42325. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42326. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42327. this.references.push(ref);
  42328. }
  42329. return newDeleted;
  42330. };
  42331. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42332. for (var i = 0; i < this.vertices.length; ++i) {
  42333. var vCount = [];
  42334. var vId = [];
  42335. var v = this.vertices[i];
  42336. var j;
  42337. for (j = 0; j < v.triangleCount; ++j) {
  42338. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42339. for (var ii = 0; ii < 3; ii++) {
  42340. var ofs = 0;
  42341. var vv = triangle.vertices[ii];
  42342. while (ofs < vCount.length) {
  42343. if (vId[ofs] === vv.id)
  42344. break;
  42345. ++ofs;
  42346. }
  42347. if (ofs === vCount.length) {
  42348. vCount.push(1);
  42349. vId.push(vv.id);
  42350. }
  42351. else {
  42352. vCount[ofs]++;
  42353. }
  42354. }
  42355. }
  42356. for (j = 0; j < vCount.length; ++j) {
  42357. if (vCount[j] === 1) {
  42358. this.vertices[vId[j]].isBorder = true;
  42359. }
  42360. else {
  42361. this.vertices[vId[j]].isBorder = false;
  42362. }
  42363. }
  42364. }
  42365. };
  42366. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42367. if (identifyBorders === void 0) { identifyBorders = false; }
  42368. var i;
  42369. if (!identifyBorders) {
  42370. var newTrianglesVector = [];
  42371. for (i = 0; i < this.triangles.length; ++i) {
  42372. if (!this.triangles[i].deleted) {
  42373. newTrianglesVector.push(this.triangles[i]);
  42374. }
  42375. }
  42376. this.triangles = newTrianglesVector;
  42377. }
  42378. for (i = 0; i < this.vertices.length; ++i) {
  42379. this.vertices[i].triangleCount = 0;
  42380. this.vertices[i].triangleStart = 0;
  42381. }
  42382. var t;
  42383. var j;
  42384. var v;
  42385. for (i = 0; i < this.triangles.length; ++i) {
  42386. t = this.triangles[i];
  42387. for (j = 0; j < 3; ++j) {
  42388. v = t.vertices[j];
  42389. v.triangleCount++;
  42390. }
  42391. }
  42392. var tStart = 0;
  42393. for (i = 0; i < this.vertices.length; ++i) {
  42394. this.vertices[i].triangleStart = tStart;
  42395. tStart += this.vertices[i].triangleCount;
  42396. this.vertices[i].triangleCount = 0;
  42397. }
  42398. var newReferences = new Array(this.triangles.length * 3);
  42399. for (i = 0; i < this.triangles.length; ++i) {
  42400. t = this.triangles[i];
  42401. for (j = 0; j < 3; ++j) {
  42402. v = t.vertices[j];
  42403. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42404. v.triangleCount++;
  42405. }
  42406. }
  42407. this.references = newReferences;
  42408. if (identifyBorders) {
  42409. this.identifyBorder();
  42410. }
  42411. };
  42412. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42413. var x = point.x;
  42414. var y = point.y;
  42415. var z = point.z;
  42416. 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
  42417. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42418. };
  42419. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42420. var q = vertex1.q.add(vertex2.q);
  42421. var border = vertex1.isBorder && vertex2.isBorder;
  42422. var error = 0;
  42423. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42424. if (qDet !== 0 && !border) {
  42425. if (!pointResult) {
  42426. pointResult = BABYLON.Vector3.Zero();
  42427. }
  42428. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42429. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42430. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42431. error = this.vertexError(q, pointResult);
  42432. }
  42433. else {
  42434. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42435. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42436. var error1 = this.vertexError(q, vertex1.position);
  42437. var error2 = this.vertexError(q, vertex2.position);
  42438. var error3 = this.vertexError(q, p3);
  42439. error = Math.min(error1, error2, error3);
  42440. if (error === error1) {
  42441. if (pointResult) {
  42442. pointResult.copyFrom(vertex1.position);
  42443. }
  42444. }
  42445. else if (error === error2) {
  42446. if (pointResult) {
  42447. pointResult.copyFrom(vertex2.position);
  42448. }
  42449. }
  42450. else {
  42451. if (pointResult) {
  42452. pointResult.copyFrom(p3);
  42453. }
  42454. }
  42455. }
  42456. return error;
  42457. };
  42458. return QuadraticErrorSimplification;
  42459. }());
  42460. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42461. })(BABYLON || (BABYLON = {}));
  42462. //# sourceMappingURL=babylon.meshSimplification.js.map
  42463. var BABYLON;
  42464. (function (BABYLON) {
  42465. var serializedGeometries = [];
  42466. var serializeGeometry = function (geometry, serializationGeometries) {
  42467. if (serializedGeometries[geometry.id]) {
  42468. return;
  42469. }
  42470. if (geometry.doNotSerialize) {
  42471. return;
  42472. }
  42473. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42474. serializationGeometries.boxes.push(geometry.serialize());
  42475. }
  42476. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42477. serializationGeometries.spheres.push(geometry.serialize());
  42478. }
  42479. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42480. serializationGeometries.cylinders.push(geometry.serialize());
  42481. }
  42482. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42483. serializationGeometries.toruses.push(geometry.serialize());
  42484. }
  42485. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42486. serializationGeometries.grounds.push(geometry.serialize());
  42487. }
  42488. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42489. serializationGeometries.planes.push(geometry.serialize());
  42490. }
  42491. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42492. serializationGeometries.torusKnots.push(geometry.serialize());
  42493. }
  42494. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42495. throw new Error("Unknown primitive type");
  42496. }
  42497. else {
  42498. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42499. }
  42500. serializedGeometries[geometry.id] = true;
  42501. };
  42502. var serializeMesh = function (mesh, serializationScene) {
  42503. var serializationObject = {};
  42504. serializationObject.name = mesh.name;
  42505. serializationObject.id = mesh.id;
  42506. if (BABYLON.Tags.HasTags(mesh)) {
  42507. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42508. }
  42509. serializationObject.position = mesh.position.asArray();
  42510. if (mesh.rotationQuaternion) {
  42511. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42512. }
  42513. else if (mesh.rotation) {
  42514. serializationObject.rotation = mesh.rotation.asArray();
  42515. }
  42516. serializationObject.scaling = mesh.scaling.asArray();
  42517. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42518. serializationObject.isEnabled = mesh.isEnabled();
  42519. serializationObject.isVisible = mesh.isVisible;
  42520. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42521. serializationObject.pickable = mesh.isPickable;
  42522. serializationObject.receiveShadows = mesh.receiveShadows;
  42523. serializationObject.billboardMode = mesh.billboardMode;
  42524. serializationObject.visibility = mesh.visibility;
  42525. serializationObject.checkCollisions = mesh.checkCollisions;
  42526. serializationObject.isBlocker = mesh.isBlocker;
  42527. // Parent
  42528. if (mesh.parent) {
  42529. serializationObject.parentId = mesh.parent.id;
  42530. }
  42531. // Geometry
  42532. var geometry = mesh._geometry;
  42533. if (geometry) {
  42534. var geometryId = geometry.id;
  42535. serializationObject.geometryId = geometryId;
  42536. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42537. // 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
  42538. serializeGeometry(geometry, serializationScene.geometries);
  42539. }
  42540. // SubMeshes
  42541. serializationObject.subMeshes = [];
  42542. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42543. var subMesh = mesh.subMeshes[subIndex];
  42544. serializationObject.subMeshes.push({
  42545. materialIndex: subMesh.materialIndex,
  42546. verticesStart: subMesh.verticesStart,
  42547. verticesCount: subMesh.verticesCount,
  42548. indexStart: subMesh.indexStart,
  42549. indexCount: subMesh.indexCount
  42550. });
  42551. }
  42552. }
  42553. // Material
  42554. if (mesh.material) {
  42555. serializationObject.materialId = mesh.material.id;
  42556. }
  42557. else {
  42558. mesh.material = null;
  42559. }
  42560. // Skeleton
  42561. if (mesh.skeleton) {
  42562. serializationObject.skeletonId = mesh.skeleton.id;
  42563. }
  42564. // Physics
  42565. //TODO implement correct serialization for physics impostors.
  42566. if (mesh.getPhysicsImpostor()) {
  42567. serializationObject.physicsMass = mesh.getPhysicsMass();
  42568. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42569. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42570. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42571. }
  42572. // Metadata
  42573. if (mesh.metadata) {
  42574. serializationObject.metadata = mesh.metadata;
  42575. }
  42576. // Instances
  42577. serializationObject.instances = [];
  42578. for (var index = 0; index < mesh.instances.length; index++) {
  42579. var instance = mesh.instances[index];
  42580. var serializationInstance = {
  42581. name: instance.name,
  42582. position: instance.position.asArray(),
  42583. scaling: instance.scaling.asArray()
  42584. };
  42585. if (instance.rotationQuaternion) {
  42586. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42587. }
  42588. else if (instance.rotation) {
  42589. serializationInstance.rotation = instance.rotation.asArray();
  42590. }
  42591. serializationObject.instances.push(serializationInstance);
  42592. // Animations
  42593. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42594. serializationInstance.ranges = instance.serializeAnimationRanges();
  42595. }
  42596. // Animations
  42597. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42598. serializationObject.ranges = mesh.serializeAnimationRanges();
  42599. // Layer mask
  42600. serializationObject.layerMask = mesh.layerMask;
  42601. // Alpha
  42602. serializationObject.alphaIndex = mesh.alphaIndex;
  42603. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42604. // Overlay
  42605. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42606. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42607. serializationObject.renderOverlay = mesh.renderOverlay;
  42608. // Fog
  42609. serializationObject.applyFog = mesh.applyFog;
  42610. // Action Manager
  42611. if (mesh.actionManager) {
  42612. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42613. }
  42614. return serializationObject;
  42615. };
  42616. var finalizeSingleMesh = function (mesh, serializationObject) {
  42617. //only works if the mesh is already loaded
  42618. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42619. //serialize material
  42620. if (mesh.material) {
  42621. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42622. serializationObject.materials = serializationObject.materials || [];
  42623. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42624. serializationObject.materials.push(mesh.material.serialize());
  42625. }
  42626. }
  42627. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42628. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42629. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42630. serializationObject.multiMaterials.push(mesh.material.serialize());
  42631. }
  42632. }
  42633. }
  42634. //serialize geometry
  42635. var geometry = mesh._geometry;
  42636. if (geometry) {
  42637. if (!serializationObject.geometries) {
  42638. serializationObject.geometries = {};
  42639. serializationObject.geometries.boxes = [];
  42640. serializationObject.geometries.spheres = [];
  42641. serializationObject.geometries.cylinders = [];
  42642. serializationObject.geometries.toruses = [];
  42643. serializationObject.geometries.grounds = [];
  42644. serializationObject.geometries.planes = [];
  42645. serializationObject.geometries.torusKnots = [];
  42646. serializationObject.geometries.vertexData = [];
  42647. }
  42648. serializeGeometry(geometry, serializationObject.geometries);
  42649. }
  42650. // Skeletons
  42651. if (mesh.skeleton) {
  42652. serializationObject.skeletons = serializationObject.skeletons || [];
  42653. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42654. }
  42655. //serialize the actual mesh
  42656. serializationObject.meshes = serializationObject.meshes || [];
  42657. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42658. }
  42659. };
  42660. var SceneSerializer = (function () {
  42661. function SceneSerializer() {
  42662. }
  42663. SceneSerializer.ClearCache = function () {
  42664. serializedGeometries = [];
  42665. };
  42666. SceneSerializer.Serialize = function (scene) {
  42667. var serializationObject = {};
  42668. // Scene
  42669. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42670. serializationObject.autoClear = scene.autoClear;
  42671. serializationObject.clearColor = scene.clearColor.asArray();
  42672. serializationObject.ambientColor = scene.ambientColor.asArray();
  42673. serializationObject.gravity = scene.gravity.asArray();
  42674. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42675. serializationObject.workerCollisions = scene.workerCollisions;
  42676. // Fog
  42677. if (scene.fogMode && scene.fogMode !== 0) {
  42678. serializationObject.fogMode = scene.fogMode;
  42679. serializationObject.fogColor = scene.fogColor.asArray();
  42680. serializationObject.fogStart = scene.fogStart;
  42681. serializationObject.fogEnd = scene.fogEnd;
  42682. serializationObject.fogDensity = scene.fogDensity;
  42683. }
  42684. //Physics
  42685. if (scene.isPhysicsEnabled()) {
  42686. serializationObject.physicsEnabled = true;
  42687. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42688. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42689. }
  42690. // Metadata
  42691. if (scene.metadata) {
  42692. serializationObject.metadata = scene.metadata;
  42693. }
  42694. // Lights
  42695. serializationObject.lights = [];
  42696. var index;
  42697. var light;
  42698. for (index = 0; index < scene.lights.length; index++) {
  42699. light = scene.lights[index];
  42700. if (!light.doNotSerialize) {
  42701. serializationObject.lights.push(light.serialize());
  42702. }
  42703. }
  42704. // Cameras
  42705. serializationObject.cameras = [];
  42706. for (index = 0; index < scene.cameras.length; index++) {
  42707. var camera = scene.cameras[index];
  42708. if (!camera.doNotSerialize) {
  42709. serializationObject.cameras.push(camera.serialize());
  42710. }
  42711. }
  42712. if (scene.activeCamera) {
  42713. serializationObject.activeCameraID = scene.activeCamera.id;
  42714. }
  42715. // Animations
  42716. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42717. // Materials
  42718. serializationObject.materials = [];
  42719. serializationObject.multiMaterials = [];
  42720. var material;
  42721. for (index = 0; index < scene.materials.length; index++) {
  42722. material = scene.materials[index];
  42723. if (!material.doNotSerialize) {
  42724. serializationObject.materials.push(material.serialize());
  42725. }
  42726. }
  42727. // MultiMaterials
  42728. serializationObject.multiMaterials = [];
  42729. for (index = 0; index < scene.multiMaterials.length; index++) {
  42730. var multiMaterial = scene.multiMaterials[index];
  42731. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42732. }
  42733. // Skeletons
  42734. serializationObject.skeletons = [];
  42735. for (index = 0; index < scene.skeletons.length; index++) {
  42736. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42737. }
  42738. // Geometries
  42739. serializationObject.geometries = {};
  42740. serializationObject.geometries.boxes = [];
  42741. serializationObject.geometries.spheres = [];
  42742. serializationObject.geometries.cylinders = [];
  42743. serializationObject.geometries.toruses = [];
  42744. serializationObject.geometries.grounds = [];
  42745. serializationObject.geometries.planes = [];
  42746. serializationObject.geometries.torusKnots = [];
  42747. serializationObject.geometries.vertexData = [];
  42748. serializedGeometries = [];
  42749. var geometries = scene.getGeometries();
  42750. for (index = 0; index < geometries.length; index++) {
  42751. var geometry = geometries[index];
  42752. if (geometry.isReady()) {
  42753. serializeGeometry(geometry, serializationObject.geometries);
  42754. }
  42755. }
  42756. // Meshes
  42757. serializationObject.meshes = [];
  42758. for (index = 0; index < scene.meshes.length; index++) {
  42759. var abstractMesh = scene.meshes[index];
  42760. if (abstractMesh instanceof BABYLON.Mesh) {
  42761. var mesh = abstractMesh;
  42762. if (!mesh.doNotSerialize) {
  42763. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42764. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42765. }
  42766. }
  42767. }
  42768. }
  42769. // Particles Systems
  42770. serializationObject.particleSystems = [];
  42771. for (index = 0; index < scene.particleSystems.length; index++) {
  42772. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42773. }
  42774. // Lens flares
  42775. serializationObject.lensFlareSystems = [];
  42776. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42777. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42778. }
  42779. // Shadows
  42780. serializationObject.shadowGenerators = [];
  42781. for (index = 0; index < scene.lights.length; index++) {
  42782. light = scene.lights[index];
  42783. var shadowGenerator = light.getShadowGenerator();
  42784. // Only support serialization for official generator so far.
  42785. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42786. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42787. }
  42788. }
  42789. // Action Manager
  42790. if (scene.actionManager) {
  42791. serializationObject.actions = scene.actionManager.serialize("scene");
  42792. }
  42793. // Audio
  42794. serializationObject.sounds = [];
  42795. for (index = 0; index < scene.soundTracks.length; index++) {
  42796. var soundtrack = scene.soundTracks[index];
  42797. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42798. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42799. }
  42800. }
  42801. return serializationObject;
  42802. };
  42803. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42804. if (withParents === void 0) { withParents = false; }
  42805. if (withChildren === void 0) { withChildren = false; }
  42806. var serializationObject = {};
  42807. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42808. if (withParents || withChildren) {
  42809. //deliberate for loop! not for each, appended should be processed as well.
  42810. for (var i = 0; i < toSerialize.length; ++i) {
  42811. if (withChildren) {
  42812. toSerialize[i].getDescendants().forEach(function (node) {
  42813. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42814. toSerialize.push(node);
  42815. }
  42816. });
  42817. }
  42818. //make sure the array doesn't contain the object already
  42819. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42820. toSerialize.push(toSerialize[i].parent);
  42821. }
  42822. }
  42823. }
  42824. toSerialize.forEach(function (mesh) {
  42825. finalizeSingleMesh(mesh, serializationObject);
  42826. });
  42827. return serializationObject;
  42828. };
  42829. return SceneSerializer;
  42830. }());
  42831. BABYLON.SceneSerializer = SceneSerializer;
  42832. })(BABYLON || (BABYLON = {}));
  42833. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42834. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42835. // Huge respect for a such great lib.
  42836. // Earcut license:
  42837. // Copyright (c) 2016, Mapbox
  42838. //
  42839. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42840. // with or without fee is hereby granted, provided that the above copyright notice
  42841. // and this permission notice appear in all copies.
  42842. //
  42843. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42844. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42845. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42846. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42847. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42848. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42849. // THIS SOFTWARE.
  42850. var Earcut;
  42851. (function (Earcut) {
  42852. /**
  42853. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42854. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42855. * @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).
  42856. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42857. */
  42858. function earcut(data, holeIndices, dim) {
  42859. dim = dim || 2;
  42860. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42861. if (!outerNode)
  42862. return triangles;
  42863. var minX, minY, maxX, maxY, x, y, size;
  42864. if (hasHoles)
  42865. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42866. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42867. if (data.length > 80 * dim) {
  42868. minX = maxX = data[0];
  42869. minY = maxY = data[1];
  42870. for (var i = dim; i < outerLen; i += dim) {
  42871. x = data[i];
  42872. y = data[i + 1];
  42873. if (x < minX)
  42874. minX = x;
  42875. if (y < minY)
  42876. minY = y;
  42877. if (x > maxX)
  42878. maxX = x;
  42879. if (y > maxY)
  42880. maxY = y;
  42881. }
  42882. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42883. size = Math.max(maxX - minX, maxY - minY);
  42884. }
  42885. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42886. return triangles;
  42887. }
  42888. Earcut.earcut = earcut;
  42889. // create a circular doubly linked list from polygon points in the specified winding order
  42890. function linkedList(data, start, end, dim, clockwise) {
  42891. var i, last;
  42892. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42893. for (i = start; i < end; i += dim)
  42894. last = insertNode(i, data[i], data[i + 1], last);
  42895. }
  42896. else {
  42897. for (i = end - dim; i >= start; i -= dim)
  42898. last = insertNode(i, data[i], data[i + 1], last);
  42899. }
  42900. if (last && equals(last, last.next)) {
  42901. removeNode(last);
  42902. last = last.next;
  42903. }
  42904. return last;
  42905. }
  42906. // eliminate colinear or duplicate points
  42907. function filterPoints(start, end) {
  42908. if (!start)
  42909. return start;
  42910. if (!end)
  42911. end = start;
  42912. var p = start, again;
  42913. do {
  42914. again = false;
  42915. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42916. removeNode(p);
  42917. p = end = p.prev;
  42918. if (p === p.next)
  42919. return null;
  42920. again = true;
  42921. }
  42922. else {
  42923. p = p.next;
  42924. }
  42925. } while (again || p !== end);
  42926. return end;
  42927. }
  42928. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42929. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42930. if (!ear)
  42931. return;
  42932. // interlink polygon nodes in z-order
  42933. if (!pass && size)
  42934. indexCurve(ear, minX, minY, size);
  42935. var stop = ear, prev, next;
  42936. // iterate through ears, slicing them one by one
  42937. while (ear.prev !== ear.next) {
  42938. prev = ear.prev;
  42939. next = ear.next;
  42940. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42941. // cut off the triangle
  42942. triangles.push(prev.i / dim);
  42943. triangles.push(ear.i / dim);
  42944. triangles.push(next.i / dim);
  42945. removeNode(ear);
  42946. // skipping the next vertice leads to less sliver triangles
  42947. ear = next.next;
  42948. stop = next.next;
  42949. continue;
  42950. }
  42951. ear = next;
  42952. // if we looped through the whole remaining polygon and can't find any more ears
  42953. if (ear === stop) {
  42954. // try filtering points and slicing again
  42955. if (!pass) {
  42956. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  42957. }
  42958. else if (pass === 1) {
  42959. ear = cureLocalIntersections(ear, triangles, dim);
  42960. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  42961. }
  42962. else if (pass === 2) {
  42963. splitEarcut(ear, triangles, dim, minX, minY, size);
  42964. }
  42965. break;
  42966. }
  42967. }
  42968. }
  42969. // check whether a polygon node forms a valid ear with adjacent nodes
  42970. function isEar(ear) {
  42971. var a = ear.prev, b = ear, c = ear.next;
  42972. if (area(a, b, c) >= 0)
  42973. return false; // reflex, can't be an ear
  42974. // now make sure we don't have other points inside the potential ear
  42975. var p = ear.next.next;
  42976. while (p !== ear.prev) {
  42977. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42978. area(p.prev, p, p.next) >= 0)
  42979. return false;
  42980. p = p.next;
  42981. }
  42982. return true;
  42983. }
  42984. function isEarHashed(ear, minX, minY, size) {
  42985. var a = ear.prev, b = ear, c = ear.next;
  42986. if (area(a, b, c) >= 0)
  42987. return false; // reflex, can't be an ear
  42988. // triangle bbox; min & max are calculated like this for speed
  42989. 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);
  42990. // z-order range for the current triangle bbox;
  42991. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  42992. // first look for points inside the triangle in increasing z-order
  42993. var p = ear.nextZ;
  42994. while (p && p.z <= maxZ) {
  42995. if (p !== ear.prev &&
  42996. p !== ear.next &&
  42997. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42998. area(p.prev, p, p.next) >= 0)
  42999. return false;
  43000. p = p.nextZ;
  43001. }
  43002. // then look for points in decreasing z-order
  43003. p = ear.prevZ;
  43004. while (p && p.z >= minZ) {
  43005. if (p !== ear.prev &&
  43006. p !== ear.next &&
  43007. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43008. area(p.prev, p, p.next) >= 0)
  43009. return false;
  43010. p = p.prevZ;
  43011. }
  43012. return true;
  43013. }
  43014. // go through all polygon nodes and cure small local self-intersections
  43015. function cureLocalIntersections(start, triangles, dim) {
  43016. var p = start;
  43017. do {
  43018. var a = p.prev, b = p.next.next;
  43019. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43020. triangles.push(a.i / dim);
  43021. triangles.push(p.i / dim);
  43022. triangles.push(b.i / dim);
  43023. // remove two nodes involved
  43024. removeNode(p);
  43025. removeNode(p.next);
  43026. p = start = b;
  43027. }
  43028. p = p.next;
  43029. } while (p !== start);
  43030. return p;
  43031. }
  43032. // try splitting polygon into two and triangulate them independently
  43033. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43034. // look for a valid diagonal that divides the polygon into two
  43035. var a = start;
  43036. do {
  43037. var b = a.next.next;
  43038. while (b !== a.prev) {
  43039. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43040. // split the polygon in two by the diagonal
  43041. var c = splitPolygon(a, b);
  43042. // filter colinear points around the cuts
  43043. a = filterPoints(a, a.next);
  43044. c = filterPoints(c, c.next);
  43045. // run earcut on each half
  43046. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43047. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43048. return;
  43049. }
  43050. b = b.next;
  43051. }
  43052. a = a.next;
  43053. } while (a !== start);
  43054. }
  43055. // link every hole into the outer loop, producing a single-ring polygon without holes
  43056. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43057. var queue = [], i, len, start, end, list;
  43058. for (i = 0, len = holeIndices.length; i < len; i++) {
  43059. start = holeIndices[i] * dim;
  43060. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43061. list = linkedList(data, start, end, dim, false);
  43062. if (list === list.next)
  43063. list.steiner = true;
  43064. queue.push(getLeftmost(list));
  43065. }
  43066. queue.sort(compareX);
  43067. // process holes from left to right
  43068. for (i = 0; i < queue.length; i++) {
  43069. eliminateHole(queue[i], outerNode);
  43070. outerNode = filterPoints(outerNode, outerNode.next);
  43071. }
  43072. return outerNode;
  43073. }
  43074. function compareX(a, b) {
  43075. return a.x - b.x;
  43076. }
  43077. // find a bridge between vertices that connects hole with an outer ring and and link it
  43078. function eliminateHole(hole, outerNode) {
  43079. outerNode = findHoleBridge(hole, outerNode);
  43080. if (outerNode) {
  43081. var b = splitPolygon(outerNode, hole);
  43082. filterPoints(b, b.next);
  43083. }
  43084. }
  43085. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43086. function findHoleBridge(hole, outerNode) {
  43087. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43088. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43089. // segment's endpoint with lesser x will be potential connection point
  43090. do {
  43091. if (hy <= p.y && hy >= p.next.y) {
  43092. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43093. if (x <= hx && x > qx) {
  43094. qx = x;
  43095. if (x === hx) {
  43096. if (hy === p.y)
  43097. return p;
  43098. if (hy === p.next.y)
  43099. return p.next;
  43100. }
  43101. m = p.x < p.next.x ? p : p.next;
  43102. }
  43103. }
  43104. p = p.next;
  43105. } while (p !== outerNode);
  43106. if (!m)
  43107. return null;
  43108. if (hx === qx)
  43109. return m.prev; // hole touches outer segment; pick lower endpoint
  43110. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43111. // if there are no points found, we have a valid connection;
  43112. // otherwise choose the point of the minimum angle with the ray as connection point
  43113. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43114. p = m.next;
  43115. while (p !== stop) {
  43116. if (hx >= p.x &&
  43117. p.x >= mx &&
  43118. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43119. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43120. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43121. m = p;
  43122. tanMin = tan;
  43123. }
  43124. }
  43125. p = p.next;
  43126. }
  43127. return m;
  43128. }
  43129. // interlink polygon nodes in z-order
  43130. function indexCurve(start, minX, minY, size) {
  43131. var p = start;
  43132. do {
  43133. if (p.z === null)
  43134. p.z = zOrder(p.x, p.y, minX, minY, size);
  43135. p.prevZ = p.prev;
  43136. p.nextZ = p.next;
  43137. p = p.next;
  43138. } while (p !== start);
  43139. p.prevZ.nextZ = null;
  43140. p.prevZ = null;
  43141. sortLinked(p);
  43142. }
  43143. // Simon Tatham's linked list merge sort algorithm
  43144. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43145. function sortLinked(list) {
  43146. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43147. do {
  43148. p = list;
  43149. list = null;
  43150. tail = null;
  43151. numMerges = 0;
  43152. while (p) {
  43153. numMerges++;
  43154. q = p;
  43155. pSize = 0;
  43156. for (i = 0; i < inSize; i++) {
  43157. pSize++;
  43158. q = q.nextZ;
  43159. if (!q)
  43160. break;
  43161. }
  43162. qSize = inSize;
  43163. while (pSize > 0 || (qSize > 0 && q)) {
  43164. if (pSize === 0) {
  43165. e = q;
  43166. q = q.nextZ;
  43167. qSize--;
  43168. }
  43169. else if (qSize === 0 || !q) {
  43170. e = p;
  43171. p = p.nextZ;
  43172. pSize--;
  43173. }
  43174. else if (p.z <= q.z) {
  43175. e = p;
  43176. p = p.nextZ;
  43177. pSize--;
  43178. }
  43179. else {
  43180. e = q;
  43181. q = q.nextZ;
  43182. qSize--;
  43183. }
  43184. if (tail)
  43185. tail.nextZ = e;
  43186. else
  43187. list = e;
  43188. e.prevZ = tail;
  43189. tail = e;
  43190. }
  43191. p = q;
  43192. }
  43193. tail.nextZ = null;
  43194. inSize *= 2;
  43195. } while (numMerges > 1);
  43196. return list;
  43197. }
  43198. // z-order of a point given coords and size of the data bounding box
  43199. function zOrder(x, y, minX, minY, size) {
  43200. // coords are transformed into non-negative 15-bit integer range
  43201. x = 32767 * (x - minX) / size;
  43202. y = 32767 * (y - minY) / size;
  43203. x = (x | (x << 8)) & 0x00FF00FF;
  43204. x = (x | (x << 4)) & 0x0F0F0F0F;
  43205. x = (x | (x << 2)) & 0x33333333;
  43206. x = (x | (x << 1)) & 0x55555555;
  43207. y = (y | (y << 8)) & 0x00FF00FF;
  43208. y = (y | (y << 4)) & 0x0F0F0F0F;
  43209. y = (y | (y << 2)) & 0x33333333;
  43210. y = (y | (y << 1)) & 0x55555555;
  43211. return x | (y << 1);
  43212. }
  43213. // find the leftmost node of a polygon ring
  43214. function getLeftmost(start) {
  43215. var p = start, leftmost = start;
  43216. do {
  43217. if (p.x < leftmost.x)
  43218. leftmost = p;
  43219. p = p.next;
  43220. } while (p !== start);
  43221. return leftmost;
  43222. }
  43223. // check if a point lies within a convex triangle
  43224. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43225. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43226. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43227. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43228. }
  43229. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43230. function isValidDiagonal(a, b) {
  43231. return a.next.i !== b.i &&
  43232. a.prev.i !== b.i &&
  43233. !intersectsPolygon(a, b) &&
  43234. locallyInside(a, b) &&
  43235. locallyInside(b, a) &&
  43236. middleInside(a, b);
  43237. }
  43238. // signed area of a triangle
  43239. function area(p, q, r) {
  43240. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43241. }
  43242. // check if two points are equal
  43243. function equals(p1, p2) {
  43244. return p1.x === p2.x && p1.y === p2.y;
  43245. }
  43246. // check if two segments intersect
  43247. function intersects(p1, q1, p2, q2) {
  43248. if ((equals(p1, q1) && equals(p2, q2)) ||
  43249. (equals(p1, q2) && equals(p2, q1)))
  43250. return true;
  43251. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43252. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43253. }
  43254. // check if a polygon diagonal intersects any polygon segments
  43255. function intersectsPolygon(a, b) {
  43256. var p = a;
  43257. do {
  43258. if (p.i !== a.i &&
  43259. p.next.i !== a.i &&
  43260. p.i !== b.i &&
  43261. p.next.i !== b.i &&
  43262. intersects(p, p.next, a, b))
  43263. return true;
  43264. p = p.next;
  43265. } while (p !== a);
  43266. return false;
  43267. }
  43268. // check if a polygon diagonal is locally inside the polygon
  43269. function locallyInside(a, b) {
  43270. return area(a.prev, a, a.next) < 0
  43271. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43272. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43273. }
  43274. // check if the middle point of a polygon diagonal is inside the polygon
  43275. function middleInside(a, b) {
  43276. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43277. do {
  43278. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43279. inside = !inside;
  43280. p = p.next;
  43281. } while (p !== a);
  43282. return inside;
  43283. }
  43284. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43285. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43286. function splitPolygon(a, b) {
  43287. 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;
  43288. a.next = b;
  43289. b.prev = a;
  43290. a2.next = an;
  43291. an.prev = a2;
  43292. b2.next = a2;
  43293. a2.prev = b2;
  43294. bp.next = b2;
  43295. b2.prev = bp;
  43296. return b2;
  43297. }
  43298. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43299. function insertNode(i, x, y, last) {
  43300. var p = new Node(i, x, y);
  43301. if (!last) {
  43302. p.prev = p;
  43303. p.next = p;
  43304. }
  43305. else {
  43306. p.next = last.next;
  43307. p.prev = last;
  43308. last.next.prev = p;
  43309. last.next = p;
  43310. }
  43311. return p;
  43312. }
  43313. function removeNode(p) {
  43314. p.next.prev = p.prev;
  43315. p.prev.next = p.next;
  43316. if (p.prevZ)
  43317. p.prevZ.nextZ = p.nextZ;
  43318. if (p.nextZ)
  43319. p.nextZ.prevZ = p.prevZ;
  43320. }
  43321. function Node(i, x, y) {
  43322. // vertice index in coordinates array
  43323. this.i = i;
  43324. // vertex coordinates
  43325. this.x = x;
  43326. this.y = y;
  43327. // previous and next vertice nodes in a polygon ring
  43328. this.prev = null;
  43329. this.next = null;
  43330. // z-order curve value
  43331. this.z = null;
  43332. // previous and next nodes in z-order
  43333. this.prevZ = null;
  43334. this.nextZ = null;
  43335. // indicates whether this is a steiner point
  43336. this.steiner = false;
  43337. }
  43338. /**
  43339. * return a percentage difference between the polygon area and its triangulation area;
  43340. * used to verify correctness of triangulation
  43341. */
  43342. function deviation(data, holeIndices, dim, triangles) {
  43343. var hasHoles = holeIndices && holeIndices.length;
  43344. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43345. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43346. if (hasHoles) {
  43347. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43348. var start = holeIndices[i] * dim;
  43349. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43350. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43351. }
  43352. }
  43353. var trianglesArea = 0;
  43354. for (i = 0; i < triangles.length; i += 3) {
  43355. var a = triangles[i] * dim;
  43356. var b = triangles[i + 1] * dim;
  43357. var c = triangles[i + 2] * dim;
  43358. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43359. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43360. }
  43361. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43362. }
  43363. Earcut.deviation = deviation;
  43364. ;
  43365. function signedArea(data, start, end, dim) {
  43366. var sum = 0;
  43367. for (var i = start, j = end - dim; i < end; i += dim) {
  43368. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43369. j = i;
  43370. }
  43371. return sum;
  43372. }
  43373. /**
  43374. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43375. */
  43376. function flatten(data) {
  43377. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43378. for (var i = 0; i < data.length; i++) {
  43379. for (var j = 0; j < data[i].length; j++) {
  43380. for (var d = 0; d < dim; d++)
  43381. result.vertices.push(data[i][j][d]);
  43382. }
  43383. if (i > 0) {
  43384. holeIndex += data[i - 1].length;
  43385. result.holes.push(holeIndex);
  43386. }
  43387. }
  43388. return result;
  43389. }
  43390. Earcut.flatten = flatten;
  43391. ;
  43392. })(Earcut || (Earcut = {}));
  43393. //# sourceMappingURL=babylon.earcut.js.map
  43394. var BABYLON;
  43395. (function (BABYLON) {
  43396. // Unique ID when we import meshes from Babylon to CSG
  43397. var currentCSGMeshId = 0;
  43398. // # class Vertex
  43399. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43400. // one to provide additional features like texture coordinates and vertex
  43401. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43402. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43403. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43404. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43405. // is not used anywhere else.
  43406. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43407. var Vertex = (function () {
  43408. function Vertex(pos, normal, uv) {
  43409. this.pos = pos;
  43410. this.normal = normal;
  43411. this.uv = uv;
  43412. }
  43413. Vertex.prototype.clone = function () {
  43414. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43415. };
  43416. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43417. // orientation of a polygon is flipped.
  43418. Vertex.prototype.flip = function () {
  43419. this.normal = this.normal.scale(-1);
  43420. };
  43421. // Create a new vertex between this vertex and `other` by linearly
  43422. // interpolating all properties using a parameter of `t`. Subclasses should
  43423. // override this to interpolate additional properties.
  43424. Vertex.prototype.interpolate = function (other, t) {
  43425. 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));
  43426. };
  43427. return Vertex;
  43428. }());
  43429. // # class Plane
  43430. // Represents a plane in 3D space.
  43431. var Plane = (function () {
  43432. function Plane(normal, w) {
  43433. this.normal = normal;
  43434. this.w = w;
  43435. }
  43436. Plane.FromPoints = function (a, b, c) {
  43437. var v0 = c.subtract(a);
  43438. var v1 = b.subtract(a);
  43439. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43440. return null;
  43441. }
  43442. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43443. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43444. };
  43445. Plane.prototype.clone = function () {
  43446. return new Plane(this.normal.clone(), this.w);
  43447. };
  43448. Plane.prototype.flip = function () {
  43449. this.normal.scaleInPlace(-1);
  43450. this.w = -this.w;
  43451. };
  43452. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43453. // fragments in the appropriate lists. Coplanar polygons go into either
  43454. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43455. // respect to this plane. Polygons in front or in back of this plane go into
  43456. // either `front` or `back`.
  43457. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43458. var COPLANAR = 0;
  43459. var FRONT = 1;
  43460. var BACK = 2;
  43461. var SPANNING = 3;
  43462. // Classify each point as well as the entire polygon into one of the above
  43463. // four classes.
  43464. var polygonType = 0;
  43465. var types = [];
  43466. var i;
  43467. var t;
  43468. for (i = 0; i < polygon.vertices.length; i++) {
  43469. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43470. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43471. polygonType |= type;
  43472. types.push(type);
  43473. }
  43474. // Put the polygon in the correct list, splitting it when necessary.
  43475. switch (polygonType) {
  43476. case COPLANAR:
  43477. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43478. break;
  43479. case FRONT:
  43480. front.push(polygon);
  43481. break;
  43482. case BACK:
  43483. back.push(polygon);
  43484. break;
  43485. case SPANNING:
  43486. var f = [], b = [];
  43487. for (i = 0; i < polygon.vertices.length; i++) {
  43488. var j = (i + 1) % polygon.vertices.length;
  43489. var ti = types[i], tj = types[j];
  43490. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43491. if (ti !== BACK)
  43492. f.push(vi);
  43493. if (ti !== FRONT)
  43494. b.push(ti !== BACK ? vi.clone() : vi);
  43495. if ((ti | tj) === SPANNING) {
  43496. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43497. var v = vi.interpolate(vj, t);
  43498. f.push(v);
  43499. b.push(v.clone());
  43500. }
  43501. }
  43502. var poly;
  43503. if (f.length >= 3) {
  43504. poly = new Polygon(f, polygon.shared);
  43505. if (poly.plane)
  43506. front.push(poly);
  43507. }
  43508. if (b.length >= 3) {
  43509. poly = new Polygon(b, polygon.shared);
  43510. if (poly.plane)
  43511. back.push(poly);
  43512. }
  43513. break;
  43514. }
  43515. };
  43516. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43517. // point is on the plane.
  43518. Plane.EPSILON = 1e-5;
  43519. return Plane;
  43520. }());
  43521. // # class Polygon
  43522. // Represents a convex polygon. The vertices used to initialize a polygon must
  43523. // be coplanar and form a convex loop.
  43524. //
  43525. // Each convex polygon has a `shared` property, which is shared between all
  43526. // polygons that are clones of each other or were split from the same polygon.
  43527. // This can be used to define per-polygon properties (such as surface color).
  43528. var Polygon = (function () {
  43529. function Polygon(vertices, shared) {
  43530. this.vertices = vertices;
  43531. this.shared = shared;
  43532. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43533. }
  43534. Polygon.prototype.clone = function () {
  43535. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43536. return new Polygon(vertices, this.shared);
  43537. };
  43538. Polygon.prototype.flip = function () {
  43539. this.vertices.reverse().map(function (v) { v.flip(); });
  43540. this.plane.flip();
  43541. };
  43542. return Polygon;
  43543. }());
  43544. // # class Node
  43545. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43546. // by picking a polygon to split along. That polygon (and all other coplanar
  43547. // polygons) are added directly to that node and the other polygons are added to
  43548. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43549. // no distinction between internal and leaf nodes.
  43550. var Node = (function () {
  43551. function Node(polygons) {
  43552. this.plane = null;
  43553. this.front = null;
  43554. this.back = null;
  43555. this.polygons = [];
  43556. if (polygons) {
  43557. this.build(polygons);
  43558. }
  43559. }
  43560. Node.prototype.clone = function () {
  43561. var node = new Node();
  43562. node.plane = this.plane && this.plane.clone();
  43563. node.front = this.front && this.front.clone();
  43564. node.back = this.back && this.back.clone();
  43565. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43566. return node;
  43567. };
  43568. // Convert solid space to empty space and empty space to solid space.
  43569. Node.prototype.invert = function () {
  43570. for (var i = 0; i < this.polygons.length; i++) {
  43571. this.polygons[i].flip();
  43572. }
  43573. if (this.plane) {
  43574. this.plane.flip();
  43575. }
  43576. if (this.front) {
  43577. this.front.invert();
  43578. }
  43579. if (this.back) {
  43580. this.back.invert();
  43581. }
  43582. var temp = this.front;
  43583. this.front = this.back;
  43584. this.back = temp;
  43585. };
  43586. // Recursively remove all polygons in `polygons` that are inside this BSP
  43587. // tree.
  43588. Node.prototype.clipPolygons = function (polygons) {
  43589. if (!this.plane)
  43590. return polygons.slice();
  43591. var front = [], back = [];
  43592. for (var i = 0; i < polygons.length; i++) {
  43593. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43594. }
  43595. if (this.front) {
  43596. front = this.front.clipPolygons(front);
  43597. }
  43598. if (this.back) {
  43599. back = this.back.clipPolygons(back);
  43600. }
  43601. else {
  43602. back = [];
  43603. }
  43604. return front.concat(back);
  43605. };
  43606. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43607. // `bsp`.
  43608. Node.prototype.clipTo = function (bsp) {
  43609. this.polygons = bsp.clipPolygons(this.polygons);
  43610. if (this.front)
  43611. this.front.clipTo(bsp);
  43612. if (this.back)
  43613. this.back.clipTo(bsp);
  43614. };
  43615. // Return a list of all polygons in this BSP tree.
  43616. Node.prototype.allPolygons = function () {
  43617. var polygons = this.polygons.slice();
  43618. if (this.front)
  43619. polygons = polygons.concat(this.front.allPolygons());
  43620. if (this.back)
  43621. polygons = polygons.concat(this.back.allPolygons());
  43622. return polygons;
  43623. };
  43624. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43625. // new polygons are filtered down to the bottom of the tree and become new
  43626. // nodes there. Each set of polygons is partitioned using the first polygon
  43627. // (no heuristic is used to pick a good split).
  43628. Node.prototype.build = function (polygons) {
  43629. if (!polygons.length)
  43630. return;
  43631. if (!this.plane)
  43632. this.plane = polygons[0].plane.clone();
  43633. var front = [], back = [];
  43634. for (var i = 0; i < polygons.length; i++) {
  43635. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43636. }
  43637. if (front.length) {
  43638. if (!this.front)
  43639. this.front = new Node();
  43640. this.front.build(front);
  43641. }
  43642. if (back.length) {
  43643. if (!this.back)
  43644. this.back = new Node();
  43645. this.back.build(back);
  43646. }
  43647. };
  43648. return Node;
  43649. }());
  43650. var CSG = (function () {
  43651. function CSG() {
  43652. this.polygons = new Array();
  43653. }
  43654. // Convert BABYLON.Mesh to BABYLON.CSG
  43655. CSG.FromMesh = function (mesh) {
  43656. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43657. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43658. if (mesh instanceof BABYLON.Mesh) {
  43659. mesh.computeWorldMatrix(true);
  43660. matrix = mesh.getWorldMatrix();
  43661. meshPosition = mesh.position.clone();
  43662. meshRotation = mesh.rotation.clone();
  43663. if (mesh.rotationQuaternion) {
  43664. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43665. }
  43666. meshScaling = mesh.scaling.clone();
  43667. }
  43668. else {
  43669. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43670. }
  43671. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43672. var subMeshes = mesh.subMeshes;
  43673. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43674. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43675. vertices = [];
  43676. for (var j = 0; j < 3; j++) {
  43677. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43678. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43679. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43680. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43681. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43682. vertex = new Vertex(position, normal, uv);
  43683. vertices.push(vertex);
  43684. }
  43685. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43686. // To handle the case of degenerated triangle
  43687. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43688. if (polygon.plane)
  43689. polygons.push(polygon);
  43690. }
  43691. }
  43692. var csg = CSG.FromPolygons(polygons);
  43693. csg.matrix = matrix;
  43694. csg.position = meshPosition;
  43695. csg.rotation = meshRotation;
  43696. csg.scaling = meshScaling;
  43697. csg.rotationQuaternion = meshRotationQuaternion;
  43698. currentCSGMeshId++;
  43699. return csg;
  43700. };
  43701. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43702. CSG.FromPolygons = function (polygons) {
  43703. var csg = new CSG();
  43704. csg.polygons = polygons;
  43705. return csg;
  43706. };
  43707. CSG.prototype.clone = function () {
  43708. var csg = new CSG();
  43709. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43710. csg.copyTransformAttributes(this);
  43711. return csg;
  43712. };
  43713. CSG.prototype.toPolygons = function () {
  43714. return this.polygons;
  43715. };
  43716. CSG.prototype.union = function (csg) {
  43717. var a = new Node(this.clone().polygons);
  43718. var b = new Node(csg.clone().polygons);
  43719. a.clipTo(b);
  43720. b.clipTo(a);
  43721. b.invert();
  43722. b.clipTo(a);
  43723. b.invert();
  43724. a.build(b.allPolygons());
  43725. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43726. };
  43727. CSG.prototype.unionInPlace = function (csg) {
  43728. var a = new Node(this.polygons);
  43729. var b = new Node(csg.polygons);
  43730. a.clipTo(b);
  43731. b.clipTo(a);
  43732. b.invert();
  43733. b.clipTo(a);
  43734. b.invert();
  43735. a.build(b.allPolygons());
  43736. this.polygons = a.allPolygons();
  43737. };
  43738. CSG.prototype.subtract = function (csg) {
  43739. var a = new Node(this.clone().polygons);
  43740. var b = new Node(csg.clone().polygons);
  43741. a.invert();
  43742. a.clipTo(b);
  43743. b.clipTo(a);
  43744. b.invert();
  43745. b.clipTo(a);
  43746. b.invert();
  43747. a.build(b.allPolygons());
  43748. a.invert();
  43749. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43750. };
  43751. CSG.prototype.subtractInPlace = function (csg) {
  43752. var a = new Node(this.polygons);
  43753. var b = new Node(csg.polygons);
  43754. a.invert();
  43755. a.clipTo(b);
  43756. b.clipTo(a);
  43757. b.invert();
  43758. b.clipTo(a);
  43759. b.invert();
  43760. a.build(b.allPolygons());
  43761. a.invert();
  43762. this.polygons = a.allPolygons();
  43763. };
  43764. CSG.prototype.intersect = function (csg) {
  43765. var a = new Node(this.clone().polygons);
  43766. var b = new Node(csg.clone().polygons);
  43767. a.invert();
  43768. b.clipTo(a);
  43769. b.invert();
  43770. a.clipTo(b);
  43771. b.clipTo(a);
  43772. a.build(b.allPolygons());
  43773. a.invert();
  43774. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43775. };
  43776. CSG.prototype.intersectInPlace = function (csg) {
  43777. var a = new Node(this.polygons);
  43778. var b = new Node(csg.polygons);
  43779. a.invert();
  43780. b.clipTo(a);
  43781. b.invert();
  43782. a.clipTo(b);
  43783. b.clipTo(a);
  43784. a.build(b.allPolygons());
  43785. a.invert();
  43786. this.polygons = a.allPolygons();
  43787. };
  43788. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43789. // not modified.
  43790. CSG.prototype.inverse = function () {
  43791. var csg = this.clone();
  43792. csg.inverseInPlace();
  43793. return csg;
  43794. };
  43795. CSG.prototype.inverseInPlace = function () {
  43796. this.polygons.map(function (p) { p.flip(); });
  43797. };
  43798. // This is used to keep meshes transformations so they can be restored
  43799. // when we build back a Babylon Mesh
  43800. // NB : All CSG operations are performed in world coordinates
  43801. CSG.prototype.copyTransformAttributes = function (csg) {
  43802. this.matrix = csg.matrix;
  43803. this.position = csg.position;
  43804. this.rotation = csg.rotation;
  43805. this.scaling = csg.scaling;
  43806. this.rotationQuaternion = csg.rotationQuaternion;
  43807. return this;
  43808. };
  43809. // Build Raw mesh from CSG
  43810. // Coordinates here are in world space
  43811. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43812. var matrix = this.matrix.clone();
  43813. matrix.invert();
  43814. 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;
  43815. if (keepSubMeshes) {
  43816. // Sort Polygons, since subMeshes are indices range
  43817. polygons.sort(function (a, b) {
  43818. if (a.shared.meshId === b.shared.meshId) {
  43819. return a.shared.subMeshId - b.shared.subMeshId;
  43820. }
  43821. else {
  43822. return a.shared.meshId - b.shared.meshId;
  43823. }
  43824. });
  43825. }
  43826. for (var i = 0, il = polygons.length; i < il; i++) {
  43827. polygon = polygons[i];
  43828. // Building SubMeshes
  43829. if (!subMesh_dict[polygon.shared.meshId]) {
  43830. subMesh_dict[polygon.shared.meshId] = {};
  43831. }
  43832. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43833. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43834. indexStart: +Infinity,
  43835. indexEnd: -Infinity,
  43836. materialIndex: polygon.shared.materialIndex
  43837. };
  43838. }
  43839. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43840. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43841. polygonIndices[0] = 0;
  43842. polygonIndices[1] = j - 1;
  43843. polygonIndices[2] = j;
  43844. for (var k = 0; k < 3; k++) {
  43845. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43846. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43847. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43848. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43849. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43850. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43851. // Check if 2 points can be merged
  43852. if (!(typeof vertex_idx !== 'undefined' &&
  43853. normals[vertex_idx * 3] === localNormal.x &&
  43854. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43855. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43856. uvs[vertex_idx * 2] === uv.x &&
  43857. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43858. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43859. uvs.push(uv.x, uv.y);
  43860. normals.push(normal.x, normal.y, normal.z);
  43861. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43862. }
  43863. indices.push(vertex_idx);
  43864. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43865. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43866. currentIndex++;
  43867. }
  43868. }
  43869. }
  43870. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43871. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43872. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43873. mesh.setIndices(indices);
  43874. if (keepSubMeshes) {
  43875. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43876. var materialIndexOffset = 0, materialMaxIndex;
  43877. mesh.subMeshes = new Array();
  43878. for (var m in subMesh_dict) {
  43879. materialMaxIndex = -1;
  43880. for (var sm in subMesh_dict[m]) {
  43881. subMesh_obj = subMesh_dict[m][sm];
  43882. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43883. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43884. }
  43885. materialIndexOffset += ++materialMaxIndex;
  43886. }
  43887. }
  43888. return mesh;
  43889. };
  43890. // Build Mesh from CSG taking material and transforms into account
  43891. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  43892. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43893. mesh.material = material;
  43894. mesh.position.copyFrom(this.position);
  43895. mesh.rotation.copyFrom(this.rotation);
  43896. if (this.rotationQuaternion) {
  43897. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43898. }
  43899. mesh.scaling.copyFrom(this.scaling);
  43900. mesh.computeWorldMatrix(true);
  43901. return mesh;
  43902. };
  43903. return CSG;
  43904. }());
  43905. BABYLON.CSG = CSG;
  43906. })(BABYLON || (BABYLON = {}));
  43907. //# sourceMappingURL=babylon.csg.js.map
  43908. var BABYLON;
  43909. (function (BABYLON) {
  43910. var VRDistortionCorrectionPostProcess = (function (_super) {
  43911. __extends(VRDistortionCorrectionPostProcess, _super);
  43912. //ANY
  43913. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43914. var _this = this;
  43915. _super.call(this, name, "vrDistortionCorrection", [
  43916. 'LensCenter',
  43917. 'Scale',
  43918. 'ScaleIn',
  43919. 'HmdWarpParam'
  43920. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43921. this._isRightEye = isRightEye;
  43922. this._distortionFactors = vrMetrics.distortionK;
  43923. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43924. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43925. this.onSizeChangedObservable.add(function () {
  43926. _this.aspectRatio = _this.width * .5 / _this.height;
  43927. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43928. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43929. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43930. });
  43931. this.onApplyObservable.add(function (effect) {
  43932. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43933. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43934. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43935. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43936. });
  43937. }
  43938. return VRDistortionCorrectionPostProcess;
  43939. }(BABYLON.PostProcess));
  43940. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43941. })(BABYLON || (BABYLON = {}));
  43942. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  43943. // Mainly based on these 2 articles :
  43944. // 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
  43945. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43946. var BABYLON;
  43947. (function (BABYLON) {
  43948. (function (JoystickAxis) {
  43949. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43950. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43951. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  43952. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  43953. var JoystickAxis = BABYLON.JoystickAxis;
  43954. var VirtualJoystick = (function () {
  43955. function VirtualJoystick(leftJoystick) {
  43956. var _this = this;
  43957. if (leftJoystick) {
  43958. this._leftJoystick = true;
  43959. }
  43960. else {
  43961. this._leftJoystick = false;
  43962. }
  43963. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  43964. VirtualJoystick._globalJoystickIndex++;
  43965. // By default left & right arrow keys are moving the X
  43966. // and up & down keys are moving the Y
  43967. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43968. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43969. this.reverseLeftRight = false;
  43970. this.reverseUpDown = false;
  43971. // collections of pointers
  43972. this._touches = new BABYLON.StringDictionary();
  43973. this.deltaPosition = BABYLON.Vector3.Zero();
  43974. this._joystickSensibility = 25;
  43975. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43976. this._rotationSpeed = 25;
  43977. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  43978. this._rotateOnAxisRelativeToMesh = false;
  43979. this._onResize = function (evt) {
  43980. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43981. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43982. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  43983. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  43984. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  43985. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  43986. };
  43987. // injecting a canvas element on top of the canvas 3D game
  43988. if (!VirtualJoystick.vjCanvas) {
  43989. window.addEventListener("resize", this._onResize, false);
  43990. VirtualJoystick.vjCanvas = document.createElement("canvas");
  43991. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43992. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43993. VirtualJoystick.vjCanvas.width = window.innerWidth;
  43994. VirtualJoystick.vjCanvas.height = window.innerHeight;
  43995. VirtualJoystick.vjCanvas.style.width = "100%";
  43996. VirtualJoystick.vjCanvas.style.height = "100%";
  43997. VirtualJoystick.vjCanvas.style.position = "absolute";
  43998. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  43999. VirtualJoystick.vjCanvas.style.top = "0px";
  44000. VirtualJoystick.vjCanvas.style.left = "0px";
  44001. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44002. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44003. // Support for jQuery PEP polyfill
  44004. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44005. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44006. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44007. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44008. document.body.appendChild(VirtualJoystick.vjCanvas);
  44009. }
  44010. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44011. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44012. this.pressed = false;
  44013. // default joystick color
  44014. this._joystickColor = "cyan";
  44015. this._joystickPointerID = -1;
  44016. // current joystick position
  44017. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44018. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44019. // origin joystick position
  44020. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44021. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44022. this._onPointerDownHandlerRef = function (evt) {
  44023. _this._onPointerDown(evt);
  44024. };
  44025. this._onPointerMoveHandlerRef = function (evt) {
  44026. _this._onPointerMove(evt);
  44027. };
  44028. this._onPointerOutHandlerRef = function (evt) {
  44029. _this._onPointerUp(evt);
  44030. };
  44031. this._onPointerUpHandlerRef = function (evt) {
  44032. _this._onPointerUp(evt);
  44033. };
  44034. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44035. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44036. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44037. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44038. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44039. evt.preventDefault(); // Disables system menu
  44040. }, false);
  44041. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44042. }
  44043. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44044. this._joystickSensibility = newJoystickSensibility;
  44045. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44046. };
  44047. VirtualJoystick.prototype._onPointerDown = function (e) {
  44048. var positionOnScreenCondition;
  44049. e.preventDefault();
  44050. if (this._leftJoystick === true) {
  44051. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44052. }
  44053. else {
  44054. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44055. }
  44056. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44057. // First contact will be dedicated to the virtual joystick
  44058. this._joystickPointerID = e.pointerId;
  44059. this._joystickPointerStartPos.x = e.clientX;
  44060. this._joystickPointerStartPos.y = e.clientY;
  44061. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44062. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44063. this._deltaJoystickVector.x = 0;
  44064. this._deltaJoystickVector.y = 0;
  44065. this.pressed = true;
  44066. this._touches.add(e.pointerId.toString(), e);
  44067. }
  44068. else {
  44069. // You can only trigger the action buttons with a joystick declared
  44070. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44071. this._action();
  44072. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44073. }
  44074. }
  44075. };
  44076. VirtualJoystick.prototype._onPointerMove = function (e) {
  44077. // If the current pointer is the one associated to the joystick (first touch contact)
  44078. if (this._joystickPointerID == e.pointerId) {
  44079. this._joystickPointerPos.x = e.clientX;
  44080. this._joystickPointerPos.y = e.clientY;
  44081. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44082. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44083. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44084. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44085. switch (this._axisTargetedByLeftAndRight) {
  44086. case JoystickAxis.X:
  44087. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44088. break;
  44089. case JoystickAxis.Y:
  44090. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44091. break;
  44092. case JoystickAxis.Z:
  44093. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44094. break;
  44095. }
  44096. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44097. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44098. switch (this._axisTargetedByUpAndDown) {
  44099. case JoystickAxis.X:
  44100. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44101. break;
  44102. case JoystickAxis.Y:
  44103. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44104. break;
  44105. case JoystickAxis.Z:
  44106. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44107. break;
  44108. }
  44109. }
  44110. else {
  44111. var data = this._touches.get(e.pointerId.toString());
  44112. if (data) {
  44113. data.x = e.clientX;
  44114. data.y = e.clientY;
  44115. }
  44116. }
  44117. };
  44118. VirtualJoystick.prototype._onPointerUp = function (e) {
  44119. if (this._joystickPointerID == e.pointerId) {
  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. this._joystickPointerID = -1;
  44123. this.pressed = false;
  44124. }
  44125. else {
  44126. var touch = this._touches.get(e.pointerId.toString());
  44127. if (touch) {
  44128. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44129. }
  44130. }
  44131. this._deltaJoystickVector.x = 0;
  44132. this._deltaJoystickVector.y = 0;
  44133. this._touches.remove(e.pointerId.toString());
  44134. };
  44135. /**
  44136. * Change the color of the virtual joystick
  44137. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44138. */
  44139. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44140. this._joystickColor = newColor;
  44141. };
  44142. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44143. this._action = action;
  44144. };
  44145. // Define which axis you'd like to control for left & right
  44146. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44147. switch (axis) {
  44148. case JoystickAxis.X:
  44149. case JoystickAxis.Y:
  44150. case JoystickAxis.Z:
  44151. this._axisTargetedByLeftAndRight = axis;
  44152. break;
  44153. default:
  44154. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44155. break;
  44156. }
  44157. };
  44158. // Define which axis you'd like to control for up & down
  44159. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44160. switch (axis) {
  44161. case JoystickAxis.X:
  44162. case JoystickAxis.Y:
  44163. case JoystickAxis.Z:
  44164. this._axisTargetedByUpAndDown = axis;
  44165. break;
  44166. default:
  44167. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44168. break;
  44169. }
  44170. };
  44171. VirtualJoystick.prototype._clearCanvas = function () {
  44172. if (this._leftJoystick) {
  44173. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44174. }
  44175. else {
  44176. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44177. }
  44178. };
  44179. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44180. var _this = this;
  44181. if (this.pressed) {
  44182. this._touches.forEach(function (touch) {
  44183. if (touch.pointerId === _this._joystickPointerID) {
  44184. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44185. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44186. VirtualJoystick.vjCanvasContext.beginPath();
  44187. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44188. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44189. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44190. VirtualJoystick.vjCanvasContext.stroke();
  44191. VirtualJoystick.vjCanvasContext.closePath();
  44192. VirtualJoystick.vjCanvasContext.beginPath();
  44193. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44194. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44195. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44196. VirtualJoystick.vjCanvasContext.stroke();
  44197. VirtualJoystick.vjCanvasContext.closePath();
  44198. VirtualJoystick.vjCanvasContext.beginPath();
  44199. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44200. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44201. VirtualJoystick.vjCanvasContext.stroke();
  44202. VirtualJoystick.vjCanvasContext.closePath();
  44203. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44204. }
  44205. else {
  44206. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44207. VirtualJoystick.vjCanvasContext.beginPath();
  44208. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44209. VirtualJoystick.vjCanvasContext.beginPath();
  44210. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44211. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44212. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44213. VirtualJoystick.vjCanvasContext.stroke();
  44214. VirtualJoystick.vjCanvasContext.closePath();
  44215. touch.prevX = touch.x;
  44216. touch.prevY = touch.y;
  44217. }
  44218. ;
  44219. });
  44220. }
  44221. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44222. };
  44223. VirtualJoystick.prototype.releaseCanvas = function () {
  44224. if (VirtualJoystick.vjCanvas) {
  44225. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44226. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44227. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44228. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44229. window.removeEventListener("resize", this._onResize);
  44230. document.body.removeChild(VirtualJoystick.vjCanvas);
  44231. VirtualJoystick.vjCanvas = null;
  44232. }
  44233. };
  44234. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44235. VirtualJoystick._globalJoystickIndex = 0;
  44236. return VirtualJoystick;
  44237. }());
  44238. BABYLON.VirtualJoystick = VirtualJoystick;
  44239. })(BABYLON || (BABYLON = {}));
  44240. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44241. var BABYLON;
  44242. (function (BABYLON) {
  44243. // We're mainly based on the logic defined into the FreeCamera code
  44244. var VirtualJoysticksCamera = (function (_super) {
  44245. __extends(VirtualJoysticksCamera, _super);
  44246. function VirtualJoysticksCamera(name, position, scene) {
  44247. _super.call(this, name, position, scene);
  44248. this.inputs.addVirtualJoystick();
  44249. }
  44250. VirtualJoysticksCamera.prototype.getClassName = function () {
  44251. return "VirtualJoysticksCamera";
  44252. };
  44253. return VirtualJoysticksCamera;
  44254. }(BABYLON.FreeCamera));
  44255. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44256. })(BABYLON || (BABYLON = {}));
  44257. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44258. var BABYLON;
  44259. (function (BABYLON) {
  44260. var FreeCameraVirtualJoystickInput = (function () {
  44261. function FreeCameraVirtualJoystickInput() {
  44262. }
  44263. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44264. return this._leftjoystick;
  44265. };
  44266. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44267. return this._rightjoystick;
  44268. };
  44269. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44270. if (this._leftjoystick) {
  44271. var camera = this.camera;
  44272. var speed = camera._computeLocalCameraSpeed() * 50;
  44273. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44274. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44275. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44276. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44277. if (!this._leftjoystick.pressed) {
  44278. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44279. }
  44280. if (!this._rightjoystick.pressed) {
  44281. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44282. }
  44283. }
  44284. };
  44285. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44286. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44287. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44288. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44289. this._leftjoystick.setJoystickSensibility(0.15);
  44290. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44291. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44292. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44293. this._rightjoystick.reverseUpDown = true;
  44294. this._rightjoystick.setJoystickSensibility(0.05);
  44295. this._rightjoystick.setJoystickColor("yellow");
  44296. };
  44297. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44298. this._leftjoystick.releaseCanvas();
  44299. this._rightjoystick.releaseCanvas();
  44300. };
  44301. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44302. return "FreeCameraVirtualJoystickInput";
  44303. };
  44304. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44305. return "virtualJoystick";
  44306. };
  44307. return FreeCameraVirtualJoystickInput;
  44308. }());
  44309. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44310. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44311. })(BABYLON || (BABYLON = {}));
  44312. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44313. var BABYLON;
  44314. (function (BABYLON) {
  44315. var AnaglyphPostProcess = (function (_super) {
  44316. __extends(AnaglyphPostProcess, _super);
  44317. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44318. var _this = this;
  44319. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  44320. this._passedProcess = rigCameras[0]._rigPostProcess;
  44321. this.onApplyObservable.add(function (effect) {
  44322. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44323. });
  44324. }
  44325. return AnaglyphPostProcess;
  44326. }(BABYLON.PostProcess));
  44327. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44328. })(BABYLON || (BABYLON = {}));
  44329. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44330. var BABYLON;
  44331. (function (BABYLON) {
  44332. var OutlineRenderer = (function () {
  44333. function OutlineRenderer(scene) {
  44334. this._scene = scene;
  44335. }
  44336. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44337. var _this = this;
  44338. if (useOverlay === void 0) { useOverlay = false; }
  44339. var scene = this._scene;
  44340. var engine = this._scene.getEngine();
  44341. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44342. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44343. return;
  44344. }
  44345. var mesh = subMesh.getRenderingMesh();
  44346. var material = subMesh.getMaterial();
  44347. engine.enableEffect(this._effect);
  44348. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44349. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44350. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44351. // Bones
  44352. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44353. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44354. }
  44355. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44356. // Alpha test
  44357. if (material && material.needAlphaTesting()) {
  44358. var alphaTexture = material.getAlphaTestTexture();
  44359. this._effect.setTexture("diffuseSampler", alphaTexture);
  44360. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44361. }
  44362. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44363. };
  44364. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44365. var defines = [];
  44366. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44367. var mesh = subMesh.getMesh();
  44368. var material = subMesh.getMaterial();
  44369. // Alpha test
  44370. if (material && material.needAlphaTesting()) {
  44371. defines.push("#define ALPHATEST");
  44372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44373. attribs.push(BABYLON.VertexBuffer.UVKind);
  44374. defines.push("#define UV1");
  44375. }
  44376. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44377. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44378. defines.push("#define UV2");
  44379. }
  44380. }
  44381. // Bones
  44382. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44383. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44384. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44385. if (mesh.numBoneInfluencers > 4) {
  44386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44388. }
  44389. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44390. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44391. }
  44392. else {
  44393. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44394. }
  44395. // Instances
  44396. if (useInstances) {
  44397. defines.push("#define INSTANCES");
  44398. attribs.push("world0");
  44399. attribs.push("world1");
  44400. attribs.push("world2");
  44401. attribs.push("world3");
  44402. }
  44403. // Get correct effect
  44404. var join = defines.join("\n");
  44405. if (this._cachedDefines !== join) {
  44406. this._cachedDefines = join;
  44407. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44408. }
  44409. return this._effect.isReady();
  44410. };
  44411. return OutlineRenderer;
  44412. }());
  44413. BABYLON.OutlineRenderer = OutlineRenderer;
  44414. })(BABYLON || (BABYLON = {}));
  44415. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44416. var BABYLON;
  44417. (function (BABYLON) {
  44418. var MeshAssetTask = (function () {
  44419. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44420. this.name = name;
  44421. this.meshesNames = meshesNames;
  44422. this.rootUrl = rootUrl;
  44423. this.sceneFilename = sceneFilename;
  44424. this.isCompleted = false;
  44425. }
  44426. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44427. var _this = this;
  44428. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44429. _this.loadedMeshes = meshes;
  44430. _this.loadedParticleSystems = particleSystems;
  44431. _this.loadedSkeletons = skeletons;
  44432. _this.isCompleted = true;
  44433. if (_this.onSuccess) {
  44434. _this.onSuccess(_this);
  44435. }
  44436. onSuccess();
  44437. }, null, function () {
  44438. if (_this.onError) {
  44439. _this.onError(_this);
  44440. }
  44441. onError();
  44442. });
  44443. };
  44444. return MeshAssetTask;
  44445. }());
  44446. BABYLON.MeshAssetTask = MeshAssetTask;
  44447. var TextFileAssetTask = (function () {
  44448. function TextFileAssetTask(name, url) {
  44449. this.name = name;
  44450. this.url = url;
  44451. this.isCompleted = false;
  44452. }
  44453. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44454. var _this = this;
  44455. BABYLON.Tools.LoadFile(this.url, function (data) {
  44456. _this.text = data;
  44457. _this.isCompleted = true;
  44458. if (_this.onSuccess) {
  44459. _this.onSuccess(_this);
  44460. }
  44461. onSuccess();
  44462. }, null, scene.database, false, function () {
  44463. if (_this.onError) {
  44464. _this.onError(_this);
  44465. }
  44466. onError();
  44467. });
  44468. };
  44469. return TextFileAssetTask;
  44470. }());
  44471. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44472. var BinaryFileAssetTask = (function () {
  44473. function BinaryFileAssetTask(name, url) {
  44474. this.name = name;
  44475. this.url = url;
  44476. this.isCompleted = false;
  44477. }
  44478. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44479. var _this = this;
  44480. BABYLON.Tools.LoadFile(this.url, function (data) {
  44481. _this.data = data;
  44482. _this.isCompleted = true;
  44483. if (_this.onSuccess) {
  44484. _this.onSuccess(_this);
  44485. }
  44486. onSuccess();
  44487. }, null, scene.database, true, function () {
  44488. if (_this.onError) {
  44489. _this.onError(_this);
  44490. }
  44491. onError();
  44492. });
  44493. };
  44494. return BinaryFileAssetTask;
  44495. }());
  44496. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44497. var ImageAssetTask = (function () {
  44498. function ImageAssetTask(name, url) {
  44499. this.name = name;
  44500. this.url = url;
  44501. this.isCompleted = false;
  44502. }
  44503. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44504. var _this = this;
  44505. var img = new Image();
  44506. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44507. img.onload = function () {
  44508. _this.image = img;
  44509. _this.isCompleted = true;
  44510. if (_this.onSuccess) {
  44511. _this.onSuccess(_this);
  44512. }
  44513. onSuccess();
  44514. };
  44515. img.onerror = function () {
  44516. if (_this.onError) {
  44517. _this.onError(_this);
  44518. }
  44519. onError();
  44520. };
  44521. img.src = this.url;
  44522. };
  44523. return ImageAssetTask;
  44524. }());
  44525. BABYLON.ImageAssetTask = ImageAssetTask;
  44526. var TextureAssetTask = (function () {
  44527. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44529. this.name = name;
  44530. this.url = url;
  44531. this.noMipmap = noMipmap;
  44532. this.invertY = invertY;
  44533. this.samplingMode = samplingMode;
  44534. this.isCompleted = false;
  44535. }
  44536. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44537. var _this = this;
  44538. var onload = function () {
  44539. _this.isCompleted = true;
  44540. if (_this.onSuccess) {
  44541. _this.onSuccess(_this);
  44542. }
  44543. onSuccess();
  44544. };
  44545. var onerror = function () {
  44546. if (_this.onError) {
  44547. _this.onError(_this);
  44548. }
  44549. onError();
  44550. };
  44551. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44552. };
  44553. return TextureAssetTask;
  44554. }());
  44555. BABYLON.TextureAssetTask = TextureAssetTask;
  44556. var CubeTextureAssetTask = (function () {
  44557. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44558. this.name = name;
  44559. this.url = url;
  44560. this.extensions = extensions;
  44561. this.noMipmap = noMipmap;
  44562. this.files = files;
  44563. this.isCompleted = false;
  44564. }
  44565. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44566. var _this = this;
  44567. var onload = function () {
  44568. _this.isCompleted = true;
  44569. if (_this.onSuccess) {
  44570. _this.onSuccess(_this);
  44571. }
  44572. onSuccess();
  44573. };
  44574. var onerror = function () {
  44575. if (_this.onError) {
  44576. _this.onError(_this);
  44577. }
  44578. onError();
  44579. };
  44580. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44581. };
  44582. return CubeTextureAssetTask;
  44583. }());
  44584. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44585. var AssetsManager = (function () {
  44586. function AssetsManager(scene) {
  44587. this.tasks = new Array();
  44588. this.waitingTasksCount = 0;
  44589. this.useDefaultLoadingScreen = true;
  44590. this._scene = scene;
  44591. }
  44592. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44593. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44594. this.tasks.push(task);
  44595. return task;
  44596. };
  44597. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44598. var task = new TextFileAssetTask(taskName, url);
  44599. this.tasks.push(task);
  44600. return task;
  44601. };
  44602. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44603. var task = new BinaryFileAssetTask(taskName, url);
  44604. this.tasks.push(task);
  44605. return task;
  44606. };
  44607. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44608. var task = new ImageAssetTask(taskName, url);
  44609. this.tasks.push(task);
  44610. return task;
  44611. };
  44612. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44614. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44615. this.tasks.push(task);
  44616. return task;
  44617. };
  44618. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44619. this.waitingTasksCount--;
  44620. if (this.waitingTasksCount === 0) {
  44621. if (this.onFinish) {
  44622. this.onFinish(this.tasks);
  44623. }
  44624. this._scene.getEngine().hideLoadingUI();
  44625. }
  44626. };
  44627. AssetsManager.prototype._runTask = function (task) {
  44628. var _this = this;
  44629. task.run(this._scene, function () {
  44630. if (_this.onTaskSuccess) {
  44631. _this.onTaskSuccess(task);
  44632. }
  44633. _this._decreaseWaitingTasksCount();
  44634. }, function () {
  44635. if (_this.onTaskError) {
  44636. _this.onTaskError(task);
  44637. }
  44638. _this._decreaseWaitingTasksCount();
  44639. });
  44640. };
  44641. AssetsManager.prototype.reset = function () {
  44642. this.tasks = new Array();
  44643. return this;
  44644. };
  44645. AssetsManager.prototype.load = function () {
  44646. this.waitingTasksCount = this.tasks.length;
  44647. if (this.waitingTasksCount === 0) {
  44648. if (this.onFinish) {
  44649. this.onFinish(this.tasks);
  44650. }
  44651. return this;
  44652. }
  44653. if (this.useDefaultLoadingScreen) {
  44654. this._scene.getEngine().displayLoadingUI();
  44655. }
  44656. for (var index = 0; index < this.tasks.length; index++) {
  44657. var task = this.tasks[index];
  44658. this._runTask(task);
  44659. }
  44660. return this;
  44661. };
  44662. return AssetsManager;
  44663. }());
  44664. BABYLON.AssetsManager = AssetsManager;
  44665. })(BABYLON || (BABYLON = {}));
  44666. //# sourceMappingURL=babylon.assetsManager.js.map
  44667. var BABYLON;
  44668. (function (BABYLON) {
  44669. var VRCameraMetrics = (function () {
  44670. function VRCameraMetrics() {
  44671. this.compensateDistortion = true;
  44672. }
  44673. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44674. get: function () {
  44675. return this.hResolution / (2 * this.vResolution);
  44676. },
  44677. enumerable: true,
  44678. configurable: true
  44679. });
  44680. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44681. get: function () {
  44682. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44683. },
  44684. enumerable: true,
  44685. configurable: true
  44686. });
  44687. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44688. get: function () {
  44689. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44690. var h = (4 * meters) / this.hScreenSize;
  44691. return BABYLON.Matrix.Translation(h, 0, 0);
  44692. },
  44693. enumerable: true,
  44694. configurable: true
  44695. });
  44696. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44697. get: function () {
  44698. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44699. var h = (4 * meters) / this.hScreenSize;
  44700. return BABYLON.Matrix.Translation(-h, 0, 0);
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44706. get: function () {
  44707. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44713. get: function () {
  44714. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44715. },
  44716. enumerable: true,
  44717. configurable: true
  44718. });
  44719. VRCameraMetrics.GetDefault = function () {
  44720. var result = new VRCameraMetrics();
  44721. result.hResolution = 1280;
  44722. result.vResolution = 800;
  44723. result.hScreenSize = 0.149759993;
  44724. result.vScreenSize = 0.0935999975;
  44725. result.vScreenCenter = 0.0467999987,
  44726. result.eyeToScreenDistance = 0.0410000011;
  44727. result.lensSeparationDistance = 0.0635000020;
  44728. result.interpupillaryDistance = 0.0640000030;
  44729. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44730. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44731. result.postProcessScaleFactor = 1.714605507808412;
  44732. result.lensCenterOffset = 0.151976421;
  44733. return result;
  44734. };
  44735. return VRCameraMetrics;
  44736. }());
  44737. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44738. })(BABYLON || (BABYLON = {}));
  44739. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44740. var BABYLON;
  44741. (function (BABYLON) {
  44742. var WebVRFreeCamera = (function (_super) {
  44743. __extends(WebVRFreeCamera, _super);
  44744. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44745. var _this = this;
  44746. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44747. if (webVROptions === void 0) { webVROptions = {}; }
  44748. _super.call(this, name, position, scene);
  44749. this.webVROptions = webVROptions;
  44750. this._vrDevice = null;
  44751. this._cacheState = null;
  44752. this._vrEnabled = false;
  44753. this._attached = false;
  44754. //using the position provided as the current position offset
  44755. this._positionOffset = position;
  44756. //enable VR
  44757. this.getEngine().initWebVR();
  44758. if (!this.getEngine().vrDisplaysPromise) {
  44759. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44760. }
  44761. else {
  44762. //TODO get the metrics updated using the device's eye parameters!
  44763. //TODO also check that the device has the right capabilities!
  44764. this._frameData = new VRFrameData();
  44765. this.getEngine().vrDisplaysPromise.then(function (devices) {
  44766. if (devices.length > 0) {
  44767. _this._vrEnabled = true;
  44768. if (_this.webVROptions.displayName) {
  44769. var found = devices.some(function (device) {
  44770. if (device.displayName === _this.webVROptions.displayName) {
  44771. _this._vrDevice = device;
  44772. return true;
  44773. }
  44774. else {
  44775. return false;
  44776. }
  44777. });
  44778. if (!found) {
  44779. _this._vrDevice = devices[0];
  44780. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44781. }
  44782. }
  44783. else {
  44784. //choose the first one
  44785. _this._vrDevice = devices[0];
  44786. }
  44787. //reset the rig parameters.
  44788. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44789. if (_this._attached) {
  44790. _this.getEngine().enableVR(_this._vrDevice);
  44791. }
  44792. }
  44793. else {
  44794. BABYLON.Tools.Error("No WebVR devices found!");
  44795. }
  44796. });
  44797. }
  44798. this.rotationQuaternion = new BABYLON.Quaternion();
  44799. this._quaternionCache = new BABYLON.Quaternion();
  44800. }
  44801. WebVRFreeCamera.prototype._checkInputs = function () {
  44802. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44803. var currentPost = this._frameData.pose;
  44804. //make sure we have data
  44805. if (currentPost && currentPost.orientation) {
  44806. this._cacheState = currentPost;
  44807. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44808. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44809. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44810. //scale the position accordingly
  44811. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44812. //add the position offset
  44813. this.position.addInPlace(this._positionOffset);
  44814. }
  44815. }
  44816. }
  44817. _super.prototype._checkInputs.call(this);
  44818. };
  44819. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44820. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44821. this._attached = true;
  44822. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44823. if (this._vrEnabled) {
  44824. this.getEngine().enableVR(this._vrDevice);
  44825. }
  44826. };
  44827. WebVRFreeCamera.prototype.detachControl = function (element) {
  44828. _super.prototype.detachControl.call(this, element);
  44829. this._vrEnabled = false;
  44830. this._attached = false;
  44831. this.getEngine().disableVR();
  44832. };
  44833. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44834. //Backwards comp.
  44835. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44836. //this.getEngine().switchFullscreen(requestPointerlock);
  44837. };
  44838. WebVRFreeCamera.prototype.getClassName = function () {
  44839. return "WebVRFreeCamera";
  44840. };
  44841. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44842. //uses the vrDisplay's "resetPose()".
  44843. //pitch and roll won't be affected.
  44844. this._vrDevice.resetPose();
  44845. };
  44846. /**
  44847. *
  44848. * Set the position offset of the VR camera
  44849. * The offset will be added to the WebVR pose, after scaling it (if set).
  44850. *
  44851. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44852. *
  44853. * @memberOf WebVRFreeCamera
  44854. */
  44855. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44856. if (newPosition) {
  44857. this._positionOffset = newPosition;
  44858. }
  44859. else {
  44860. this._positionOffset.copyFrom(this.position);
  44861. }
  44862. };
  44863. return WebVRFreeCamera;
  44864. }(BABYLON.FreeCamera));
  44865. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44866. })(BABYLON || (BABYLON = {}));
  44867. //# sourceMappingURL=babylon.webVRCamera.js.map
  44868. var BABYLON;
  44869. (function (BABYLON) {
  44870. // Standard optimizations
  44871. var SceneOptimization = (function () {
  44872. function SceneOptimization(priority) {
  44873. if (priority === void 0) { priority = 0; }
  44874. this.priority = priority;
  44875. this.apply = function (scene) {
  44876. return true; // Return true if everything that can be done was applied
  44877. };
  44878. }
  44879. return SceneOptimization;
  44880. }());
  44881. BABYLON.SceneOptimization = SceneOptimization;
  44882. var TextureOptimization = (function (_super) {
  44883. __extends(TextureOptimization, _super);
  44884. function TextureOptimization(priority, maximumSize) {
  44885. var _this = this;
  44886. if (priority === void 0) { priority = 0; }
  44887. if (maximumSize === void 0) { maximumSize = 1024; }
  44888. _super.call(this, priority);
  44889. this.priority = priority;
  44890. this.maximumSize = maximumSize;
  44891. this.apply = function (scene) {
  44892. var allDone = true;
  44893. for (var index = 0; index < scene.textures.length; index++) {
  44894. var texture = scene.textures[index];
  44895. if (!texture.canRescale) {
  44896. continue;
  44897. }
  44898. var currentSize = texture.getSize();
  44899. var maxDimension = Math.max(currentSize.width, currentSize.height);
  44900. if (maxDimension > _this.maximumSize) {
  44901. texture.scale(0.5);
  44902. allDone = false;
  44903. }
  44904. }
  44905. return allDone;
  44906. };
  44907. }
  44908. return TextureOptimization;
  44909. }(SceneOptimization));
  44910. BABYLON.TextureOptimization = TextureOptimization;
  44911. var HardwareScalingOptimization = (function (_super) {
  44912. __extends(HardwareScalingOptimization, _super);
  44913. function HardwareScalingOptimization(priority, maximumScale) {
  44914. var _this = this;
  44915. if (priority === void 0) { priority = 0; }
  44916. if (maximumScale === void 0) { maximumScale = 2; }
  44917. _super.call(this, priority);
  44918. this.priority = priority;
  44919. this.maximumScale = maximumScale;
  44920. this._currentScale = 1;
  44921. this.apply = function (scene) {
  44922. _this._currentScale++;
  44923. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  44924. return _this._currentScale >= _this.maximumScale;
  44925. };
  44926. }
  44927. return HardwareScalingOptimization;
  44928. }(SceneOptimization));
  44929. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44930. var ShadowsOptimization = (function (_super) {
  44931. __extends(ShadowsOptimization, _super);
  44932. function ShadowsOptimization() {
  44933. _super.apply(this, arguments);
  44934. this.apply = function (scene) {
  44935. scene.shadowsEnabled = false;
  44936. return true;
  44937. };
  44938. }
  44939. return ShadowsOptimization;
  44940. }(SceneOptimization));
  44941. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44942. var PostProcessesOptimization = (function (_super) {
  44943. __extends(PostProcessesOptimization, _super);
  44944. function PostProcessesOptimization() {
  44945. _super.apply(this, arguments);
  44946. this.apply = function (scene) {
  44947. scene.postProcessesEnabled = false;
  44948. return true;
  44949. };
  44950. }
  44951. return PostProcessesOptimization;
  44952. }(SceneOptimization));
  44953. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  44954. var LensFlaresOptimization = (function (_super) {
  44955. __extends(LensFlaresOptimization, _super);
  44956. function LensFlaresOptimization() {
  44957. _super.apply(this, arguments);
  44958. this.apply = function (scene) {
  44959. scene.lensFlaresEnabled = false;
  44960. return true;
  44961. };
  44962. }
  44963. return LensFlaresOptimization;
  44964. }(SceneOptimization));
  44965. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  44966. var ParticlesOptimization = (function (_super) {
  44967. __extends(ParticlesOptimization, _super);
  44968. function ParticlesOptimization() {
  44969. _super.apply(this, arguments);
  44970. this.apply = function (scene) {
  44971. scene.particlesEnabled = false;
  44972. return true;
  44973. };
  44974. }
  44975. return ParticlesOptimization;
  44976. }(SceneOptimization));
  44977. BABYLON.ParticlesOptimization = ParticlesOptimization;
  44978. var RenderTargetsOptimization = (function (_super) {
  44979. __extends(RenderTargetsOptimization, _super);
  44980. function RenderTargetsOptimization() {
  44981. _super.apply(this, arguments);
  44982. this.apply = function (scene) {
  44983. scene.renderTargetsEnabled = false;
  44984. return true;
  44985. };
  44986. }
  44987. return RenderTargetsOptimization;
  44988. }(SceneOptimization));
  44989. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  44990. var MergeMeshesOptimization = (function (_super) {
  44991. __extends(MergeMeshesOptimization, _super);
  44992. function MergeMeshesOptimization() {
  44993. var _this = this;
  44994. _super.apply(this, arguments);
  44995. this._canBeMerged = function (abstractMesh) {
  44996. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  44997. return false;
  44998. }
  44999. var mesh = abstractMesh;
  45000. if (!mesh.isVisible || !mesh.isEnabled()) {
  45001. return false;
  45002. }
  45003. if (mesh.instances.length > 0) {
  45004. return false;
  45005. }
  45006. if (mesh.skeleton || mesh.hasLODLevels) {
  45007. return false;
  45008. }
  45009. if (mesh.parent) {
  45010. return false;
  45011. }
  45012. return true;
  45013. };
  45014. this.apply = function (scene, updateSelectionTree) {
  45015. var globalPool = scene.meshes.slice(0);
  45016. var globalLength = globalPool.length;
  45017. for (var index = 0; index < globalLength; index++) {
  45018. var currentPool = new Array();
  45019. var current = globalPool[index];
  45020. // Checks
  45021. if (!_this._canBeMerged(current)) {
  45022. continue;
  45023. }
  45024. currentPool.push(current);
  45025. // Find compatible meshes
  45026. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45027. var otherMesh = globalPool[subIndex];
  45028. if (!_this._canBeMerged(otherMesh)) {
  45029. continue;
  45030. }
  45031. if (otherMesh.material !== current.material) {
  45032. continue;
  45033. }
  45034. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45035. continue;
  45036. }
  45037. currentPool.push(otherMesh);
  45038. globalLength--;
  45039. globalPool.splice(subIndex, 1);
  45040. subIndex--;
  45041. }
  45042. if (currentPool.length < 2) {
  45043. continue;
  45044. }
  45045. // Merge meshes
  45046. BABYLON.Mesh.MergeMeshes(currentPool);
  45047. }
  45048. if (updateSelectionTree != undefined) {
  45049. if (updateSelectionTree) {
  45050. scene.createOrUpdateSelectionOctree();
  45051. }
  45052. }
  45053. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45054. scene.createOrUpdateSelectionOctree();
  45055. }
  45056. return true;
  45057. };
  45058. }
  45059. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45060. get: function () {
  45061. return MergeMeshesOptimization._UpdateSelectionTree;
  45062. },
  45063. set: function (value) {
  45064. MergeMeshesOptimization._UpdateSelectionTree = value;
  45065. },
  45066. enumerable: true,
  45067. configurable: true
  45068. });
  45069. MergeMeshesOptimization._UpdateSelectionTree = false;
  45070. return MergeMeshesOptimization;
  45071. }(SceneOptimization));
  45072. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45073. // Options
  45074. var SceneOptimizerOptions = (function () {
  45075. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45076. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45077. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45078. this.targetFrameRate = targetFrameRate;
  45079. this.trackerDuration = trackerDuration;
  45080. this.optimizations = new Array();
  45081. }
  45082. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45083. var result = new SceneOptimizerOptions(targetFrameRate);
  45084. var priority = 0;
  45085. result.optimizations.push(new MergeMeshesOptimization(priority));
  45086. result.optimizations.push(new ShadowsOptimization(priority));
  45087. result.optimizations.push(new LensFlaresOptimization(priority));
  45088. // Next priority
  45089. priority++;
  45090. result.optimizations.push(new PostProcessesOptimization(priority));
  45091. result.optimizations.push(new ParticlesOptimization(priority));
  45092. // Next priority
  45093. priority++;
  45094. result.optimizations.push(new TextureOptimization(priority, 1024));
  45095. return result;
  45096. };
  45097. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45098. var result = new SceneOptimizerOptions(targetFrameRate);
  45099. var priority = 0;
  45100. result.optimizations.push(new MergeMeshesOptimization(priority));
  45101. result.optimizations.push(new ShadowsOptimization(priority));
  45102. result.optimizations.push(new LensFlaresOptimization(priority));
  45103. // Next priority
  45104. priority++;
  45105. result.optimizations.push(new PostProcessesOptimization(priority));
  45106. result.optimizations.push(new ParticlesOptimization(priority));
  45107. // Next priority
  45108. priority++;
  45109. result.optimizations.push(new TextureOptimization(priority, 512));
  45110. // Next priority
  45111. priority++;
  45112. result.optimizations.push(new RenderTargetsOptimization(priority));
  45113. // Next priority
  45114. priority++;
  45115. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45116. return result;
  45117. };
  45118. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45119. var result = new SceneOptimizerOptions(targetFrameRate);
  45120. var priority = 0;
  45121. result.optimizations.push(new MergeMeshesOptimization(priority));
  45122. result.optimizations.push(new ShadowsOptimization(priority));
  45123. result.optimizations.push(new LensFlaresOptimization(priority));
  45124. // Next priority
  45125. priority++;
  45126. result.optimizations.push(new PostProcessesOptimization(priority));
  45127. result.optimizations.push(new ParticlesOptimization(priority));
  45128. // Next priority
  45129. priority++;
  45130. result.optimizations.push(new TextureOptimization(priority, 256));
  45131. // Next priority
  45132. priority++;
  45133. result.optimizations.push(new RenderTargetsOptimization(priority));
  45134. // Next priority
  45135. priority++;
  45136. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45137. return result;
  45138. };
  45139. return SceneOptimizerOptions;
  45140. }());
  45141. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45142. // Scene optimizer tool
  45143. var SceneOptimizer = (function () {
  45144. function SceneOptimizer() {
  45145. }
  45146. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45147. // TODO: add an epsilon
  45148. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45149. if (onSuccess) {
  45150. onSuccess();
  45151. }
  45152. return;
  45153. }
  45154. // Apply current level of optimizations
  45155. var allDone = true;
  45156. var noOptimizationApplied = true;
  45157. for (var index = 0; index < options.optimizations.length; index++) {
  45158. var optimization = options.optimizations[index];
  45159. if (optimization.priority === currentPriorityLevel) {
  45160. noOptimizationApplied = false;
  45161. allDone = allDone && optimization.apply(scene);
  45162. }
  45163. }
  45164. // If no optimization was applied, this is a failure :(
  45165. if (noOptimizationApplied) {
  45166. if (onFailure) {
  45167. onFailure();
  45168. }
  45169. return;
  45170. }
  45171. // If all optimizations were done, move to next level
  45172. if (allDone) {
  45173. currentPriorityLevel++;
  45174. }
  45175. // Let's the system running for a specific amount of time before checking FPS
  45176. scene.executeWhenReady(function () {
  45177. setTimeout(function () {
  45178. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45179. }, options.trackerDuration);
  45180. });
  45181. };
  45182. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45183. if (!options) {
  45184. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45185. }
  45186. // Let's the system running for a specific amount of time before checking FPS
  45187. scene.executeWhenReady(function () {
  45188. setTimeout(function () {
  45189. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45190. }, options.trackerDuration);
  45191. });
  45192. };
  45193. return SceneOptimizer;
  45194. }());
  45195. BABYLON.SceneOptimizer = SceneOptimizer;
  45196. })(BABYLON || (BABYLON = {}));
  45197. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45198. var BABYLON;
  45199. (function (BABYLON) {
  45200. var Internals;
  45201. (function (Internals) {
  45202. var MeshLODLevel = (function () {
  45203. function MeshLODLevel(distance, mesh) {
  45204. this.distance = distance;
  45205. this.mesh = mesh;
  45206. }
  45207. return MeshLODLevel;
  45208. }());
  45209. Internals.MeshLODLevel = MeshLODLevel;
  45210. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45211. })(BABYLON || (BABYLON = {}));
  45212. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45213. var BABYLON;
  45214. (function (BABYLON) {
  45215. var RawTexture = (function (_super) {
  45216. __extends(RawTexture, _super);
  45217. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45218. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45219. if (invertY === void 0) { invertY = false; }
  45220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45221. _super.call(this, null, scene, !generateMipMaps, invertY);
  45222. this.format = format;
  45223. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45224. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45225. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45226. }
  45227. RawTexture.prototype.update = function (data) {
  45228. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45229. };
  45230. // Statics
  45231. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45232. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45233. if (invertY === void 0) { invertY = false; }
  45234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45235. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45236. };
  45237. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45238. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45239. if (invertY === void 0) { invertY = false; }
  45240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45241. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45242. };
  45243. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45244. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45245. if (invertY === void 0) { invertY = false; }
  45246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45247. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45248. };
  45249. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45250. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45251. if (invertY === void 0) { invertY = false; }
  45252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45253. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45254. };
  45255. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45256. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45257. if (invertY === void 0) { invertY = false; }
  45258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45259. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45260. };
  45261. return RawTexture;
  45262. }(BABYLON.Texture));
  45263. BABYLON.RawTexture = RawTexture;
  45264. })(BABYLON || (BABYLON = {}));
  45265. //# sourceMappingURL=babylon.rawTexture.js.map
  45266. var BABYLON;
  45267. (function (BABYLON) {
  45268. var IndexedVector2 = (function (_super) {
  45269. __extends(IndexedVector2, _super);
  45270. function IndexedVector2(original, index) {
  45271. _super.call(this, original.x, original.y);
  45272. this.index = index;
  45273. }
  45274. return IndexedVector2;
  45275. }(BABYLON.Vector2));
  45276. var PolygonPoints = (function () {
  45277. function PolygonPoints() {
  45278. this.elements = new Array();
  45279. }
  45280. PolygonPoints.prototype.add = function (originalPoints) {
  45281. var _this = this;
  45282. var result = new Array();
  45283. originalPoints.forEach(function (point) {
  45284. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45285. var newPoint = new IndexedVector2(point, _this.elements.length);
  45286. result.push(newPoint);
  45287. _this.elements.push(newPoint);
  45288. }
  45289. });
  45290. return result;
  45291. };
  45292. PolygonPoints.prototype.computeBounds = function () {
  45293. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45294. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45295. this.elements.forEach(function (point) {
  45296. // x
  45297. if (point.x < lmin.x) {
  45298. lmin.x = point.x;
  45299. }
  45300. else if (point.x > lmax.x) {
  45301. lmax.x = point.x;
  45302. }
  45303. // y
  45304. if (point.y < lmin.y) {
  45305. lmin.y = point.y;
  45306. }
  45307. else if (point.y > lmax.y) {
  45308. lmax.y = point.y;
  45309. }
  45310. });
  45311. return {
  45312. min: lmin,
  45313. max: lmax,
  45314. width: lmax.x - lmin.x,
  45315. height: lmax.y - lmin.y
  45316. };
  45317. };
  45318. return PolygonPoints;
  45319. }());
  45320. var Polygon = (function () {
  45321. function Polygon() {
  45322. }
  45323. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45324. return [
  45325. new BABYLON.Vector2(xmin, ymin),
  45326. new BABYLON.Vector2(xmax, ymin),
  45327. new BABYLON.Vector2(xmax, ymax),
  45328. new BABYLON.Vector2(xmin, ymax)
  45329. ];
  45330. };
  45331. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45332. if (cx === void 0) { cx = 0; }
  45333. if (cy === void 0) { cy = 0; }
  45334. if (numberOfSides === void 0) { numberOfSides = 32; }
  45335. var result = new Array();
  45336. var angle = 0;
  45337. var increment = (Math.PI * 2) / numberOfSides;
  45338. for (var i = 0; i < numberOfSides; i++) {
  45339. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45340. angle -= increment;
  45341. }
  45342. return result;
  45343. };
  45344. Polygon.Parse = function (input) {
  45345. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45346. var i, result = [];
  45347. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45348. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45349. }
  45350. return result;
  45351. };
  45352. Polygon.StartingAt = function (x, y) {
  45353. return BABYLON.Path2.StartingAt(x, y);
  45354. };
  45355. return Polygon;
  45356. }());
  45357. BABYLON.Polygon = Polygon;
  45358. var PolygonMeshBuilder = (function () {
  45359. function PolygonMeshBuilder(name, contours, scene) {
  45360. this._points = new PolygonPoints();
  45361. this._outlinepoints = new PolygonPoints();
  45362. this._holes = [];
  45363. this._epoints = new Array();
  45364. this._eholes = new Array();
  45365. this._name = name;
  45366. this._scene = scene;
  45367. var points;
  45368. if (contours instanceof BABYLON.Path2) {
  45369. points = contours.getPoints();
  45370. }
  45371. else {
  45372. points = contours;
  45373. }
  45374. this._addToepoint(points);
  45375. this._points.add(points);
  45376. this._outlinepoints.add(points);
  45377. }
  45378. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45379. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45380. var p = points_1[_i];
  45381. this._epoints.push(p.x, p.y);
  45382. }
  45383. };
  45384. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45385. this._points.add(hole);
  45386. var holepoints = new PolygonPoints();
  45387. holepoints.add(hole);
  45388. this._holes.push(holepoints);
  45389. this._eholes.push(this._epoints.length / 2);
  45390. this._addToepoint(hole);
  45391. return this;
  45392. };
  45393. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45394. var _this = this;
  45395. if (updatable === void 0) { updatable = false; }
  45396. var result = new BABYLON.Mesh(this._name, this._scene);
  45397. var normals = [];
  45398. var positions = [];
  45399. var uvs = [];
  45400. var bounds = this._points.computeBounds();
  45401. this._points.elements.forEach(function (p) {
  45402. normals.push(0, 1.0, 0);
  45403. positions.push(p.x, 0, p.y);
  45404. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45405. });
  45406. var indices = [];
  45407. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45408. for (var i = 0; i < res.length; i++) {
  45409. indices.push(res[i]);
  45410. }
  45411. if (depth > 0) {
  45412. var positionscount = (positions.length / 3); //get the current pointcount
  45413. this._points.elements.forEach(function (p) {
  45414. normals.push(0, -1.0, 0);
  45415. positions.push(p.x, -depth, p.y);
  45416. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45417. });
  45418. var totalCount = indices.length;
  45419. for (var i = 0; i < totalCount; i += 3) {
  45420. var i0 = indices[i + 0];
  45421. var i1 = indices[i + 1];
  45422. var i2 = indices[i + 2];
  45423. indices.push(i2 + positionscount);
  45424. indices.push(i1 + positionscount);
  45425. indices.push(i0 + positionscount);
  45426. }
  45427. //Add the sides
  45428. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45429. this._holes.forEach(function (hole) {
  45430. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45431. });
  45432. }
  45433. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45434. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45435. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45436. result.setIndices(indices);
  45437. return result;
  45438. };
  45439. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45440. var StartIndex = positions.length / 3;
  45441. var ulength = 0;
  45442. for (var i = 0; i < points.elements.length; i++) {
  45443. var p = points.elements[i];
  45444. var p1;
  45445. if ((i + 1) > points.elements.length - 1) {
  45446. p1 = points.elements[0];
  45447. }
  45448. else {
  45449. p1 = points.elements[i + 1];
  45450. }
  45451. positions.push(p.x, 0, p.y);
  45452. positions.push(p.x, -depth, p.y);
  45453. positions.push(p1.x, 0, p1.y);
  45454. positions.push(p1.x, -depth, p1.y);
  45455. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45456. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45457. var v3 = v2.subtract(v1);
  45458. var v4 = new BABYLON.Vector3(0, 1, 0);
  45459. var vn = BABYLON.Vector3.Cross(v3, v4);
  45460. vn = vn.normalize();
  45461. uvs.push(ulength / bounds.width, 0);
  45462. uvs.push(ulength / bounds.width, 1);
  45463. ulength += v3.length();
  45464. uvs.push((ulength / bounds.width), 0);
  45465. uvs.push((ulength / bounds.width), 1);
  45466. if (!flip) {
  45467. normals.push(-vn.x, -vn.y, -vn.z);
  45468. normals.push(-vn.x, -vn.y, -vn.z);
  45469. normals.push(-vn.x, -vn.y, -vn.z);
  45470. normals.push(-vn.x, -vn.y, -vn.z);
  45471. indices.push(StartIndex);
  45472. indices.push(StartIndex + 1);
  45473. indices.push(StartIndex + 2);
  45474. indices.push(StartIndex + 1);
  45475. indices.push(StartIndex + 3);
  45476. indices.push(StartIndex + 2);
  45477. }
  45478. else {
  45479. normals.push(vn.x, vn.y, vn.z);
  45480. normals.push(vn.x, vn.y, vn.z);
  45481. normals.push(vn.x, vn.y, vn.z);
  45482. normals.push(vn.x, vn.y, vn.z);
  45483. indices.push(StartIndex);
  45484. indices.push(StartIndex + 2);
  45485. indices.push(StartIndex + 1);
  45486. indices.push(StartIndex + 1);
  45487. indices.push(StartIndex + 2);
  45488. indices.push(StartIndex + 3);
  45489. }
  45490. StartIndex += 4;
  45491. }
  45492. ;
  45493. };
  45494. return PolygonMeshBuilder;
  45495. }());
  45496. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45497. })(BABYLON || (BABYLON = {}));
  45498. //# sourceMappingURL=babylon.polygonMesh.js.map
  45499. var BABYLON;
  45500. (function (BABYLON) {
  45501. var Octree = (function () {
  45502. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45503. if (maxDepth === void 0) { maxDepth = 2; }
  45504. this.maxDepth = maxDepth;
  45505. this.dynamicContent = new Array();
  45506. this._maxBlockCapacity = maxBlockCapacity || 64;
  45507. this._selectionContent = new BABYLON.SmartArray(1024);
  45508. this._creationFunc = creationFunc;
  45509. }
  45510. // Methods
  45511. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45512. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45513. };
  45514. Octree.prototype.addMesh = function (entry) {
  45515. for (var index = 0; index < this.blocks.length; index++) {
  45516. var block = this.blocks[index];
  45517. block.addEntry(entry);
  45518. }
  45519. };
  45520. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45521. this._selectionContent.reset();
  45522. for (var index = 0; index < this.blocks.length; index++) {
  45523. var block = this.blocks[index];
  45524. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45525. }
  45526. if (allowDuplicate) {
  45527. this._selectionContent.concat(this.dynamicContent);
  45528. }
  45529. else {
  45530. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45531. }
  45532. return this._selectionContent;
  45533. };
  45534. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45535. this._selectionContent.reset();
  45536. for (var index = 0; index < this.blocks.length; index++) {
  45537. var block = this.blocks[index];
  45538. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45539. }
  45540. if (allowDuplicate) {
  45541. this._selectionContent.concat(this.dynamicContent);
  45542. }
  45543. else {
  45544. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45545. }
  45546. return this._selectionContent;
  45547. };
  45548. Octree.prototype.intersectsRay = function (ray) {
  45549. this._selectionContent.reset();
  45550. for (var index = 0; index < this.blocks.length; index++) {
  45551. var block = this.blocks[index];
  45552. block.intersectsRay(ray, this._selectionContent);
  45553. }
  45554. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45555. return this._selectionContent;
  45556. };
  45557. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45558. target.blocks = new Array();
  45559. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45560. // Segmenting space
  45561. for (var x = 0; x < 2; x++) {
  45562. for (var y = 0; y < 2; y++) {
  45563. for (var z = 0; z < 2; z++) {
  45564. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45565. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45566. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45567. block.addEntries(entries);
  45568. target.blocks.push(block);
  45569. }
  45570. }
  45571. }
  45572. };
  45573. Octree.CreationFuncForMeshes = function (entry, block) {
  45574. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45575. block.entries.push(entry);
  45576. }
  45577. };
  45578. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45579. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45580. block.entries.push(entry);
  45581. }
  45582. };
  45583. return Octree;
  45584. }());
  45585. BABYLON.Octree = Octree;
  45586. })(BABYLON || (BABYLON = {}));
  45587. //# sourceMappingURL=babylon.octree.js.map
  45588. var BABYLON;
  45589. (function (BABYLON) {
  45590. var OctreeBlock = (function () {
  45591. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45592. this.entries = new Array();
  45593. this._boundingVectors = new Array();
  45594. this._capacity = capacity;
  45595. this._depth = depth;
  45596. this._maxDepth = maxDepth;
  45597. this._creationFunc = creationFunc;
  45598. this._minPoint = minPoint;
  45599. this._maxPoint = maxPoint;
  45600. this._boundingVectors.push(minPoint.clone());
  45601. this._boundingVectors.push(maxPoint.clone());
  45602. this._boundingVectors.push(minPoint.clone());
  45603. this._boundingVectors[2].x = maxPoint.x;
  45604. this._boundingVectors.push(minPoint.clone());
  45605. this._boundingVectors[3].y = maxPoint.y;
  45606. this._boundingVectors.push(minPoint.clone());
  45607. this._boundingVectors[4].z = maxPoint.z;
  45608. this._boundingVectors.push(maxPoint.clone());
  45609. this._boundingVectors[5].z = minPoint.z;
  45610. this._boundingVectors.push(maxPoint.clone());
  45611. this._boundingVectors[6].x = minPoint.x;
  45612. this._boundingVectors.push(maxPoint.clone());
  45613. this._boundingVectors[7].y = minPoint.y;
  45614. }
  45615. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45616. // Property
  45617. get: function () {
  45618. return this._capacity;
  45619. },
  45620. enumerable: true,
  45621. configurable: true
  45622. });
  45623. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45624. get: function () {
  45625. return this._minPoint;
  45626. },
  45627. enumerable: true,
  45628. configurable: true
  45629. });
  45630. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45631. get: function () {
  45632. return this._maxPoint;
  45633. },
  45634. enumerable: true,
  45635. configurable: true
  45636. });
  45637. // Methods
  45638. OctreeBlock.prototype.addEntry = function (entry) {
  45639. if (this.blocks) {
  45640. for (var index = 0; index < this.blocks.length; index++) {
  45641. var block = this.blocks[index];
  45642. block.addEntry(entry);
  45643. }
  45644. return;
  45645. }
  45646. this._creationFunc(entry, this);
  45647. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45648. this.createInnerBlocks();
  45649. }
  45650. };
  45651. OctreeBlock.prototype.addEntries = function (entries) {
  45652. for (var index = 0; index < entries.length; index++) {
  45653. var mesh = entries[index];
  45654. this.addEntry(mesh);
  45655. }
  45656. };
  45657. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45658. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45659. if (this.blocks) {
  45660. for (var index = 0; index < this.blocks.length; index++) {
  45661. var block = this.blocks[index];
  45662. block.select(frustumPlanes, selection, allowDuplicate);
  45663. }
  45664. return;
  45665. }
  45666. if (allowDuplicate) {
  45667. selection.concat(this.entries);
  45668. }
  45669. else {
  45670. selection.concatWithNoDuplicate(this.entries);
  45671. }
  45672. }
  45673. };
  45674. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45675. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45676. if (this.blocks) {
  45677. for (var index = 0; index < this.blocks.length; index++) {
  45678. var block = this.blocks[index];
  45679. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45680. }
  45681. return;
  45682. }
  45683. if (allowDuplicate) {
  45684. selection.concat(this.entries);
  45685. }
  45686. else {
  45687. selection.concatWithNoDuplicate(this.entries);
  45688. }
  45689. }
  45690. };
  45691. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45692. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45693. if (this.blocks) {
  45694. for (var index = 0; index < this.blocks.length; index++) {
  45695. var block = this.blocks[index];
  45696. block.intersectsRay(ray, selection);
  45697. }
  45698. return;
  45699. }
  45700. selection.concatWithNoDuplicate(this.entries);
  45701. }
  45702. };
  45703. OctreeBlock.prototype.createInnerBlocks = function () {
  45704. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45705. };
  45706. return OctreeBlock;
  45707. }());
  45708. BABYLON.OctreeBlock = OctreeBlock;
  45709. })(BABYLON || (BABYLON = {}));
  45710. //# sourceMappingURL=babylon.octreeBlock.js.map
  45711. var BABYLON;
  45712. (function (BABYLON) {
  45713. var BlurPostProcess = (function (_super) {
  45714. __extends(BlurPostProcess, _super);
  45715. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45716. var _this = this;
  45717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45718. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  45719. this.direction = direction;
  45720. this.blurWidth = blurWidth;
  45721. this.onApplyObservable.add(function (effect) {
  45722. effect.setFloat2("screenSize", _this.width, _this.height);
  45723. effect.setVector2("direction", _this.direction);
  45724. effect.setFloat("blurWidth", _this.blurWidth);
  45725. });
  45726. }
  45727. return BlurPostProcess;
  45728. }(BABYLON.PostProcess));
  45729. BABYLON.BlurPostProcess = BlurPostProcess;
  45730. })(BABYLON || (BABYLON = {}));
  45731. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45732. var BABYLON;
  45733. (function (BABYLON) {
  45734. var RefractionPostProcess = (function (_super) {
  45735. __extends(RefractionPostProcess, _super);
  45736. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45737. var _this = this;
  45738. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  45739. this.color = color;
  45740. this.depth = depth;
  45741. this.colorLevel = colorLevel;
  45742. this.onActivateObservable.add(function (cam) {
  45743. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45744. });
  45745. this.onApplyObservable.add(function (effect) {
  45746. effect.setColor3("baseColor", _this.color);
  45747. effect.setFloat("depth", _this.depth);
  45748. effect.setFloat("colorLevel", _this.colorLevel);
  45749. effect.setTexture("refractionSampler", _this._refRexture);
  45750. });
  45751. }
  45752. // Methods
  45753. RefractionPostProcess.prototype.dispose = function (camera) {
  45754. if (this._refRexture) {
  45755. this._refRexture.dispose();
  45756. }
  45757. _super.prototype.dispose.call(this, camera);
  45758. };
  45759. return RefractionPostProcess;
  45760. }(BABYLON.PostProcess));
  45761. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45762. })(BABYLON || (BABYLON = {}));
  45763. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45764. var BABYLON;
  45765. (function (BABYLON) {
  45766. var BlackAndWhitePostProcess = (function (_super) {
  45767. __extends(BlackAndWhitePostProcess, _super);
  45768. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45769. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  45770. }
  45771. return BlackAndWhitePostProcess;
  45772. }(BABYLON.PostProcess));
  45773. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45774. })(BABYLON || (BABYLON = {}));
  45775. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45776. var BABYLON;
  45777. (function (BABYLON) {
  45778. var ConvolutionPostProcess = (function (_super) {
  45779. __extends(ConvolutionPostProcess, _super);
  45780. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45781. var _this = this;
  45782. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  45783. this.kernel = kernel;
  45784. this.onApply = function (effect) {
  45785. effect.setFloat2("screenSize", _this.width, _this.height);
  45786. effect.setArray("kernel", _this.kernel);
  45787. };
  45788. }
  45789. // Statics
  45790. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45791. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45792. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45793. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45794. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45795. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45796. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45797. return ConvolutionPostProcess;
  45798. }(BABYLON.PostProcess));
  45799. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45800. })(BABYLON || (BABYLON = {}));
  45801. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45802. var BABYLON;
  45803. (function (BABYLON) {
  45804. var FilterPostProcess = (function (_super) {
  45805. __extends(FilterPostProcess, _super);
  45806. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45807. var _this = this;
  45808. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  45809. this.kernelMatrix = kernelMatrix;
  45810. this.onApply = function (effect) {
  45811. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45812. };
  45813. }
  45814. return FilterPostProcess;
  45815. }(BABYLON.PostProcess));
  45816. BABYLON.FilterPostProcess = FilterPostProcess;
  45817. })(BABYLON || (BABYLON = {}));
  45818. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45819. var BABYLON;
  45820. (function (BABYLON) {
  45821. var FxaaPostProcess = (function (_super) {
  45822. __extends(FxaaPostProcess, _super);
  45823. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45824. var _this = this;
  45825. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  45826. this.onSizeChangedObservable.add(function () {
  45827. _this.texelWidth = 1.0 / _this.width;
  45828. _this.texelHeight = 1.0 / _this.height;
  45829. });
  45830. this.onApplyObservable.add(function (effect) {
  45831. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45832. });
  45833. }
  45834. return FxaaPostProcess;
  45835. }(BABYLON.PostProcess));
  45836. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45837. })(BABYLON || (BABYLON = {}));
  45838. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45839. var BABYLON;
  45840. (function (BABYLON) {
  45841. var StereoscopicInterlacePostProcess = (function (_super) {
  45842. __extends(StereoscopicInterlacePostProcess, _super);
  45843. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45844. var _this = this;
  45845. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  45846. this._passedProcess = rigCameras[0]._rigPostProcess;
  45847. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  45848. this.onSizeChangedObservable.add(function () {
  45849. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45850. });
  45851. this.onApplyObservable.add(function (effect) {
  45852. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45853. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45854. });
  45855. }
  45856. return StereoscopicInterlacePostProcess;
  45857. }(BABYLON.PostProcess));
  45858. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45859. })(BABYLON || (BABYLON = {}));
  45860. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45861. var BABYLON;
  45862. (function (BABYLON) {
  45863. var LensFlare = (function () {
  45864. function LensFlare(size, position, color, imgUrl, system) {
  45865. this.size = size;
  45866. this.position = position;
  45867. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45868. this.dispose = function () {
  45869. if (this.texture) {
  45870. this.texture.dispose();
  45871. }
  45872. // Remove from scene
  45873. var index = this._system.lensFlares.indexOf(this);
  45874. this._system.lensFlares.splice(index, 1);
  45875. };
  45876. this.color = color || new BABYLON.Color3(1, 1, 1);
  45877. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45878. this._system = system;
  45879. system.lensFlares.push(this);
  45880. }
  45881. return LensFlare;
  45882. }());
  45883. BABYLON.LensFlare = LensFlare;
  45884. })(BABYLON || (BABYLON = {}));
  45885. //# sourceMappingURL=babylon.lensFlare.js.map
  45886. var BABYLON;
  45887. (function (BABYLON) {
  45888. var LensFlareSystem = (function () {
  45889. function LensFlareSystem(name, emitter, scene) {
  45890. this.name = name;
  45891. this.lensFlares = new Array();
  45892. this.borderLimit = 300;
  45893. this.viewportBorder = 0;
  45894. this.layerMask = 0x0FFFFFFF;
  45895. this._vertexBuffers = {};
  45896. this._isEnabled = true;
  45897. this._scene = scene;
  45898. this._emitter = emitter;
  45899. this.id = name;
  45900. scene.lensFlareSystems.push(this);
  45901. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  45902. var engine = scene.getEngine();
  45903. // VBO
  45904. var vertices = [];
  45905. vertices.push(1, 1);
  45906. vertices.push(-1, 1);
  45907. vertices.push(-1, -1);
  45908. vertices.push(1, -1);
  45909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  45910. // Indices
  45911. var indices = [];
  45912. indices.push(0);
  45913. indices.push(1);
  45914. indices.push(2);
  45915. indices.push(0);
  45916. indices.push(2);
  45917. indices.push(3);
  45918. this._indexBuffer = engine.createIndexBuffer(indices);
  45919. // Effects
  45920. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  45921. }
  45922. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  45923. get: function () {
  45924. return this._isEnabled;
  45925. },
  45926. set: function (value) {
  45927. this._isEnabled = value;
  45928. },
  45929. enumerable: true,
  45930. configurable: true
  45931. });
  45932. LensFlareSystem.prototype.getScene = function () {
  45933. return this._scene;
  45934. };
  45935. LensFlareSystem.prototype.getEmitter = function () {
  45936. return this._emitter;
  45937. };
  45938. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  45939. this._emitter = newEmitter;
  45940. };
  45941. LensFlareSystem.prototype.getEmitterPosition = function () {
  45942. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45943. };
  45944. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45945. var position = this.getEmitterPosition();
  45946. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45947. this._positionX = position.x;
  45948. this._positionY = position.y;
  45949. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45950. if (this.viewportBorder > 0) {
  45951. globalViewport.x -= this.viewportBorder;
  45952. globalViewport.y -= this.viewportBorder;
  45953. globalViewport.width += this.viewportBorder * 2;
  45954. globalViewport.height += this.viewportBorder * 2;
  45955. position.x += this.viewportBorder;
  45956. position.y += this.viewportBorder;
  45957. this._positionX += this.viewportBorder;
  45958. this._positionY += this.viewportBorder;
  45959. }
  45960. if (position.z > 0) {
  45961. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  45962. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  45963. return true;
  45964. }
  45965. return true;
  45966. }
  45967. return false;
  45968. };
  45969. LensFlareSystem.prototype._isVisible = function () {
  45970. if (!this._isEnabled) {
  45971. return false;
  45972. }
  45973. var emitterPosition = this.getEmitterPosition();
  45974. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  45975. var distance = direction.length();
  45976. direction.normalize();
  45977. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  45978. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  45979. return !pickInfo.hit || pickInfo.distance > distance;
  45980. };
  45981. LensFlareSystem.prototype.render = function () {
  45982. if (!this._effect.isReady())
  45983. return false;
  45984. var engine = this._scene.getEngine();
  45985. var viewport = this._scene.activeCamera.viewport;
  45986. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  45987. // Position
  45988. if (!this.computeEffectivePosition(globalViewport)) {
  45989. return false;
  45990. }
  45991. // Visibility
  45992. if (!this._isVisible()) {
  45993. return false;
  45994. }
  45995. // Intensity
  45996. var awayX;
  45997. var awayY;
  45998. if (this._positionX < this.borderLimit + globalViewport.x) {
  45999. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46000. }
  46001. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46002. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46003. }
  46004. else {
  46005. awayX = 0;
  46006. }
  46007. if (this._positionY < this.borderLimit + globalViewport.y) {
  46008. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46009. }
  46010. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46011. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46012. }
  46013. else {
  46014. awayY = 0;
  46015. }
  46016. var away = (awayX > awayY) ? awayX : awayY;
  46017. away -= this.viewportBorder;
  46018. if (away > this.borderLimit) {
  46019. away = this.borderLimit;
  46020. }
  46021. var intensity = 1.0 - (away / this.borderLimit);
  46022. if (intensity < 0) {
  46023. return false;
  46024. }
  46025. if (intensity > 1.0) {
  46026. intensity = 1.0;
  46027. }
  46028. if (this.viewportBorder > 0) {
  46029. globalViewport.x += this.viewportBorder;
  46030. globalViewport.y += this.viewportBorder;
  46031. globalViewport.width -= this.viewportBorder * 2;
  46032. globalViewport.height -= this.viewportBorder * 2;
  46033. this._positionX -= this.viewportBorder;
  46034. this._positionY -= this.viewportBorder;
  46035. }
  46036. // Position
  46037. var centerX = globalViewport.x + globalViewport.width / 2;
  46038. var centerY = globalViewport.y + globalViewport.height / 2;
  46039. var distX = centerX - this._positionX;
  46040. var distY = centerY - this._positionY;
  46041. // Effects
  46042. engine.enableEffect(this._effect);
  46043. engine.setState(false);
  46044. engine.setDepthBuffer(false);
  46045. // VBOs
  46046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46047. // Flares
  46048. for (var index = 0; index < this.lensFlares.length; index++) {
  46049. var flare = this.lensFlares[index];
  46050. engine.setAlphaMode(flare.alphaMode);
  46051. var x = centerX - (distX * flare.position);
  46052. var y = centerY - (distY * flare.position);
  46053. var cw = flare.size;
  46054. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46055. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46056. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46057. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46058. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46059. // Texture
  46060. this._effect.setTexture("textureSampler", flare.texture);
  46061. // Color
  46062. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46063. // Draw order
  46064. engine.draw(true, 0, 6);
  46065. }
  46066. engine.setDepthBuffer(true);
  46067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46068. return true;
  46069. };
  46070. LensFlareSystem.prototype.dispose = function () {
  46071. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46072. if (vertexBuffer) {
  46073. vertexBuffer.dispose();
  46074. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46075. }
  46076. if (this._indexBuffer) {
  46077. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46078. this._indexBuffer = null;
  46079. }
  46080. while (this.lensFlares.length) {
  46081. this.lensFlares[0].dispose();
  46082. }
  46083. // Remove from scene
  46084. var index = this._scene.lensFlareSystems.indexOf(this);
  46085. this._scene.lensFlareSystems.splice(index, 1);
  46086. };
  46087. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46088. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46089. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46090. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46091. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46092. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46093. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46094. var parsedFlare = parsedLensFlareSystem.flares[index];
  46095. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46096. }
  46097. return lensFlareSystem;
  46098. };
  46099. LensFlareSystem.prototype.serialize = function () {
  46100. var serializationObject = {};
  46101. serializationObject.id = this.id;
  46102. serializationObject.name = this.name;
  46103. serializationObject.emitterId = this.getEmitter().id;
  46104. serializationObject.borderLimit = this.borderLimit;
  46105. serializationObject.flares = [];
  46106. for (var index = 0; index < this.lensFlares.length; index++) {
  46107. var flare = this.lensFlares[index];
  46108. serializationObject.flares.push({
  46109. size: flare.size,
  46110. position: flare.position,
  46111. color: flare.color.asArray(),
  46112. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46113. });
  46114. }
  46115. return serializationObject;
  46116. };
  46117. return LensFlareSystem;
  46118. }());
  46119. BABYLON.LensFlareSystem = LensFlareSystem;
  46120. })(BABYLON || (BABYLON = {}));
  46121. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46122. var BABYLON;
  46123. (function (BABYLON) {
  46124. // We're mainly based on the logic defined into the FreeCamera code
  46125. var DeviceOrientationCamera = (function (_super) {
  46126. __extends(DeviceOrientationCamera, _super);
  46127. function DeviceOrientationCamera(name, position, scene) {
  46128. _super.call(this, name, position, scene);
  46129. this._quaternionCache = new BABYLON.Quaternion();
  46130. this.inputs.addDeviceOrientation();
  46131. }
  46132. DeviceOrientationCamera.prototype.getClassName = function () {
  46133. return "DeviceOrientationCamera";
  46134. };
  46135. DeviceOrientationCamera.prototype._checkInputs = function () {
  46136. _super.prototype._checkInputs.call(this);
  46137. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46138. if (this._initialQuaternion) {
  46139. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46140. }
  46141. };
  46142. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46143. var _this = this;
  46144. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46145. //can only work if this camera has a rotation quaternion already.
  46146. if (!this.rotationQuaternion)
  46147. return;
  46148. if (!this._initialQuaternion) {
  46149. this._initialQuaternion = new BABYLON.Quaternion();
  46150. }
  46151. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46152. ['x', 'y', 'z'].forEach(function (axisName) {
  46153. if (!axis[axisName]) {
  46154. _this._initialQuaternion[axisName] = 0;
  46155. }
  46156. else {
  46157. _this._initialQuaternion[axisName] *= -1;
  46158. }
  46159. });
  46160. this._initialQuaternion.normalize();
  46161. //force rotation update
  46162. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46163. };
  46164. return DeviceOrientationCamera;
  46165. }(BABYLON.FreeCamera));
  46166. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46167. })(BABYLON || (BABYLON = {}));
  46168. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46169. var BABYLON;
  46170. (function (BABYLON) {
  46171. var VRDeviceOrientationFreeCamera = (function (_super) {
  46172. __extends(VRDeviceOrientationFreeCamera, _super);
  46173. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46174. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46175. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46176. _super.call(this, name, position, scene);
  46177. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46178. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46179. }
  46180. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46181. return "VRDeviceOrientationFreeCamera";
  46182. };
  46183. return VRDeviceOrientationFreeCamera;
  46184. }(BABYLON.DeviceOrientationCamera));
  46185. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46186. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46187. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46188. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46189. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46190. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46191. _super.call(this, name, alpha, beta, radius, target, scene);
  46192. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46193. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46194. this.inputs.addVRDeviceOrientation();
  46195. }
  46196. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46197. return "VRDeviceOrientationArcRotateCamera";
  46198. };
  46199. return VRDeviceOrientationArcRotateCamera;
  46200. }(BABYLON.ArcRotateCamera));
  46201. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46202. })(BABYLON || (BABYLON = {}));
  46203. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46204. var BABYLON;
  46205. (function (BABYLON) {
  46206. // We're mainly based on the logic defined into the FreeCamera code
  46207. var UniversalCamera = (function (_super) {
  46208. __extends(UniversalCamera, _super);
  46209. //-- end properties for backward compatibility for inputs
  46210. function UniversalCamera(name, position, scene) {
  46211. _super.call(this, name, position, scene);
  46212. this.inputs.addGamepad();
  46213. }
  46214. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46215. //-- Begin properties for backward compatibility for inputs
  46216. get: function () {
  46217. var gamepad = this.inputs.attached["gamepad"];
  46218. if (gamepad)
  46219. return gamepad.gamepadAngularSensibility;
  46220. },
  46221. set: function (value) {
  46222. var gamepad = this.inputs.attached["gamepad"];
  46223. if (gamepad)
  46224. gamepad.gamepadAngularSensibility = value;
  46225. },
  46226. enumerable: true,
  46227. configurable: true
  46228. });
  46229. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46230. get: function () {
  46231. var gamepad = this.inputs.attached["gamepad"];
  46232. if (gamepad)
  46233. return gamepad.gamepadMoveSensibility;
  46234. },
  46235. set: function (value) {
  46236. var gamepad = this.inputs.attached["gamepad"];
  46237. if (gamepad)
  46238. gamepad.gamepadMoveSensibility = value;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. UniversalCamera.prototype.getClassName = function () {
  46244. return "UniversalCamera";
  46245. };
  46246. return UniversalCamera;
  46247. }(BABYLON.TouchCamera));
  46248. BABYLON.UniversalCamera = UniversalCamera;
  46249. })(BABYLON || (BABYLON = {}));
  46250. //# sourceMappingURL=babylon.universalCamera.js.map
  46251. var BABYLON;
  46252. (function (BABYLON) {
  46253. var Gamepads = (function () {
  46254. function Gamepads(ongamedpadconnected) {
  46255. var _this = this;
  46256. this.babylonGamepads = [];
  46257. this.oneGamepadConnected = false;
  46258. this.isMonitoring = false;
  46259. this.gamepadEventSupported = 'GamepadEvent' in window;
  46260. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46261. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46262. this._callbackGamepadConnected = ongamedpadconnected;
  46263. if (this.gamepadSupportAvailable) {
  46264. // Checking if the gamepad connected event is supported (like in Firefox)
  46265. if (this.gamepadEventSupported) {
  46266. this._onGamepadConnectedEvent = function (evt) {
  46267. _this._onGamepadConnected(evt);
  46268. };
  46269. this._onGamepadDisonnectedEvent = function (evt) {
  46270. _this._onGamepadDisconnected(evt);
  46271. };
  46272. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46273. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46274. }
  46275. else {
  46276. this._startMonitoringGamepads();
  46277. }
  46278. }
  46279. }
  46280. Gamepads.prototype.dispose = function () {
  46281. if (Gamepads.gamepadDOMInfo) {
  46282. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46283. }
  46284. if (this._onGamepadConnectedEvent) {
  46285. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46286. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46287. this._onGamepadConnectedEvent = null;
  46288. this._onGamepadDisonnectedEvent = null;
  46289. }
  46290. };
  46291. Gamepads.prototype._onGamepadConnected = function (evt) {
  46292. var newGamepad = this._addNewGamepad(evt.gamepad);
  46293. if (this._callbackGamepadConnected)
  46294. this._callbackGamepadConnected(newGamepad);
  46295. this._startMonitoringGamepads();
  46296. };
  46297. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46298. if (!this.oneGamepadConnected) {
  46299. this.oneGamepadConnected = true;
  46300. if (Gamepads.gamepadDOMInfo) {
  46301. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46302. Gamepads.gamepadDOMInfo = null;
  46303. }
  46304. }
  46305. var newGamepad;
  46306. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46307. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46308. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46309. }
  46310. else {
  46311. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46312. }
  46313. this.babylonGamepads.push(newGamepad);
  46314. return newGamepad;
  46315. };
  46316. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46317. // Remove the gamepad from the list of gamepads to monitor.
  46318. for (var i in this.babylonGamepads) {
  46319. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46320. this.babylonGamepads.splice(+i, 1);
  46321. break;
  46322. }
  46323. }
  46324. // If no gamepads are left, stop the polling loop.
  46325. if (this.babylonGamepads.length == 0) {
  46326. this._stopMonitoringGamepads();
  46327. }
  46328. };
  46329. Gamepads.prototype._startMonitoringGamepads = function () {
  46330. if (!this.isMonitoring) {
  46331. this.isMonitoring = true;
  46332. this._checkGamepadsStatus();
  46333. }
  46334. };
  46335. Gamepads.prototype._stopMonitoringGamepads = function () {
  46336. this.isMonitoring = false;
  46337. };
  46338. Gamepads.prototype._checkGamepadsStatus = function () {
  46339. var _this = this;
  46340. // updating gamepad objects
  46341. this._updateGamepadObjects();
  46342. for (var i in this.babylonGamepads) {
  46343. this.babylonGamepads[i].update();
  46344. }
  46345. if (this.isMonitoring) {
  46346. if (window.requestAnimationFrame) {
  46347. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46348. }
  46349. else if (window.mozRequestAnimationFrame) {
  46350. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46351. }
  46352. else if (window.webkitRequestAnimationFrame) {
  46353. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46354. }
  46355. }
  46356. };
  46357. // This function is called only on Chrome, which does not yet support
  46358. // connection/disconnection events, but requires you to monitor
  46359. // an array for changes.
  46360. Gamepads.prototype._updateGamepadObjects = function () {
  46361. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46362. for (var i = 0; i < gamepads.length; i++) {
  46363. if (gamepads[i]) {
  46364. if (!(gamepads[i].index in this.babylonGamepads)) {
  46365. var newGamepad = this._addNewGamepad(gamepads[i]);
  46366. if (this._callbackGamepadConnected) {
  46367. this._callbackGamepadConnected(newGamepad);
  46368. }
  46369. }
  46370. else {
  46371. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46372. }
  46373. }
  46374. }
  46375. };
  46376. return Gamepads;
  46377. }());
  46378. BABYLON.Gamepads = Gamepads;
  46379. var StickValues = (function () {
  46380. function StickValues(x, y) {
  46381. this.x = x;
  46382. this.y = y;
  46383. }
  46384. return StickValues;
  46385. }());
  46386. BABYLON.StickValues = StickValues;
  46387. var Gamepad = (function () {
  46388. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46389. if (leftStickX === void 0) { leftStickX = 0; }
  46390. if (leftStickY === void 0) { leftStickY = 1; }
  46391. if (rightStickX === void 0) { rightStickX = 2; }
  46392. if (rightStickY === void 0) { rightStickY = 3; }
  46393. this.id = id;
  46394. this.index = index;
  46395. this.browserGamepad = browserGamepad;
  46396. this._leftStickAxisX = leftStickX;
  46397. this._leftStickAxisY = leftStickY;
  46398. this._rightStickAxisX = rightStickX;
  46399. this._rightStickAxisY = rightStickY;
  46400. if (this.browserGamepad.axes.length >= 2) {
  46401. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46402. }
  46403. if (this.browserGamepad.axes.length >= 4) {
  46404. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46405. }
  46406. }
  46407. Gamepad.prototype.onleftstickchanged = function (callback) {
  46408. this._onleftstickchanged = callback;
  46409. };
  46410. Gamepad.prototype.onrightstickchanged = function (callback) {
  46411. this._onrightstickchanged = callback;
  46412. };
  46413. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46414. get: function () {
  46415. return this._leftStick;
  46416. },
  46417. set: function (newValues) {
  46418. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46419. this._onleftstickchanged(newValues);
  46420. }
  46421. this._leftStick = newValues;
  46422. },
  46423. enumerable: true,
  46424. configurable: true
  46425. });
  46426. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46427. get: function () {
  46428. return this._rightStick;
  46429. },
  46430. set: function (newValues) {
  46431. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46432. this._onrightstickchanged(newValues);
  46433. }
  46434. this._rightStick = newValues;
  46435. },
  46436. enumerable: true,
  46437. configurable: true
  46438. });
  46439. Gamepad.prototype.update = function () {
  46440. if (this._leftStick) {
  46441. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46442. }
  46443. if (this._rightStick) {
  46444. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46445. }
  46446. };
  46447. return Gamepad;
  46448. }());
  46449. BABYLON.Gamepad = Gamepad;
  46450. var GenericPad = (function (_super) {
  46451. __extends(GenericPad, _super);
  46452. function GenericPad(id, index, gamepad) {
  46453. _super.call(this, id, index, gamepad);
  46454. this.id = id;
  46455. this.index = index;
  46456. this.gamepad = gamepad;
  46457. this._buttons = new Array(gamepad.buttons.length);
  46458. }
  46459. GenericPad.prototype.onbuttondown = function (callback) {
  46460. this._onbuttondown = callback;
  46461. };
  46462. GenericPad.prototype.onbuttonup = function (callback) {
  46463. this._onbuttonup = callback;
  46464. };
  46465. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46466. if (newValue !== currentValue) {
  46467. if (this._onbuttondown && newValue === 1) {
  46468. this._onbuttondown(buttonIndex);
  46469. }
  46470. if (this._onbuttonup && newValue === 0) {
  46471. this._onbuttonup(buttonIndex);
  46472. }
  46473. }
  46474. return newValue;
  46475. };
  46476. GenericPad.prototype.update = function () {
  46477. _super.prototype.update.call(this);
  46478. for (var index = 0; index < this._buttons.length; index++) {
  46479. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46480. }
  46481. };
  46482. return GenericPad;
  46483. }(Gamepad));
  46484. BABYLON.GenericPad = GenericPad;
  46485. (function (Xbox360Button) {
  46486. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46487. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46488. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46489. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46490. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46491. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46492. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46493. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46494. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46495. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46496. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46497. var Xbox360Button = BABYLON.Xbox360Button;
  46498. (function (Xbox360Dpad) {
  46499. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46500. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46501. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46502. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46503. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46504. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46505. var Xbox360Pad = (function (_super) {
  46506. __extends(Xbox360Pad, _super);
  46507. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46508. if (xboxOne === void 0) { xboxOne = false; }
  46509. _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3));
  46510. this._leftTrigger = 0;
  46511. this._rightTrigger = 0;
  46512. this._buttonA = 0;
  46513. this._buttonB = 0;
  46514. this._buttonX = 0;
  46515. this._buttonY = 0;
  46516. this._buttonBack = 0;
  46517. this._buttonStart = 0;
  46518. this._buttonLB = 0;
  46519. this._buttonRB = 0;
  46520. this._buttonLeftStick = 0;
  46521. this._buttonRightStick = 0;
  46522. this._dPadUp = 0;
  46523. this._dPadDown = 0;
  46524. this._dPadLeft = 0;
  46525. this._dPadRight = 0;
  46526. this._isXboxOnePad = false;
  46527. this._isXboxOnePad = xboxOne;
  46528. }
  46529. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46530. this._onlefttriggerchanged = callback;
  46531. };
  46532. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46533. this._onrighttriggerchanged = callback;
  46534. };
  46535. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46536. get: function () {
  46537. return this._leftTrigger;
  46538. },
  46539. set: function (newValue) {
  46540. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46541. this._onlefttriggerchanged(newValue);
  46542. }
  46543. this._leftTrigger = newValue;
  46544. },
  46545. enumerable: true,
  46546. configurable: true
  46547. });
  46548. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46549. get: function () {
  46550. return this._rightTrigger;
  46551. },
  46552. set: function (newValue) {
  46553. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46554. this._onrighttriggerchanged(newValue);
  46555. }
  46556. this._rightTrigger = newValue;
  46557. },
  46558. enumerable: true,
  46559. configurable: true
  46560. });
  46561. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46562. this._onbuttondown = callback;
  46563. };
  46564. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46565. this._onbuttonup = callback;
  46566. };
  46567. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46568. this._ondpaddown = callback;
  46569. };
  46570. Xbox360Pad.prototype.ondpadup = function (callback) {
  46571. this._ondpadup = callback;
  46572. };
  46573. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46574. if (newValue !== currentValue) {
  46575. if (this._onbuttondown && newValue === 1) {
  46576. this._onbuttondown(buttonType);
  46577. }
  46578. if (this._onbuttonup && newValue === 0) {
  46579. this._onbuttonup(buttonType);
  46580. }
  46581. }
  46582. return newValue;
  46583. };
  46584. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46585. if (newValue !== currentValue) {
  46586. if (this._ondpaddown && newValue === 1) {
  46587. this._ondpaddown(buttonType);
  46588. }
  46589. if (this._ondpadup && newValue === 0) {
  46590. this._ondpadup(buttonType);
  46591. }
  46592. }
  46593. return newValue;
  46594. };
  46595. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46596. get: function () {
  46597. return this._buttonA;
  46598. },
  46599. set: function (value) {
  46600. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46601. },
  46602. enumerable: true,
  46603. configurable: true
  46604. });
  46605. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46606. get: function () {
  46607. return this._buttonB;
  46608. },
  46609. set: function (value) {
  46610. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46616. get: function () {
  46617. return this._buttonX;
  46618. },
  46619. set: function (value) {
  46620. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46621. },
  46622. enumerable: true,
  46623. configurable: true
  46624. });
  46625. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46626. get: function () {
  46627. return this._buttonY;
  46628. },
  46629. set: function (value) {
  46630. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46631. },
  46632. enumerable: true,
  46633. configurable: true
  46634. });
  46635. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46636. get: function () {
  46637. return this._buttonStart;
  46638. },
  46639. set: function (value) {
  46640. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46641. },
  46642. enumerable: true,
  46643. configurable: true
  46644. });
  46645. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46646. get: function () {
  46647. return this._buttonBack;
  46648. },
  46649. set: function (value) {
  46650. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46651. },
  46652. enumerable: true,
  46653. configurable: true
  46654. });
  46655. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46656. get: function () {
  46657. return this._buttonLB;
  46658. },
  46659. set: function (value) {
  46660. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46661. },
  46662. enumerable: true,
  46663. configurable: true
  46664. });
  46665. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46666. get: function () {
  46667. return this._buttonRB;
  46668. },
  46669. set: function (value) {
  46670. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46671. },
  46672. enumerable: true,
  46673. configurable: true
  46674. });
  46675. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46676. get: function () {
  46677. return this._buttonLeftStick;
  46678. },
  46679. set: function (value) {
  46680. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46681. },
  46682. enumerable: true,
  46683. configurable: true
  46684. });
  46685. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46686. get: function () {
  46687. return this._buttonRightStick;
  46688. },
  46689. set: function (value) {
  46690. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46691. },
  46692. enumerable: true,
  46693. configurable: true
  46694. });
  46695. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46696. get: function () {
  46697. return this._dPadUp;
  46698. },
  46699. set: function (value) {
  46700. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46701. },
  46702. enumerable: true,
  46703. configurable: true
  46704. });
  46705. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46706. get: function () {
  46707. return this._dPadDown;
  46708. },
  46709. set: function (value) {
  46710. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46711. },
  46712. enumerable: true,
  46713. configurable: true
  46714. });
  46715. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46716. get: function () {
  46717. return this._dPadLeft;
  46718. },
  46719. set: function (value) {
  46720. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46726. get: function () {
  46727. return this._dPadRight;
  46728. },
  46729. set: function (value) {
  46730. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46731. },
  46732. enumerable: true,
  46733. configurable: true
  46734. });
  46735. Xbox360Pad.prototype.update = function () {
  46736. _super.prototype.update.call(this);
  46737. if (this._isXboxOnePad) {
  46738. this.buttonA = this.browserGamepad.buttons[0].value;
  46739. this.buttonB = this.browserGamepad.buttons[1].value;
  46740. this.buttonX = this.browserGamepad.buttons[2].value;
  46741. this.buttonY = this.browserGamepad.buttons[3].value;
  46742. this.buttonLB = this.browserGamepad.buttons[4].value;
  46743. this.buttonRB = this.browserGamepad.buttons[5].value;
  46744. this.leftTrigger = this.browserGamepad.axes[2];
  46745. this.rightTrigger = this.browserGamepad.axes[5];
  46746. this.buttonBack = this.browserGamepad.buttons[9].value;
  46747. this.buttonStart = this.browserGamepad.buttons[8].value;
  46748. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46749. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46750. this.dPadUp = this.browserGamepad.buttons[11].value;
  46751. this.dPadDown = this.browserGamepad.buttons[12].value;
  46752. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46753. this.dPadRight = this.browserGamepad.buttons[14].value;
  46754. }
  46755. else {
  46756. this.buttonA = this.browserGamepad.buttons[0].value;
  46757. this.buttonB = this.browserGamepad.buttons[1].value;
  46758. this.buttonX = this.browserGamepad.buttons[2].value;
  46759. this.buttonY = this.browserGamepad.buttons[3].value;
  46760. this.buttonLB = this.browserGamepad.buttons[4].value;
  46761. this.buttonRB = this.browserGamepad.buttons[5].value;
  46762. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46763. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46764. this.buttonBack = this.browserGamepad.buttons[8].value;
  46765. this.buttonStart = this.browserGamepad.buttons[9].value;
  46766. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46767. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46768. this.dPadUp = this.browserGamepad.buttons[12].value;
  46769. this.dPadDown = this.browserGamepad.buttons[13].value;
  46770. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46771. this.dPadRight = this.browserGamepad.buttons[15].value;
  46772. }
  46773. };
  46774. return Xbox360Pad;
  46775. }(Gamepad));
  46776. BABYLON.Xbox360Pad = Xbox360Pad;
  46777. })(BABYLON || (BABYLON = {}));
  46778. //# sourceMappingURL=babylon.gamepads.js.map
  46779. var BABYLON;
  46780. (function (BABYLON) {
  46781. // We're mainly based on the logic defined into the FreeCamera code
  46782. var GamepadCamera = (function (_super) {
  46783. __extends(GamepadCamera, _super);
  46784. //-- end properties for backward compatibility for inputs
  46785. function GamepadCamera(name, position, scene) {
  46786. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46787. _super.call(this, name, position, scene);
  46788. }
  46789. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46790. //-- Begin properties for backward compatibility for inputs
  46791. get: function () {
  46792. var gamepad = this.inputs.attached["gamepad"];
  46793. if (gamepad)
  46794. return gamepad.gamepadAngularSensibility;
  46795. },
  46796. set: function (value) {
  46797. var gamepad = this.inputs.attached["gamepad"];
  46798. if (gamepad)
  46799. gamepad.gamepadAngularSensibility = value;
  46800. },
  46801. enumerable: true,
  46802. configurable: true
  46803. });
  46804. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46805. get: function () {
  46806. var gamepad = this.inputs.attached["gamepad"];
  46807. if (gamepad)
  46808. return gamepad.gamepadMoveSensibility;
  46809. },
  46810. set: function (value) {
  46811. var gamepad = this.inputs.attached["gamepad"];
  46812. if (gamepad)
  46813. gamepad.gamepadMoveSensibility = value;
  46814. },
  46815. enumerable: true,
  46816. configurable: true
  46817. });
  46818. GamepadCamera.prototype.getClassName = function () {
  46819. return "GamepadCamera";
  46820. };
  46821. return GamepadCamera;
  46822. }(BABYLON.UniversalCamera));
  46823. BABYLON.GamepadCamera = GamepadCamera;
  46824. })(BABYLON || (BABYLON = {}));
  46825. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46826. var BABYLON;
  46827. (function (BABYLON) {
  46828. var Analyser = (function () {
  46829. function Analyser(scene) {
  46830. this.SMOOTHING = 0.75;
  46831. this.FFT_SIZE = 512;
  46832. this.BARGRAPHAMPLITUDE = 256;
  46833. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46834. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46835. this._scene = scene;
  46836. this._audioEngine = BABYLON.Engine.audioEngine;
  46837. if (this._audioEngine.canUseWebAudio) {
  46838. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46839. this._webAudioAnalyser.minDecibels = -140;
  46840. this._webAudioAnalyser.maxDecibels = 0;
  46841. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46842. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46843. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46844. }
  46845. }
  46846. Analyser.prototype.getFrequencyBinCount = function () {
  46847. if (this._audioEngine.canUseWebAudio) {
  46848. return this._webAudioAnalyser.frequencyBinCount;
  46849. }
  46850. else {
  46851. return 0;
  46852. }
  46853. };
  46854. Analyser.prototype.getByteFrequencyData = function () {
  46855. if (this._audioEngine.canUseWebAudio) {
  46856. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46857. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46858. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46859. }
  46860. return this._byteFreqs;
  46861. };
  46862. Analyser.prototype.getByteTimeDomainData = function () {
  46863. if (this._audioEngine.canUseWebAudio) {
  46864. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46865. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46866. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46867. }
  46868. return this._byteTime;
  46869. };
  46870. Analyser.prototype.getFloatFrequencyData = function () {
  46871. if (this._audioEngine.canUseWebAudio) {
  46872. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46873. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46874. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46875. }
  46876. return this._floatFreqs;
  46877. };
  46878. Analyser.prototype.drawDebugCanvas = function () {
  46879. var _this = this;
  46880. if (this._audioEngine.canUseWebAudio) {
  46881. if (!this._debugCanvas) {
  46882. this._debugCanvas = document.createElement("canvas");
  46883. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46884. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46885. this._debugCanvas.style.position = "absolute";
  46886. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46887. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46888. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46889. document.body.appendChild(this._debugCanvas);
  46890. this._registerFunc = function () {
  46891. _this.drawDebugCanvas();
  46892. };
  46893. this._scene.registerBeforeRender(this._registerFunc);
  46894. }
  46895. if (this._registerFunc) {
  46896. var workingArray = this.getByteFrequencyData();
  46897. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46898. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46899. // Draw the frequency domain chart.
  46900. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46901. var value = workingArray[i];
  46902. var percent = value / this.BARGRAPHAMPLITUDE;
  46903. var height = this.DEBUGCANVASSIZE.height * percent;
  46904. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46905. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46906. var hue = i / this.getFrequencyBinCount() * 360;
  46907. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46908. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46909. }
  46910. }
  46911. }
  46912. };
  46913. Analyser.prototype.stopDebugCanvas = function () {
  46914. if (this._debugCanvas) {
  46915. this._scene.unregisterBeforeRender(this._registerFunc);
  46916. this._registerFunc = null;
  46917. document.body.removeChild(this._debugCanvas);
  46918. this._debugCanvas = null;
  46919. this._debugCanvasContext = null;
  46920. }
  46921. };
  46922. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46923. if (this._audioEngine.canUseWebAudio) {
  46924. inputAudioNode.connect(this._webAudioAnalyser);
  46925. this._webAudioAnalyser.connect(outputAudioNode);
  46926. }
  46927. };
  46928. Analyser.prototype.dispose = function () {
  46929. if (this._audioEngine.canUseWebAudio) {
  46930. this._webAudioAnalyser.disconnect();
  46931. }
  46932. };
  46933. return Analyser;
  46934. }());
  46935. BABYLON.Analyser = Analyser;
  46936. })(BABYLON || (BABYLON = {}));
  46937. //# sourceMappingURL=babylon.analyser.js.map
  46938. var BABYLON;
  46939. (function (BABYLON) {
  46940. var DepthRenderer = (function () {
  46941. function DepthRenderer(scene, type) {
  46942. var _this = this;
  46943. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46944. this._viewMatrix = BABYLON.Matrix.Zero();
  46945. this._projectionMatrix = BABYLON.Matrix.Zero();
  46946. this._transformMatrix = BABYLON.Matrix.Zero();
  46947. this._worldViewProjection = BABYLON.Matrix.Zero();
  46948. this._scene = scene;
  46949. var engine = scene.getEngine();
  46950. // Render target
  46951. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46952. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46953. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46954. this._depthMap.refreshRate = 1;
  46955. this._depthMap.renderParticles = false;
  46956. this._depthMap.renderList = null;
  46957. // set default depth value to 1.0 (far away)
  46958. this._depthMap.onClearObservable.add(function (engine) {
  46959. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46960. });
  46961. // Custom render function
  46962. var renderSubMesh = function (subMesh) {
  46963. var mesh = subMesh.getRenderingMesh();
  46964. var scene = _this._scene;
  46965. var engine = scene.getEngine();
  46966. // Culling
  46967. engine.setState(subMesh.getMaterial().backFaceCulling);
  46968. // Managing instances
  46969. var batch = mesh._getInstancesRenderList(subMesh._id);
  46970. if (batch.mustReturn) {
  46971. return;
  46972. }
  46973. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46974. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46975. engine.enableEffect(_this._effect);
  46976. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46977. var material = subMesh.getMaterial();
  46978. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46979. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46980. // Alpha test
  46981. if (material && material.needAlphaTesting()) {
  46982. var alphaTexture = material.getAlphaTestTexture();
  46983. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46984. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46985. }
  46986. // Bones
  46987. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46989. }
  46990. // Draw
  46991. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46992. }
  46993. };
  46994. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46995. var index;
  46996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46997. renderSubMesh(opaqueSubMeshes.data[index]);
  46998. }
  46999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47000. renderSubMesh(alphaTestSubMeshes.data[index]);
  47001. }
  47002. };
  47003. }
  47004. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47005. var material = subMesh.getMaterial();
  47006. if (material.disableDepthWrite) {
  47007. return false;
  47008. }
  47009. var defines = [];
  47010. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47011. var mesh = subMesh.getMesh();
  47012. var scene = mesh.getScene();
  47013. // Alpha test
  47014. if (material && material.needAlphaTesting()) {
  47015. defines.push("#define ALPHATEST");
  47016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47017. attribs.push(BABYLON.VertexBuffer.UVKind);
  47018. defines.push("#define UV1");
  47019. }
  47020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47022. defines.push("#define UV2");
  47023. }
  47024. }
  47025. // Bones
  47026. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47029. if (mesh.numBoneInfluencers > 4) {
  47030. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47031. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47032. }
  47033. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47034. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47035. }
  47036. else {
  47037. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47038. }
  47039. // Instances
  47040. if (useInstances) {
  47041. defines.push("#define INSTANCES");
  47042. attribs.push("world0");
  47043. attribs.push("world1");
  47044. attribs.push("world2");
  47045. attribs.push("world3");
  47046. }
  47047. // Get correct effect
  47048. var join = defines.join("\n");
  47049. if (this._cachedDefines !== join) {
  47050. this._cachedDefines = join;
  47051. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47052. }
  47053. return this._effect.isReady();
  47054. };
  47055. DepthRenderer.prototype.getDepthMap = function () {
  47056. return this._depthMap;
  47057. };
  47058. // Methods
  47059. DepthRenderer.prototype.dispose = function () {
  47060. this._depthMap.dispose();
  47061. };
  47062. return DepthRenderer;
  47063. }());
  47064. BABYLON.DepthRenderer = DepthRenderer;
  47065. })(BABYLON || (BABYLON = {}));
  47066. //# sourceMappingURL=babylon.depthRenderer.js.map
  47067. var BABYLON;
  47068. (function (BABYLON) {
  47069. var SSAORenderingPipeline = (function (_super) {
  47070. __extends(SSAORenderingPipeline, _super);
  47071. /**
  47072. * @constructor
  47073. * @param {string} name - The rendering pipeline name
  47074. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47075. * @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 }
  47076. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47077. */
  47078. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47079. var _this = this;
  47080. _super.call(this, scene.getEngine(), name);
  47081. // Members
  47082. /**
  47083. * The PassPostProcess id in the pipeline that contains the original scene color
  47084. * @type {string}
  47085. */
  47086. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47087. /**
  47088. * The SSAO PostProcess id in the pipeline
  47089. * @type {string}
  47090. */
  47091. this.SSAORenderEffect = "SSAORenderEffect";
  47092. /**
  47093. * The horizontal blur PostProcess id in the pipeline
  47094. * @type {string}
  47095. */
  47096. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47097. /**
  47098. * The vertical blur PostProcess id in the pipeline
  47099. * @type {string}
  47100. */
  47101. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47102. /**
  47103. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47104. * @type {string}
  47105. */
  47106. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47107. /**
  47108. * The output strength of the SSAO post-process. Default value is 1.0.
  47109. * @type {number}
  47110. */
  47111. this.totalStrength = 1.0;
  47112. /**
  47113. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47114. * @type {number}
  47115. */
  47116. this.radius = 0.0001;
  47117. /**
  47118. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47119. * Must not be equal to fallOff and superior to fallOff.
  47120. * Default value is 0.975
  47121. * @type {number}
  47122. */
  47123. this.area = 0.0075;
  47124. /**
  47125. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47126. * Must not be equal to area and inferior to area.
  47127. * Default value is 0.0
  47128. * @type {number}
  47129. */
  47130. this.fallOff = 0.000001;
  47131. /**
  47132. * The base color of the SSAO post-process
  47133. * The final result is "base + ssao" between [0, 1]
  47134. * @type {number}
  47135. */
  47136. this.base = 0.5;
  47137. this._firstUpdate = true;
  47138. this._scene = scene;
  47139. // Set up assets
  47140. this._createRandomTexture();
  47141. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47142. var ssaoRatio = ratio.ssaoRatio || ratio;
  47143. var combineRatio = ratio.combineRatio || ratio;
  47144. this._ratio = {
  47145. ssaoRatio: ssaoRatio,
  47146. combineRatio: combineRatio
  47147. };
  47148. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47149. this._createSSAOPostProcess(ssaoRatio);
  47150. this._createBlurPostProcess(ssaoRatio);
  47151. this._createSSAOCombinePostProcess(combineRatio);
  47152. // Set up pipeline
  47153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47158. // Finish
  47159. scene.postProcessRenderPipelineManager.addPipeline(this);
  47160. if (cameras)
  47161. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47162. }
  47163. // Public Methods
  47164. /**
  47165. * Returns the horizontal blur PostProcess
  47166. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47167. */
  47168. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47169. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47170. return null;
  47171. };
  47172. /**
  47173. * Returns the vertical blur PostProcess
  47174. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47175. */
  47176. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47177. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47178. return null;
  47179. };
  47180. /**
  47181. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47182. */
  47183. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47184. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47185. for (var i = 0; i < this._scene.cameras.length; i++) {
  47186. var camera = this._scene.cameras[i];
  47187. this._originalColorPostProcess.dispose(camera);
  47188. this._ssaoPostProcess.dispose(camera);
  47189. this._blurHPostProcess.dispose(camera);
  47190. this._blurVPostProcess.dispose(camera);
  47191. this._ssaoCombinePostProcess.dispose(camera);
  47192. }
  47193. this._randomTexture.dispose();
  47194. if (disableDepthRender)
  47195. this._scene.disableDepthRenderer();
  47196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47197. };
  47198. // Private Methods
  47199. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47200. var _this = this;
  47201. /*
  47202. var samplerOffsets = [
  47203. -8.0, -6.0, -4.0, -2.0,
  47204. 0.0,
  47205. 2.0, 4.0, 6.0, 8.0
  47206. ];
  47207. */
  47208. var samples = 16;
  47209. var samplerOffsets = [];
  47210. for (var i = -8; i < 8; i++) {
  47211. samplerOffsets.push(i * 2);
  47212. }
  47213. 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");
  47214. this._blurHPostProcess.onApply = function (effect) {
  47215. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47216. effect.setTexture("depthSampler", _this._depthTexture);
  47217. if (_this._firstUpdate) {
  47218. effect.setArray("samplerOffsets", samplerOffsets);
  47219. }
  47220. };
  47221. 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");
  47222. this._blurVPostProcess.onApply = function (effect) {
  47223. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47224. effect.setTexture("depthSampler", _this._depthTexture);
  47225. if (_this._firstUpdate) {
  47226. effect.setArray("samplerOffsets", samplerOffsets);
  47227. _this._firstUpdate = false;
  47228. }
  47229. };
  47230. };
  47231. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47232. var _this = this;
  47233. var numSamples = 16;
  47234. var sampleSphere = [
  47235. 0.5381, 0.1856, -0.4319,
  47236. 0.1379, 0.2486, 0.4430,
  47237. 0.3371, 0.5679, -0.0057,
  47238. -0.6999, -0.0451, -0.0019,
  47239. 0.0689, -0.1598, -0.8547,
  47240. 0.0560, 0.0069, -0.1843,
  47241. -0.0146, 0.1402, 0.0762,
  47242. 0.0100, -0.1924, -0.0344,
  47243. -0.3577, -0.5301, -0.4358,
  47244. -0.3169, 0.1063, 0.0158,
  47245. 0.0103, -0.5869, 0.0046,
  47246. -0.0897, -0.4940, 0.3287,
  47247. 0.7119, -0.0154, -0.0918,
  47248. -0.0533, 0.0596, -0.5411,
  47249. 0.0352, -0.0631, 0.5460,
  47250. -0.4776, 0.2847, -0.0271
  47251. ];
  47252. var samplesFactor = 1.0 / numSamples;
  47253. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47254. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47255. "area", "fallOff", "base", "range", "viewport"
  47256. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47257. var viewport = new BABYLON.Vector2(0, 0);
  47258. this._ssaoPostProcess.onApply = function (effect) {
  47259. if (_this._firstUpdate) {
  47260. effect.setArray3("sampleSphere", sampleSphere);
  47261. effect.setFloat("samplesFactor", samplesFactor);
  47262. effect.setFloat("randTextureTiles", 4.0);
  47263. }
  47264. effect.setFloat("totalStrength", _this.totalStrength);
  47265. effect.setFloat("radius", _this.radius);
  47266. effect.setFloat("area", _this.area);
  47267. effect.setFloat("fallOff", _this.fallOff);
  47268. effect.setFloat("base", _this.base);
  47269. effect.setTexture("textureSampler", _this._depthTexture);
  47270. effect.setTexture("randomSampler", _this._randomTexture);
  47271. };
  47272. };
  47273. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47274. var _this = this;
  47275. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47276. this._ssaoCombinePostProcess.onApply = function (effect) {
  47277. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47278. };
  47279. };
  47280. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47281. var size = 512;
  47282. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47283. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47284. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47285. var context = this._randomTexture.getContext();
  47286. var rand = function (min, max) {
  47287. return Math.random() * (max - min) + min;
  47288. };
  47289. var randVector = BABYLON.Vector3.Zero();
  47290. for (var x = 0; x < size; x++) {
  47291. for (var y = 0; y < size; y++) {
  47292. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47293. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47294. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47295. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47296. context.fillRect(x, y, 1, 1);
  47297. }
  47298. }
  47299. this._randomTexture.update(false);
  47300. };
  47301. __decorate([
  47302. BABYLON.serialize()
  47303. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47304. __decorate([
  47305. BABYLON.serialize()
  47306. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47307. __decorate([
  47308. BABYLON.serialize()
  47309. ], SSAORenderingPipeline.prototype, "area", void 0);
  47310. __decorate([
  47311. BABYLON.serialize()
  47312. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47313. __decorate([
  47314. BABYLON.serialize()
  47315. ], SSAORenderingPipeline.prototype, "base", void 0);
  47316. __decorate([
  47317. BABYLON.serialize()
  47318. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47319. return SSAORenderingPipeline;
  47320. }(BABYLON.PostProcessRenderPipeline));
  47321. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47322. })(BABYLON || (BABYLON = {}));
  47323. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47324. var BABYLON;
  47325. (function (BABYLON) {
  47326. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47327. var VolumetricLightScatteringPostProcess = (function (_super) {
  47328. __extends(VolumetricLightScatteringPostProcess, _super);
  47329. /**
  47330. * @constructor
  47331. * @param {string} name - The post-process name
  47332. * @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)
  47333. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47334. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47335. * @param {number} samples - The post-process quality, default 100
  47336. * @param {number} samplingMode - The post-process filtering mode
  47337. * @param {BABYLON.Engine} engine - The babylon engine
  47338. * @param {boolean} reusable - If the post-process is reusable
  47339. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47340. */
  47341. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47342. var _this = this;
  47343. if (samples === void 0) { samples = 100; }
  47344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47345. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47346. this._screenCoordinates = BABYLON.Vector2.Zero();
  47347. /**
  47348. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47349. * @type {Vector3}
  47350. */
  47351. this.customMeshPosition = BABYLON.Vector3.Zero();
  47352. /**
  47353. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47354. * @type {boolean}
  47355. */
  47356. this.useCustomMeshPosition = false;
  47357. /**
  47358. * If the post-process should inverse the light scattering direction
  47359. * @type {boolean}
  47360. */
  47361. this.invert = true;
  47362. /**
  47363. * Array containing the excluded meshes not rendered in the internal pass
  47364. */
  47365. this.excludedMeshes = new Array();
  47366. /**
  47367. * Controls the overall intensity of the post-process
  47368. * @type {number}
  47369. */
  47370. this.exposure = 0.3;
  47371. /**
  47372. * Dissipates each sample's contribution in range [0, 1]
  47373. * @type {number}
  47374. */
  47375. this.decay = 0.96815;
  47376. /**
  47377. * Controls the overall intensity of each sample
  47378. * @type {number}
  47379. */
  47380. this.weight = 0.58767;
  47381. /**
  47382. * Controls the density of each sample
  47383. * @type {number}
  47384. */
  47385. this.density = 0.926;
  47386. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47387. var engine = scene.getEngine();
  47388. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47389. // Configure mesh
  47390. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47391. // Configure
  47392. this._createPass(scene, ratio.passRatio || ratio);
  47393. this.onActivate = function (camera) {
  47394. if (!_this.isSupported) {
  47395. _this.dispose(camera);
  47396. }
  47397. _this.onActivate = null;
  47398. };
  47399. this.onApplyObservable.add(function (effect) {
  47400. _this._updateMeshScreenCoordinates(scene);
  47401. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47402. effect.setFloat("exposure", _this.exposure);
  47403. effect.setFloat("decay", _this.decay);
  47404. effect.setFloat("weight", _this.weight);
  47405. effect.setFloat("density", _this.density);
  47406. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47407. });
  47408. }
  47409. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47410. get: function () {
  47411. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47412. return false;
  47413. },
  47414. set: function (useDiffuseColor) {
  47415. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47416. },
  47417. enumerable: true,
  47418. configurable: true
  47419. });
  47420. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47421. var mesh = subMesh.getMesh();
  47422. // Render this.mesh as default
  47423. if (mesh === this.mesh) {
  47424. return mesh.material.isReady(mesh);
  47425. }
  47426. var defines = [];
  47427. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47428. var material = subMesh.getMaterial();
  47429. var needUV = false;
  47430. // Alpha test
  47431. if (material) {
  47432. if (material.needAlphaTesting()) {
  47433. defines.push("#define ALPHATEST");
  47434. }
  47435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47436. attribs.push(BABYLON.VertexBuffer.UVKind);
  47437. defines.push("#define UV1");
  47438. }
  47439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47441. defines.push("#define UV2");
  47442. }
  47443. }
  47444. // Bones
  47445. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47446. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47447. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47448. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47449. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47450. }
  47451. else {
  47452. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47453. }
  47454. // Instances
  47455. if (useInstances) {
  47456. defines.push("#define INSTANCES");
  47457. attribs.push("world0");
  47458. attribs.push("world1");
  47459. attribs.push("world2");
  47460. attribs.push("world3");
  47461. }
  47462. // Get correct effect
  47463. var join = defines.join("\n");
  47464. if (this._cachedDefines !== join) {
  47465. this._cachedDefines = join;
  47466. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47467. }
  47468. return this._volumetricLightScatteringPass.isReady();
  47469. };
  47470. /**
  47471. * Sets the new light position for light scattering effect
  47472. * @param {BABYLON.Vector3} The new custom light position
  47473. */
  47474. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47475. this.customMeshPosition = position;
  47476. };
  47477. /**
  47478. * Returns the light position for light scattering effect
  47479. * @return {BABYLON.Vector3} The custom light position
  47480. */
  47481. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47482. return this.customMeshPosition;
  47483. };
  47484. /**
  47485. * Disposes the internal assets and detaches the post-process from the camera
  47486. */
  47487. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47488. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47489. if (rttIndex !== -1) {
  47490. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47491. }
  47492. this._volumetricLightScatteringRTT.dispose();
  47493. _super.prototype.dispose.call(this, camera);
  47494. };
  47495. /**
  47496. * Returns the render target texture used by the post-process
  47497. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47498. */
  47499. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47500. return this._volumetricLightScatteringRTT;
  47501. };
  47502. // Private methods
  47503. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47504. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47505. return true;
  47506. }
  47507. return false;
  47508. };
  47509. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47510. var _this = this;
  47511. var engine = scene.getEngine();
  47512. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47513. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47514. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47515. this._volumetricLightScatteringRTT.renderList = null;
  47516. this._volumetricLightScatteringRTT.renderParticles = false;
  47517. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47518. // Custom render function for submeshes
  47519. var renderSubMesh = function (subMesh) {
  47520. var mesh = subMesh.getRenderingMesh();
  47521. if (_this._meshExcluded(mesh)) {
  47522. return;
  47523. }
  47524. var scene = mesh.getScene();
  47525. var engine = scene.getEngine();
  47526. // Culling
  47527. engine.setState(subMesh.getMaterial().backFaceCulling);
  47528. // Managing instances
  47529. var batch = mesh._getInstancesRenderList(subMesh._id);
  47530. if (batch.mustReturn) {
  47531. return;
  47532. }
  47533. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47534. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47535. var effect = _this._volumetricLightScatteringPass;
  47536. if (mesh === _this.mesh) {
  47537. effect = subMesh.getMaterial().getEffect();
  47538. }
  47539. engine.enableEffect(effect);
  47540. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47541. if (mesh === _this.mesh) {
  47542. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47543. }
  47544. else {
  47545. var material = subMesh.getMaterial();
  47546. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47547. // Alpha test
  47548. if (material && material.needAlphaTesting()) {
  47549. var alphaTexture = material.getAlphaTestTexture();
  47550. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47551. if (alphaTexture) {
  47552. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47553. }
  47554. }
  47555. // Bones
  47556. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47557. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47558. }
  47559. }
  47560. // Draw
  47561. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47562. }
  47563. };
  47564. // Render target texture callbacks
  47565. var savedSceneClearColor;
  47566. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47567. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47568. savedSceneClearColor = scene.clearColor;
  47569. scene.clearColor = sceneClearColor;
  47570. });
  47571. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47572. scene.clearColor = savedSceneClearColor;
  47573. });
  47574. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47575. var engine = scene.getEngine();
  47576. var index;
  47577. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47578. renderSubMesh(opaqueSubMeshes.data[index]);
  47579. }
  47580. engine.setAlphaTesting(true);
  47581. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47582. renderSubMesh(alphaTestSubMeshes.data[index]);
  47583. }
  47584. engine.setAlphaTesting(false);
  47585. if (transparentSubMeshes.length) {
  47586. // Sort sub meshes
  47587. for (index = 0; index < transparentSubMeshes.length; index++) {
  47588. var submesh = transparentSubMeshes.data[index];
  47589. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47590. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47591. }
  47592. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47593. sortedArray.sort(function (a, b) {
  47594. // Alpha index first
  47595. if (a._alphaIndex > b._alphaIndex) {
  47596. return 1;
  47597. }
  47598. if (a._alphaIndex < b._alphaIndex) {
  47599. return -1;
  47600. }
  47601. // Then distance to camera
  47602. if (a._distanceToCamera < b._distanceToCamera) {
  47603. return 1;
  47604. }
  47605. if (a._distanceToCamera > b._distanceToCamera) {
  47606. return -1;
  47607. }
  47608. return 0;
  47609. });
  47610. // Render sub meshes
  47611. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47612. for (index = 0; index < sortedArray.length; index++) {
  47613. renderSubMesh(sortedArray[index]);
  47614. }
  47615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47616. }
  47617. };
  47618. };
  47619. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47620. var transform = scene.getTransformMatrix();
  47621. var meshPosition;
  47622. if (this.useCustomMeshPosition) {
  47623. meshPosition = this.customMeshPosition;
  47624. }
  47625. else if (this.attachedNode) {
  47626. meshPosition = this.attachedNode.position;
  47627. }
  47628. else {
  47629. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47630. }
  47631. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47632. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47633. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47634. if (this.invert)
  47635. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47636. };
  47637. // Static methods
  47638. /**
  47639. * Creates a default mesh for the Volumeric Light Scattering post-process
  47640. * @param {string} The mesh name
  47641. * @param {BABYLON.Scene} The scene where to create the mesh
  47642. * @return {BABYLON.Mesh} the default mesh
  47643. */
  47644. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47645. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47646. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47647. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47648. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47649. mesh.material = material;
  47650. return mesh;
  47651. };
  47652. __decorate([
  47653. BABYLON.serializeAsVector3()
  47654. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47655. __decorate([
  47656. BABYLON.serialize()
  47657. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47658. __decorate([
  47659. BABYLON.serialize()
  47660. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47661. __decorate([
  47662. BABYLON.serializeAsMeshReference()
  47663. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47664. __decorate([
  47665. BABYLON.serialize()
  47666. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47667. __decorate([
  47668. BABYLON.serialize()
  47669. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47670. __decorate([
  47671. BABYLON.serialize()
  47672. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47673. __decorate([
  47674. BABYLON.serialize()
  47675. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47676. __decorate([
  47677. BABYLON.serialize()
  47678. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47679. return VolumetricLightScatteringPostProcess;
  47680. }(BABYLON.PostProcess));
  47681. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47682. })(BABYLON || (BABYLON = {}));
  47683. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47684. // BABYLON.JS Chromatic Aberration GLSL Shader
  47685. // Author: Olivier Guyot
  47686. // Separates very slightly R, G and B colors on the edges of the screen
  47687. // Inspired by Francois Tarlier & Martins Upitis
  47688. var BABYLON;
  47689. (function (BABYLON) {
  47690. var LensRenderingPipeline = (function (_super) {
  47691. __extends(LensRenderingPipeline, _super);
  47692. /**
  47693. * @constructor
  47694. *
  47695. * Effect parameters are as follow:
  47696. * {
  47697. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47698. * edge_blur: number; // from 0 to x (1 for realism)
  47699. * distortion: number; // from 0 to x (1 for realism)
  47700. * grain_amount: number; // from 0 to 1
  47701. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47702. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47703. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47704. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47705. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47706. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47707. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47708. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47709. * }
  47710. * Note: if an effect parameter is unset, effect is disabled
  47711. *
  47712. * @param {string} name - The rendering pipeline name
  47713. * @param {object} parameters - An object containing all parameters (see above)
  47714. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47715. * @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)
  47716. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47717. */
  47718. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47719. var _this = this;
  47720. if (ratio === void 0) { ratio = 1.0; }
  47721. _super.call(this, scene.getEngine(), name);
  47722. // Lens effects can be of the following:
  47723. // - chromatic aberration (slight shift of RGB colors)
  47724. // - blur on the edge of the lens
  47725. // - lens distortion
  47726. // - depth-of-field blur & highlights enhancing
  47727. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47728. // - grain effect (noise or custom texture)
  47729. // Two additional texture samplers are needed:
  47730. // - depth map (for depth-of-field)
  47731. // - grain texture
  47732. /**
  47733. * The chromatic aberration PostProcess id in the pipeline
  47734. * @type {string}
  47735. */
  47736. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47737. /**
  47738. * The highlights enhancing PostProcess id in the pipeline
  47739. * @type {string}
  47740. */
  47741. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47742. /**
  47743. * The depth-of-field PostProcess id in the pipeline
  47744. * @type {string}
  47745. */
  47746. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47747. this._scene = scene;
  47748. // Fetch texture samplers
  47749. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47750. if (parameters.grain_texture) {
  47751. this._grainTexture = parameters.grain_texture;
  47752. }
  47753. else {
  47754. this._createGrainTexture();
  47755. }
  47756. // save parameters
  47757. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47758. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47759. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47760. this._distortion = parameters.distortion ? parameters.distortion : 0;
  47761. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47762. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47763. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47764. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47765. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47766. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47767. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47768. // Create effects
  47769. this._createChromaticAberrationPostProcess(ratio);
  47770. this._createHighlightsPostProcess(ratio);
  47771. this._createDepthOfFieldPostProcess(ratio / 4);
  47772. // Set up pipeline
  47773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47775. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47776. if (this._highlightsGain === -1) {
  47777. this._disableEffect(this.HighlightsEnhancingEffect, null);
  47778. }
  47779. // Finish
  47780. scene.postProcessRenderPipelineManager.addPipeline(this);
  47781. if (cameras) {
  47782. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47783. }
  47784. }
  47785. // public methods (self explanatory)
  47786. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47787. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47788. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47789. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47790. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47791. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47792. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47793. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47794. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47795. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47796. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47797. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47798. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47799. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47800. };
  47801. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47802. this._highlightsPostProcess.updateEffect();
  47803. };
  47804. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47805. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47806. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47807. this._highlightsGain = amount;
  47808. };
  47809. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47810. if (this._highlightsGain === -1) {
  47811. this._highlightsGain = 1.0;
  47812. }
  47813. this._highlightsThreshold = amount;
  47814. };
  47815. LensRenderingPipeline.prototype.disableHighlights = function () {
  47816. this._highlightsGain = -1;
  47817. };
  47818. /**
  47819. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47820. */
  47821. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47822. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47823. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47824. this._chromaticAberrationPostProcess = undefined;
  47825. this._highlightsPostProcess = undefined;
  47826. this._depthOfFieldPostProcess = undefined;
  47827. this._grainTexture.dispose();
  47828. if (disableDepthRender)
  47829. this._scene.disableDepthRenderer();
  47830. };
  47831. // colors shifting and distortion
  47832. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47833. var _this = this;
  47834. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47835. [], // samplers
  47836. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47837. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47838. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47839. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47840. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47841. };
  47842. };
  47843. // highlights enhancing
  47844. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47845. var _this = this;
  47846. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47847. [], // samplers
  47848. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47849. this._highlightsPostProcess.onApply = function (effect) {
  47850. effect.setFloat('gain', _this._highlightsGain);
  47851. effect.setFloat('threshold', _this._highlightsThreshold);
  47852. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47853. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47854. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47855. };
  47856. };
  47857. // colors shifting and distortion
  47858. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47859. var _this = this;
  47860. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47861. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47862. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47863. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47864. this._depthOfFieldPostProcess.onApply = function (effect) {
  47865. effect.setTexture("depthSampler", _this._depthTexture);
  47866. effect.setTexture("grainSampler", _this._grainTexture);
  47867. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47868. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47869. effect.setFloat('grain_amount', _this._grainAmount);
  47870. effect.setBool('blur_noise', _this._blurNoise);
  47871. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47872. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47873. effect.setFloat('distortion', _this._distortion);
  47874. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47875. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47876. effect.setFloat('aperture', _this._dofAperture);
  47877. effect.setFloat('darken', _this._dofDarken);
  47878. effect.setFloat('edge_blur', _this._edgeBlur);
  47879. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47880. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47881. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47882. };
  47883. };
  47884. // creates a black and white random noise texture, 512x512
  47885. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47886. var size = 512;
  47887. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47888. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47889. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47890. var context = this._grainTexture.getContext();
  47891. var rand = function (min, max) {
  47892. return Math.random() * (max - min) + min;
  47893. };
  47894. var value;
  47895. for (var x = 0; x < size; x++) {
  47896. for (var y = 0; y < size; y++) {
  47897. value = Math.floor(rand(0.42, 0.58) * 255);
  47898. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47899. context.fillRect(x, y, 1, 1);
  47900. }
  47901. }
  47902. this._grainTexture.update(false);
  47903. };
  47904. return LensRenderingPipeline;
  47905. }(BABYLON.PostProcessRenderPipeline));
  47906. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47907. })(BABYLON || (BABYLON = {}));
  47908. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47909. //
  47910. // This post-process allows the modification of rendered colors by using
  47911. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47912. //
  47913. // The object needs to be provided an url to a texture containing the color
  47914. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47915. // Use an image editing software to tweak the LUT to match your needs.
  47916. //
  47917. // For an example of a color LUT, see here:
  47918. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47919. // For explanations on color grading, see here:
  47920. // http://udn.epicgames.com/Three/ColorGrading.html
  47921. //
  47922. var BABYLON;
  47923. (function (BABYLON) {
  47924. var ColorCorrectionPostProcess = (function (_super) {
  47925. __extends(ColorCorrectionPostProcess, _super);
  47926. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47927. var _this = this;
  47928. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  47929. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47930. this._colorTableTexture.anisotropicFilteringLevel = 1;
  47931. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47932. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47933. this.onApply = function (effect) {
  47934. effect.setTexture("colorTable", _this._colorTableTexture);
  47935. };
  47936. }
  47937. return ColorCorrectionPostProcess;
  47938. }(BABYLON.PostProcess));
  47939. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47940. })(BABYLON || (BABYLON = {}));
  47941. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47942. var BABYLON;
  47943. (function (BABYLON) {
  47944. var AnaglyphFreeCamera = (function (_super) {
  47945. __extends(AnaglyphFreeCamera, _super);
  47946. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  47947. _super.call(this, name, position, scene);
  47948. this.interaxialDistance = interaxialDistance;
  47949. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47950. }
  47951. AnaglyphFreeCamera.prototype.getClassName = function () {
  47952. return "AnaglyphFreeCamera";
  47953. };
  47954. return AnaglyphFreeCamera;
  47955. }(BABYLON.FreeCamera));
  47956. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  47957. var AnaglyphArcRotateCamera = (function (_super) {
  47958. __extends(AnaglyphArcRotateCamera, _super);
  47959. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  47960. _super.call(this, name, alpha, beta, radius, target, scene);
  47961. this.interaxialDistance = interaxialDistance;
  47962. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47963. }
  47964. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  47965. return "AnaglyphArcRotateCamera";
  47966. };
  47967. return AnaglyphArcRotateCamera;
  47968. }(BABYLON.ArcRotateCamera));
  47969. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  47970. var AnaglyphGamepadCamera = (function (_super) {
  47971. __extends(AnaglyphGamepadCamera, _super);
  47972. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  47973. _super.call(this, name, position, scene);
  47974. this.interaxialDistance = interaxialDistance;
  47975. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47976. }
  47977. AnaglyphGamepadCamera.prototype.getClassName = function () {
  47978. return "AnaglyphGamepadCamera";
  47979. };
  47980. return AnaglyphGamepadCamera;
  47981. }(BABYLON.GamepadCamera));
  47982. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  47983. var AnaglyphUniversalCamera = (function (_super) {
  47984. __extends(AnaglyphUniversalCamera, _super);
  47985. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  47986. _super.call(this, name, position, scene);
  47987. this.interaxialDistance = interaxialDistance;
  47988. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47989. }
  47990. AnaglyphUniversalCamera.prototype.getClassName = function () {
  47991. return "AnaglyphUniversalCamera";
  47992. };
  47993. return AnaglyphUniversalCamera;
  47994. }(BABYLON.UniversalCamera));
  47995. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  47996. var StereoscopicFreeCamera = (function (_super) {
  47997. __extends(StereoscopicFreeCamera, _super);
  47998. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47999. _super.call(this, name, position, scene);
  48000. this.interaxialDistance = interaxialDistance;
  48001. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48002. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48003. }
  48004. StereoscopicFreeCamera.prototype.getClassName = function () {
  48005. return "StereoscopicFreeCamera";
  48006. };
  48007. return StereoscopicFreeCamera;
  48008. }(BABYLON.FreeCamera));
  48009. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48010. var StereoscopicArcRotateCamera = (function (_super) {
  48011. __extends(StereoscopicArcRotateCamera, _super);
  48012. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48013. _super.call(this, name, alpha, beta, radius, target, scene);
  48014. this.interaxialDistance = interaxialDistance;
  48015. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48016. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48017. }
  48018. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48019. return "StereoscopicArcRotateCamera";
  48020. };
  48021. return StereoscopicArcRotateCamera;
  48022. }(BABYLON.ArcRotateCamera));
  48023. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48024. var StereoscopicGamepadCamera = (function (_super) {
  48025. __extends(StereoscopicGamepadCamera, _super);
  48026. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48027. _super.call(this, name, position, scene);
  48028. this.interaxialDistance = interaxialDistance;
  48029. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48030. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48031. }
  48032. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48033. return "StereoscopicGamepadCamera";
  48034. };
  48035. return StereoscopicGamepadCamera;
  48036. }(BABYLON.GamepadCamera));
  48037. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48038. var StereoscopicUniversalCamera = (function (_super) {
  48039. __extends(StereoscopicUniversalCamera, _super);
  48040. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48041. _super.call(this, name, position, scene);
  48042. this.interaxialDistance = interaxialDistance;
  48043. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48044. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48045. }
  48046. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48047. return "StereoscopicUniversalCamera";
  48048. };
  48049. return StereoscopicUniversalCamera;
  48050. }(BABYLON.UniversalCamera));
  48051. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48052. })(BABYLON || (BABYLON = {}));
  48053. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48054. var BABYLON;
  48055. (function (BABYLON) {
  48056. var HDRRenderingPipeline = (function (_super) {
  48057. __extends(HDRRenderingPipeline, _super);
  48058. /**
  48059. * @constructor
  48060. * @param {string} name - The rendering pipeline name
  48061. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48062. * @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)
  48063. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48064. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48065. */
  48066. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48067. var _this = this;
  48068. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48069. _super.call(this, scene.getEngine(), name);
  48070. /**
  48071. * Public members
  48072. */
  48073. // Gaussian Blur
  48074. /**
  48075. * Gaussian blur coefficient
  48076. * @type {number}
  48077. */
  48078. this.gaussCoeff = 0.3;
  48079. /**
  48080. * Gaussian blur mean
  48081. * @type {number}
  48082. */
  48083. this.gaussMean = 1.0;
  48084. /**
  48085. * Gaussian blur standard deviation
  48086. * @type {number}
  48087. */
  48088. this.gaussStandDev = 0.8;
  48089. /**
  48090. * Gaussian blur multiplier. Multiplies the blur effect
  48091. * @type {number}
  48092. */
  48093. this.gaussMultiplier = 4.0;
  48094. // HDR
  48095. /**
  48096. * Exposure, controls the overall intensity of the pipeline
  48097. * @type {number}
  48098. */
  48099. this.exposure = 1.0;
  48100. /**
  48101. * Minimum luminance that the post-process can output. Luminance is >= 0
  48102. * @type {number}
  48103. */
  48104. this.minimumLuminance = 1.0;
  48105. /**
  48106. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48107. * @type {number}
  48108. */
  48109. this.maximumLuminance = 1e20;
  48110. /**
  48111. * Increase rate for luminance: eye adaptation speed to dark
  48112. * @type {number}
  48113. */
  48114. this.luminanceIncreaserate = 0.5;
  48115. /**
  48116. * Decrease rate for luminance: eye adaptation speed to bright
  48117. * @type {number}
  48118. */
  48119. this.luminanceDecreaseRate = 0.5;
  48120. // Bright pass
  48121. /**
  48122. * Minimum luminance needed to compute HDR
  48123. * @type {number}
  48124. */
  48125. this.brightThreshold = 0.8;
  48126. this._needUpdate = true;
  48127. this._scene = scene;
  48128. // Bright pass
  48129. this._createBrightPassPostProcess(scene, ratio);
  48130. // Down sample X4
  48131. this._createDownSampleX4PostProcess(scene, ratio);
  48132. // Create gaussian blur post-processes
  48133. this._createGaussianBlurPostProcess(scene, ratio);
  48134. // Texture adder
  48135. this._createTextureAdderPostProcess(scene, ratio);
  48136. // Luminance generator
  48137. this._createLuminanceGeneratorPostProcess(scene);
  48138. // HDR
  48139. this._createHDRPostProcess(scene, ratio);
  48140. // Pass postprocess
  48141. if (originalPostProcess === null) {
  48142. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48143. }
  48144. else {
  48145. this._originalPostProcess = originalPostProcess;
  48146. }
  48147. // Configure pipeline
  48148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48154. var addDownSamplerPostProcess = function (id) {
  48155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48156. };
  48157. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48158. addDownSamplerPostProcess(i);
  48159. }
  48160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48161. // Finish
  48162. scene.postProcessRenderPipelineManager.addPipeline(this);
  48163. if (cameras !== null) {
  48164. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48165. }
  48166. this.update();
  48167. }
  48168. /**
  48169. * Tells the pipeline to update its post-processes
  48170. */
  48171. HDRRenderingPipeline.prototype.update = function () {
  48172. this._needUpdate = true;
  48173. };
  48174. /**
  48175. * Returns the current calculated luminance
  48176. */
  48177. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48178. return this._hdrCurrentLuminance;
  48179. };
  48180. /**
  48181. * Returns the currently drawn luminance
  48182. */
  48183. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48184. return this._hdrOutputLuminance;
  48185. };
  48186. /**
  48187. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48188. */
  48189. HDRRenderingPipeline.prototype.dispose = function () {
  48190. this._originalPostProcess = undefined;
  48191. this._brightPassPostProcess = undefined;
  48192. this._downSampleX4PostProcess = undefined;
  48193. this._guassianBlurHPostProcess = undefined;
  48194. this._guassianBlurVPostProcess = undefined;
  48195. this._textureAdderPostProcess = undefined;
  48196. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48197. this._downSamplePostProcesses[i] = undefined;
  48198. }
  48199. this._hdrPostProcess = undefined;
  48200. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48201. };
  48202. /**
  48203. * Creates the HDR post-process and computes the luminance adaptation
  48204. */
  48205. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48206. var _this = this;
  48207. var hdrLastLuminance = 0.0;
  48208. this._hdrOutputLuminance = -1.0;
  48209. this._hdrCurrentLuminance = 1.0;
  48210. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48211. this._hdrPostProcess.onApply = function (effect) {
  48212. if (_this._hdrOutputLuminance < 0.0) {
  48213. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48214. }
  48215. else {
  48216. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48217. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48218. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48219. }
  48220. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48221. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48222. }
  48223. else {
  48224. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48225. }
  48226. }
  48227. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48228. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48229. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48230. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48231. effect.setFloat("exposure", _this.exposure);
  48232. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48233. _this._needUpdate = false;
  48234. };
  48235. };
  48236. /**
  48237. * Texture Adder post-process
  48238. */
  48239. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48240. var _this = this;
  48241. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48242. this._textureAdderPostProcess.onApply = function (effect) {
  48243. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48244. };
  48245. };
  48246. /**
  48247. * Down sample X4 post-process
  48248. */
  48249. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48250. var _this = this;
  48251. var downSampleX4Offsets = new Array(32);
  48252. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48253. this._downSampleX4PostProcess.onApply = function (effect) {
  48254. if (_this._needUpdate) {
  48255. var id = 0;
  48256. for (var i = -2; i < 2; i++) {
  48257. for (var j = -2; j < 2; j++) {
  48258. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48259. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48260. id += 2;
  48261. }
  48262. }
  48263. }
  48264. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48265. };
  48266. };
  48267. /**
  48268. * Bright pass post-process
  48269. */
  48270. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48271. var _this = this;
  48272. var brightOffsets = new Array(8);
  48273. var brightPassCallback = function (effect) {
  48274. if (_this._needUpdate) {
  48275. var sU = (1.0 / _this._brightPassPostProcess.width);
  48276. var sV = (1.0 / _this._brightPassPostProcess.height);
  48277. brightOffsets[0] = -0.5 * sU;
  48278. brightOffsets[1] = 0.5 * sV;
  48279. brightOffsets[2] = 0.5 * sU;
  48280. brightOffsets[3] = 0.5 * sV;
  48281. brightOffsets[4] = -0.5 * sU;
  48282. brightOffsets[5] = -0.5 * sV;
  48283. brightOffsets[6] = 0.5 * sU;
  48284. brightOffsets[7] = -0.5 * sV;
  48285. }
  48286. effect.setArray2("dsOffsets", brightOffsets);
  48287. effect.setFloat("brightThreshold", _this.brightThreshold);
  48288. };
  48289. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48290. this._brightPassPostProcess.onApply = brightPassCallback;
  48291. };
  48292. /**
  48293. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48294. */
  48295. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48296. var _this = this;
  48297. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48298. var luminanceOffsets = new Array(8);
  48299. var downSampleOffsets = new Array(18);
  48300. var halfDestPixelSize;
  48301. this._downSamplePostProcesses = new Array(lumSteps);
  48302. // Utils for luminance
  48303. var luminanceUpdateSourceOffsets = function (width, height) {
  48304. var sU = (1.0 / width);
  48305. var sV = (1.0 / height);
  48306. luminanceOffsets[0] = -0.5 * sU;
  48307. luminanceOffsets[1] = 0.5 * sV;
  48308. luminanceOffsets[2] = 0.5 * sU;
  48309. luminanceOffsets[3] = 0.5 * sV;
  48310. luminanceOffsets[4] = -0.5 * sU;
  48311. luminanceOffsets[5] = -0.5 * sV;
  48312. luminanceOffsets[6] = 0.5 * sU;
  48313. luminanceOffsets[7] = -0.5 * sV;
  48314. };
  48315. var luminanceUpdateDestOffsets = function (width, height) {
  48316. var id = 0;
  48317. for (var x = -1; x < 2; x++) {
  48318. for (var y = -1; y < 2; y++) {
  48319. downSampleOffsets[id] = (x) / width;
  48320. downSampleOffsets[id + 1] = (y) / height;
  48321. id += 2;
  48322. }
  48323. }
  48324. };
  48325. // Luminance callback
  48326. var luminanceCallback = function (effect) {
  48327. if (_this._needUpdate) {
  48328. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48329. }
  48330. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48331. effect.setArray2("lumOffsets", luminanceOffsets);
  48332. };
  48333. // Down sample callbacks
  48334. var downSampleCallback = function (indice) {
  48335. var i = indice;
  48336. return function (effect) {
  48337. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48338. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48339. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48340. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48341. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48342. effect.setArray2("dsOffsets", downSampleOffsets);
  48343. };
  48344. };
  48345. var downSampleAfterRenderCallback = function (effect) {
  48346. // Unpack result
  48347. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48348. 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);
  48349. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48350. };
  48351. // Create luminance post-process
  48352. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48353. 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);
  48354. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48355. // Create down sample post-processes
  48356. for (var i = lumSteps - 2; i >= 0; i--) {
  48357. var length = Math.pow(3, i);
  48358. ratio = { width: length, height: length };
  48359. var defines = "#define DOWN_SAMPLE\n";
  48360. if (i === 0) {
  48361. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48362. }
  48363. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48364. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48365. if (i === 0) {
  48366. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48367. }
  48368. }
  48369. };
  48370. /**
  48371. * Gaussian blur post-processes. Horizontal and Vertical
  48372. */
  48373. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48374. var _this = this;
  48375. var blurOffsetsW = new Array(9);
  48376. var blurOffsetsH = new Array(9);
  48377. var blurWeights = new Array(9);
  48378. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48379. // Utils for gaussian blur
  48380. var calculateBlurOffsets = function (height) {
  48381. var lastOutputDimensions = {
  48382. width: scene.getEngine().getRenderWidth(),
  48383. height: scene.getEngine().getRenderHeight()
  48384. };
  48385. for (var i = 0; i < 9; i++) {
  48386. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48387. if (height) {
  48388. blurOffsetsH[i] = value;
  48389. }
  48390. else {
  48391. blurOffsetsW[i] = value;
  48392. }
  48393. }
  48394. };
  48395. var calculateWeights = function () {
  48396. var x = 0.0;
  48397. for (var i = 0; i < 9; i++) {
  48398. x = (i - 4.0) / 4.0;
  48399. 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));
  48400. }
  48401. };
  48402. // Callback
  48403. var gaussianBlurCallback = function (height) {
  48404. return function (effect) {
  48405. if (_this._needUpdate) {
  48406. calculateWeights();
  48407. calculateBlurOffsets(height);
  48408. }
  48409. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48410. effect.setArray("blurWeights", blurWeights);
  48411. effect.setFloat("multiplier", _this.gaussMultiplier);
  48412. };
  48413. };
  48414. // Create horizontal gaussian blur post-processes
  48415. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48416. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48417. // Create vertical gaussian blur post-process
  48418. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48419. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48420. };
  48421. // Luminance generator
  48422. HDRRenderingPipeline.LUM_STEPS = 6;
  48423. return HDRRenderingPipeline;
  48424. }(BABYLON.PostProcessRenderPipeline));
  48425. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48426. })(BABYLON || (BABYLON = {}));
  48427. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48428. var BABYLON;
  48429. (function (BABYLON) {
  48430. var FaceAdjacencies = (function () {
  48431. function FaceAdjacencies() {
  48432. this.edges = new Array();
  48433. this.edgesConnectedCount = 0;
  48434. }
  48435. return FaceAdjacencies;
  48436. }());
  48437. var EdgesRenderer = (function () {
  48438. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48439. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48440. if (epsilon === void 0) { epsilon = 0.95; }
  48441. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48442. this.edgesWidthScalerForOrthographic = 1000.0;
  48443. this.edgesWidthScalerForPerspective = 50.0;
  48444. this._linesPositions = new Array();
  48445. this._linesNormals = new Array();
  48446. this._linesIndices = new Array();
  48447. this._buffers = {};
  48448. this._checkVerticesInsteadOfIndices = false;
  48449. this._source = source;
  48450. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48451. this._epsilon = epsilon;
  48452. this._prepareRessources();
  48453. this._generateEdgesLines();
  48454. }
  48455. EdgesRenderer.prototype._prepareRessources = function () {
  48456. if (this._lineShader) {
  48457. return;
  48458. }
  48459. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48460. attributes: ["position", "normal"],
  48461. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48462. });
  48463. this._lineShader.disableDepthWrite = true;
  48464. this._lineShader.backFaceCulling = false;
  48465. };
  48466. EdgesRenderer.prototype.dispose = function () {
  48467. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48468. if (buffer) {
  48469. buffer.dispose();
  48470. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48471. }
  48472. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48473. if (buffer) {
  48474. buffer.dispose();
  48475. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48476. }
  48477. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48478. this._lineShader.dispose();
  48479. };
  48480. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48481. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48482. return 0;
  48483. }
  48484. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48485. return 1;
  48486. }
  48487. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48488. return 2;
  48489. }
  48490. return -1;
  48491. };
  48492. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48493. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48494. return 0;
  48495. }
  48496. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48497. return 1;
  48498. }
  48499. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48500. return 2;
  48501. }
  48502. return -1;
  48503. };
  48504. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48505. var needToCreateLine;
  48506. if (edge === undefined) {
  48507. needToCreateLine = true;
  48508. }
  48509. else {
  48510. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48511. needToCreateLine = dotProduct < this._epsilon;
  48512. }
  48513. if (needToCreateLine) {
  48514. var offset = this._linesPositions.length / 3;
  48515. var normal = p0.subtract(p1);
  48516. normal.normalize();
  48517. // Positions
  48518. this._linesPositions.push(p0.x);
  48519. this._linesPositions.push(p0.y);
  48520. this._linesPositions.push(p0.z);
  48521. this._linesPositions.push(p0.x);
  48522. this._linesPositions.push(p0.y);
  48523. this._linesPositions.push(p0.z);
  48524. this._linesPositions.push(p1.x);
  48525. this._linesPositions.push(p1.y);
  48526. this._linesPositions.push(p1.z);
  48527. this._linesPositions.push(p1.x);
  48528. this._linesPositions.push(p1.y);
  48529. this._linesPositions.push(p1.z);
  48530. // Normals
  48531. this._linesNormals.push(p1.x);
  48532. this._linesNormals.push(p1.y);
  48533. this._linesNormals.push(p1.z);
  48534. this._linesNormals.push(-1);
  48535. this._linesNormals.push(p1.x);
  48536. this._linesNormals.push(p1.y);
  48537. this._linesNormals.push(p1.z);
  48538. this._linesNormals.push(1);
  48539. this._linesNormals.push(p0.x);
  48540. this._linesNormals.push(p0.y);
  48541. this._linesNormals.push(p0.z);
  48542. this._linesNormals.push(-1);
  48543. this._linesNormals.push(p0.x);
  48544. this._linesNormals.push(p0.y);
  48545. this._linesNormals.push(p0.z);
  48546. this._linesNormals.push(1);
  48547. // Indices
  48548. this._linesIndices.push(offset);
  48549. this._linesIndices.push(offset + 1);
  48550. this._linesIndices.push(offset + 2);
  48551. this._linesIndices.push(offset);
  48552. this._linesIndices.push(offset + 2);
  48553. this._linesIndices.push(offset + 3);
  48554. }
  48555. };
  48556. EdgesRenderer.prototype._generateEdgesLines = function () {
  48557. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48558. var indices = this._source.getIndices();
  48559. // First let's find adjacencies
  48560. var adjacencies = new Array();
  48561. var faceNormals = new Array();
  48562. var index;
  48563. var faceAdjacencies;
  48564. // Prepare faces
  48565. for (index = 0; index < indices.length; index += 3) {
  48566. faceAdjacencies = new FaceAdjacencies();
  48567. var p0Index = indices[index];
  48568. var p1Index = indices[index + 1];
  48569. var p2Index = indices[index + 2];
  48570. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48571. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48572. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48573. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48574. faceNormal.normalize();
  48575. faceNormals.push(faceNormal);
  48576. adjacencies.push(faceAdjacencies);
  48577. }
  48578. // Scan
  48579. for (index = 0; index < adjacencies.length; index++) {
  48580. faceAdjacencies = adjacencies[index];
  48581. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48582. var otherFaceAdjacencies = adjacencies[otherIndex];
  48583. if (faceAdjacencies.edgesConnectedCount === 3) {
  48584. break;
  48585. }
  48586. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48587. continue;
  48588. }
  48589. var otherP0 = indices[otherIndex * 3];
  48590. var otherP1 = indices[otherIndex * 3 + 1];
  48591. var otherP2 = indices[otherIndex * 3 + 2];
  48592. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48593. var otherEdgeIndex;
  48594. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48595. continue;
  48596. }
  48597. switch (edgeIndex) {
  48598. case 0:
  48599. if (this._checkVerticesInsteadOfIndices) {
  48600. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48601. }
  48602. else {
  48603. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48604. }
  48605. break;
  48606. case 1:
  48607. if (this._checkVerticesInsteadOfIndices) {
  48608. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48609. }
  48610. else {
  48611. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48612. }
  48613. break;
  48614. case 2:
  48615. if (this._checkVerticesInsteadOfIndices) {
  48616. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48617. }
  48618. else {
  48619. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48620. }
  48621. break;
  48622. }
  48623. if (otherEdgeIndex === -1) {
  48624. continue;
  48625. }
  48626. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48627. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48628. faceAdjacencies.edgesConnectedCount++;
  48629. otherFaceAdjacencies.edgesConnectedCount++;
  48630. if (faceAdjacencies.edgesConnectedCount === 3) {
  48631. break;
  48632. }
  48633. }
  48634. }
  48635. }
  48636. // Create lines
  48637. for (index = 0; index < adjacencies.length; index++) {
  48638. // 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
  48639. var current = adjacencies[index];
  48640. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48641. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48642. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48643. }
  48644. // Merge into a single mesh
  48645. var engine = this._source.getScene().getEngine();
  48646. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48647. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48648. this._ib = engine.createIndexBuffer(this._linesIndices);
  48649. this._indicesCount = this._linesIndices.length;
  48650. };
  48651. EdgesRenderer.prototype.render = function () {
  48652. if (!this._lineShader.isReady()) {
  48653. return;
  48654. }
  48655. var scene = this._source.getScene();
  48656. var engine = scene.getEngine();
  48657. this._lineShader._preBind();
  48658. // VBOs
  48659. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48660. scene.resetCachedMaterial();
  48661. this._lineShader.setColor4("color", this._source.edgesColor);
  48662. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48663. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48664. }
  48665. else {
  48666. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48667. }
  48668. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48669. this._lineShader.bind(this._source.getWorldMatrix());
  48670. // Draw order
  48671. engine.draw(true, 0, this._indicesCount);
  48672. this._lineShader.unbind();
  48673. engine.setDepthWrite(true);
  48674. };
  48675. return EdgesRenderer;
  48676. }());
  48677. BABYLON.EdgesRenderer = EdgesRenderer;
  48678. })(BABYLON || (BABYLON = {}));
  48679. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48680. var BABYLON;
  48681. (function (BABYLON) {
  48682. (function (TonemappingOperator) {
  48683. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48684. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48685. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48686. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48687. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48688. var TonemappingOperator = BABYLON.TonemappingOperator;
  48689. ;
  48690. var TonemapPostProcess = (function (_super) {
  48691. __extends(TonemapPostProcess, _super);
  48692. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48693. var _this = this;
  48694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48695. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48696. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48697. this._operator = _operator;
  48698. this.exposureAdjustment = exposureAdjustment;
  48699. var defines = "#define ";
  48700. if (this._operator === TonemappingOperator.Hable)
  48701. defines += "HABLE_TONEMAPPING";
  48702. else if (this._operator === TonemappingOperator.Reinhard)
  48703. defines += "REINHARD_TONEMAPPING";
  48704. else if (this._operator === TonemappingOperator.HejiDawson)
  48705. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48706. else if (this._operator === TonemappingOperator.Photographic)
  48707. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48708. //sadly a second call to create the effect.
  48709. this.updateEffect(defines);
  48710. this.onApply = function (effect) {
  48711. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48712. };
  48713. }
  48714. return TonemapPostProcess;
  48715. }(BABYLON.PostProcess));
  48716. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48717. })(BABYLON || (BABYLON = {}));
  48718. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48719. var BABYLON;
  48720. (function (BABYLON) {
  48721. var ReflectionProbe = (function () {
  48722. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48723. var _this = this;
  48724. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48725. this.name = name;
  48726. this._viewMatrix = BABYLON.Matrix.Identity();
  48727. this._target = BABYLON.Vector3.Zero();
  48728. this._add = BABYLON.Vector3.Zero();
  48729. this.invertYAxis = false;
  48730. this.position = BABYLON.Vector3.Zero();
  48731. this._scene = scene;
  48732. this._scene.reflectionProbes.push(this);
  48733. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48734. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48735. switch (faceIndex) {
  48736. case 0:
  48737. _this._add.copyFromFloats(1, 0, 0);
  48738. break;
  48739. case 1:
  48740. _this._add.copyFromFloats(-1, 0, 0);
  48741. break;
  48742. case 2:
  48743. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48744. break;
  48745. case 3:
  48746. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48747. break;
  48748. case 4:
  48749. _this._add.copyFromFloats(0, 0, 1);
  48750. break;
  48751. case 5:
  48752. _this._add.copyFromFloats(0, 0, -1);
  48753. break;
  48754. }
  48755. if (_this._attachedMesh) {
  48756. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48757. }
  48758. _this.position.addToRef(_this._add, _this._target);
  48759. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48760. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48761. });
  48762. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48763. scene.updateTransformMatrix(true);
  48764. });
  48765. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48766. }
  48767. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48768. get: function () {
  48769. return this._renderTargetTexture.refreshRate;
  48770. },
  48771. set: function (value) {
  48772. this._renderTargetTexture.refreshRate = value;
  48773. },
  48774. enumerable: true,
  48775. configurable: true
  48776. });
  48777. ReflectionProbe.prototype.getScene = function () {
  48778. return this._scene;
  48779. };
  48780. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48781. get: function () {
  48782. return this._renderTargetTexture;
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48788. get: function () {
  48789. return this._renderTargetTexture.renderList;
  48790. },
  48791. enumerable: true,
  48792. configurable: true
  48793. });
  48794. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48795. this._attachedMesh = mesh;
  48796. };
  48797. ReflectionProbe.prototype.dispose = function () {
  48798. var index = this._scene.reflectionProbes.indexOf(this);
  48799. if (index !== -1) {
  48800. // Remove from the scene if found
  48801. this._scene.reflectionProbes.splice(index, 1);
  48802. }
  48803. if (this._renderTargetTexture) {
  48804. this._renderTargetTexture.dispose();
  48805. this._renderTargetTexture = null;
  48806. }
  48807. };
  48808. return ReflectionProbe;
  48809. }());
  48810. BABYLON.ReflectionProbe = ReflectionProbe;
  48811. })(BABYLON || (BABYLON = {}));
  48812. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48813. var BABYLON;
  48814. (function (BABYLON) {
  48815. var SolidParticle = (function () {
  48816. /**
  48817. * Creates a Solid Particle object.
  48818. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48819. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48820. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48821. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48822. * `shapeId` (integer) is the model shape identifier in the SPS.
  48823. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48824. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48825. */
  48826. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48827. this.idx = 0; // particle global index
  48828. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48829. this.position = BABYLON.Vector3.Zero(); // position
  48830. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48831. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48832. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48833. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48834. this.alive = true; // alive
  48835. this.isVisible = true; // visibility
  48836. this._pos = 0; // index of this particle in the global "positions" array
  48837. this.shapeId = 0; // model shape id
  48838. this.idxInShape = 0; // index of the particle in its shape id
  48839. this.idx = particleIndex;
  48840. this._pos = positionIndex;
  48841. this._model = model;
  48842. this.shapeId = shapeId;
  48843. this.idxInShape = idxInShape;
  48844. this._sps = sps;
  48845. if (modelBoundingInfo) {
  48846. this._modelBoundingInfo = modelBoundingInfo;
  48847. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48848. }
  48849. }
  48850. Object.defineProperty(SolidParticle.prototype, "scale", {
  48851. /**
  48852. * legacy support, changed scale to scaling
  48853. */
  48854. get: function () {
  48855. return this.scaling;
  48856. },
  48857. set: function (scale) {
  48858. this.scaling = scale;
  48859. },
  48860. enumerable: true,
  48861. configurable: true
  48862. });
  48863. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48864. /**
  48865. * legacy support, changed quaternion to rotationQuaternion
  48866. */
  48867. get: function () {
  48868. return this.rotationQuaternion;
  48869. },
  48870. set: function (q) {
  48871. this.rotationQuaternion = q;
  48872. },
  48873. enumerable: true,
  48874. configurable: true
  48875. });
  48876. /**
  48877. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48878. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48879. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  48880. */
  48881. SolidParticle.prototype.intersectsMesh = function (target) {
  48882. if (!this._boundingInfo || !target._boundingInfo) {
  48883. return false;
  48884. }
  48885. if (this._sps._bSphereOnly) {
  48886. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48887. }
  48888. return this._boundingInfo.intersects(target._boundingInfo, false);
  48889. };
  48890. return SolidParticle;
  48891. }());
  48892. BABYLON.SolidParticle = SolidParticle;
  48893. var ModelShape = (function () {
  48894. /**
  48895. * 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.
  48896. * SPS internal tool, don't use it manually.
  48897. */
  48898. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  48899. this.shapeID = id;
  48900. this._shape = shape;
  48901. this._shapeUV = shapeUV;
  48902. this._positionFunction = posFunction;
  48903. this._vertexFunction = vtxFunction;
  48904. }
  48905. return ModelShape;
  48906. }());
  48907. BABYLON.ModelShape = ModelShape;
  48908. })(BABYLON || (BABYLON = {}));
  48909. //# sourceMappingURL=babylon.solidParticle.js.map
  48910. var BABYLON;
  48911. (function (BABYLON) {
  48912. /**
  48913. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48914. */
  48915. var SolidParticleSystem = (function () {
  48916. /**
  48917. * Creates a SPS (Solid Particle System) object.
  48918. * `name` (String) is the SPS name, this will be the underlying mesh name.
  48919. * `scene` (Scene) is the scene in which the SPS is added.
  48920. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  48921. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  48922. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  48923. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48924. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48925. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48926. */
  48927. function SolidParticleSystem(name, scene, options) {
  48928. // public members
  48929. /**
  48930. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48931. * Example : var p = SPS.particles[i];
  48932. */
  48933. this.particles = new Array();
  48934. /**
  48935. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48936. */
  48937. this.nbParticles = 0;
  48938. /**
  48939. * If the particles must ever face the camera (default false). Useful for planar particles.
  48940. */
  48941. this.billboard = false;
  48942. /**
  48943. * Recompute normals when adding a shape
  48944. */
  48945. this.recomputeNormals = true;
  48946. /**
  48947. * This a counter ofr your own usage. It's not set by any SPS functions.
  48948. */
  48949. this.counter = 0;
  48950. /**
  48951. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48952. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48953. */
  48954. this.vars = {};
  48955. this._positions = new Array();
  48956. this._indices = new Array();
  48957. this._normals = new Array();
  48958. this._colors = new Array();
  48959. this._uvs = new Array();
  48960. this._index = 0; // indices index
  48961. this._updatable = true;
  48962. this._pickable = false;
  48963. this._isVisibilityBoxLocked = false;
  48964. this._alwaysVisible = false;
  48965. this._shapeCounter = 0;
  48966. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  48967. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48968. this._computeParticleColor = true;
  48969. this._computeParticleTexture = true;
  48970. this._computeParticleRotation = true;
  48971. this._computeParticleVertex = false;
  48972. this._computeBoundingBox = false;
  48973. this._cam_axisZ = BABYLON.Vector3.Zero();
  48974. this._cam_axisY = BABYLON.Vector3.Zero();
  48975. this._cam_axisX = BABYLON.Vector3.Zero();
  48976. this._axisX = BABYLON.Axis.X;
  48977. this._axisY = BABYLON.Axis.Y;
  48978. this._axisZ = BABYLON.Axis.Z;
  48979. this._camDir = BABYLON.Vector3.Zero();
  48980. this._rotMatrix = new BABYLON.Matrix();
  48981. this._invertMatrix = new BABYLON.Matrix();
  48982. this._rotated = BABYLON.Vector3.Zero();
  48983. this._quaternion = new BABYLON.Quaternion();
  48984. this._vertex = BABYLON.Vector3.Zero();
  48985. this._normal = BABYLON.Vector3.Zero();
  48986. this._yaw = 0.0;
  48987. this._pitch = 0.0;
  48988. this._roll = 0.0;
  48989. this._halfroll = 0.0;
  48990. this._halfpitch = 0.0;
  48991. this._halfyaw = 0.0;
  48992. this._sinRoll = 0.0;
  48993. this._cosRoll = 0.0;
  48994. this._sinPitch = 0.0;
  48995. this._cosPitch = 0.0;
  48996. this._sinYaw = 0.0;
  48997. this._cosYaw = 0.0;
  48998. this._w = 0.0;
  48999. this._minimum = BABYLON.Tmp.Vector3[0];
  49000. this._maximum = BABYLON.Tmp.Vector3[1];
  49001. this._scale = BABYLON.Tmp.Vector3[2];
  49002. this._translation = BABYLON.Tmp.Vector3[3];
  49003. this._minBbox = BABYLON.Tmp.Vector3[4];
  49004. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49005. this._particlesIntersect = false;
  49006. this._bSphereOnly = false;
  49007. this._bSphereRadiusFactor = 1.0;
  49008. this.name = name;
  49009. this._scene = scene;
  49010. this._camera = scene.activeCamera;
  49011. this._pickable = options ? options.isPickable : false;
  49012. this._particlesIntersect = options ? options.particleIntersection : false;
  49013. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49014. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49015. if (options && options.updatable) {
  49016. this._updatable = options.updatable;
  49017. }
  49018. else {
  49019. this._updatable = true;
  49020. }
  49021. if (this._pickable) {
  49022. this.pickedParticles = [];
  49023. }
  49024. }
  49025. /**
  49026. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49027. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49028. */
  49029. SolidParticleSystem.prototype.buildMesh = function () {
  49030. if (this.nbParticles === 0) {
  49031. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49032. this.addShape(triangle, 1);
  49033. triangle.dispose();
  49034. }
  49035. this._positions32 = new Float32Array(this._positions);
  49036. this._uvs32 = new Float32Array(this._uvs);
  49037. this._colors32 = new Float32Array(this._colors);
  49038. if (this.recomputeNormals) {
  49039. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49040. }
  49041. this._normals32 = new Float32Array(this._normals);
  49042. this._fixedNormal32 = new Float32Array(this._normals);
  49043. var vertexData = new BABYLON.VertexData();
  49044. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49045. vertexData.indices = this._indices;
  49046. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49047. if (this._uvs32) {
  49048. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49049. ;
  49050. }
  49051. if (this._colors32) {
  49052. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49053. }
  49054. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49055. vertexData.applyToMesh(mesh, this._updatable);
  49056. this.mesh = mesh;
  49057. this.mesh.isPickable = this._pickable;
  49058. // free memory
  49059. this._positions = null;
  49060. this._normals = null;
  49061. this._uvs = null;
  49062. this._colors = null;
  49063. if (!this._updatable) {
  49064. this.particles.length = 0;
  49065. }
  49066. return mesh;
  49067. };
  49068. /**
  49069. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49070. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49071. * Thus the particles generated from `digest()` have their property `position` set yet.
  49072. * `mesh` ( Mesh ) is the mesh to be digested
  49073. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49074. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49075. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49076. */
  49077. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49078. var size = (options && options.facetNb) || 1;
  49079. var number = (options && options.number);
  49080. var delta = (options && options.delta) || 0;
  49081. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49082. var meshInd = mesh.getIndices();
  49083. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49084. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49085. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49086. var f = 0; // facet counter
  49087. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49088. // compute size from number
  49089. if (number) {
  49090. number = (number > totalFacets) ? totalFacets : number;
  49091. size = Math.round(totalFacets / number);
  49092. delta = 0;
  49093. }
  49094. else {
  49095. size = (size > totalFacets) ? totalFacets : size;
  49096. }
  49097. var facetPos = []; // submesh positions
  49098. var facetInd = []; // submesh indices
  49099. var facetUV = []; // submesh UV
  49100. var facetCol = []; // submesh colors
  49101. var barycenter = BABYLON.Tmp.Vector3[0];
  49102. var rand;
  49103. var sizeO = size;
  49104. while (f < totalFacets) {
  49105. size = sizeO + Math.floor((1 + delta) * Math.random());
  49106. if (f > totalFacets - size) {
  49107. size = totalFacets - f;
  49108. }
  49109. // reset temp arrays
  49110. facetPos.length = 0;
  49111. facetInd.length = 0;
  49112. facetUV.length = 0;
  49113. facetCol.length = 0;
  49114. // iterate over "size" facets
  49115. var fi = 0;
  49116. for (var j = f * 3; j < (f + size) * 3; j++) {
  49117. facetInd.push(fi);
  49118. var i = meshInd[j];
  49119. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49120. if (meshUV) {
  49121. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49122. }
  49123. if (meshCol) {
  49124. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49125. }
  49126. fi++;
  49127. }
  49128. // create a model shape for each single particle
  49129. var idx = this.nbParticles;
  49130. var shape = this._posToShape(facetPos);
  49131. var shapeUV = this._uvsToShapeUV(facetUV);
  49132. // compute the barycenter of the shape
  49133. var v;
  49134. for (v = 0; v < shape.length; v++) {
  49135. barycenter.addInPlace(shape[v]);
  49136. }
  49137. barycenter.scaleInPlace(1 / shape.length);
  49138. // shift the shape from its barycenter to the origin
  49139. for (v = 0; v < shape.length; v++) {
  49140. shape[v].subtractInPlace(barycenter);
  49141. }
  49142. var bInfo;
  49143. if (this._particlesIntersect) {
  49144. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49145. }
  49146. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49147. // add the particle in the SPS
  49148. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49149. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49150. // initialize the particle position
  49151. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49152. this._index += shape.length;
  49153. idx++;
  49154. this.nbParticles++;
  49155. this._shapeCounter++;
  49156. f += size;
  49157. }
  49158. return this;
  49159. };
  49160. //reset copy
  49161. SolidParticleSystem.prototype._resetCopy = function () {
  49162. this._copy.position.x = 0;
  49163. this._copy.position.y = 0;
  49164. this._copy.position.z = 0;
  49165. this._copy.rotation.x = 0;
  49166. this._copy.rotation.y = 0;
  49167. this._copy.rotation.z = 0;
  49168. this._copy.rotationQuaternion = null;
  49169. this._copy.scaling.x = 1;
  49170. this._copy.scaling.y = 1;
  49171. this._copy.scaling.z = 1;
  49172. this._copy.uvs.x = 0;
  49173. this._copy.uvs.y = 0;
  49174. this._copy.uvs.z = 1;
  49175. this._copy.uvs.w = 1;
  49176. this._copy.color = null;
  49177. };
  49178. // _meshBuilder : inserts the shape model in the global SPS mesh
  49179. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49180. var i;
  49181. var u = 0;
  49182. var c = 0;
  49183. var n = 0;
  49184. this._resetCopy();
  49185. if (options && options.positionFunction) {
  49186. options.positionFunction(this._copy, idx, idxInShape);
  49187. }
  49188. if (this._copy.rotationQuaternion) {
  49189. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49190. }
  49191. else {
  49192. this._yaw = this._copy.rotation.y;
  49193. this._pitch = this._copy.rotation.x;
  49194. this._roll = this._copy.rotation.z;
  49195. this._quaternionRotationYPR();
  49196. }
  49197. this._quaternionToRotationMatrix();
  49198. for (i = 0; i < shape.length; i++) {
  49199. this._vertex.x = shape[i].x;
  49200. this._vertex.y = shape[i].y;
  49201. this._vertex.z = shape[i].z;
  49202. if (options && options.vertexFunction) {
  49203. options.vertexFunction(this._copy, this._vertex, i);
  49204. }
  49205. this._vertex.x *= this._copy.scaling.x;
  49206. this._vertex.y *= this._copy.scaling.y;
  49207. this._vertex.z *= this._copy.scaling.z;
  49208. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49209. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49210. if (meshUV) {
  49211. 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);
  49212. u += 2;
  49213. }
  49214. if (this._copy.color) {
  49215. this._color = this._copy.color;
  49216. }
  49217. else if (meshCol && meshCol[c] !== undefined) {
  49218. this._color.r = meshCol[c];
  49219. this._color.g = meshCol[c + 1];
  49220. this._color.b = meshCol[c + 2];
  49221. this._color.a = meshCol[c + 3];
  49222. }
  49223. else {
  49224. this._color.r = 1;
  49225. this._color.g = 1;
  49226. this._color.b = 1;
  49227. this._color.a = 1;
  49228. }
  49229. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49230. c += 4;
  49231. if (!this.recomputeNormals && meshNor) {
  49232. this._normal.x = meshNor[n];
  49233. this._normal.y = meshNor[n + 1];
  49234. this._normal.z = meshNor[n + 2];
  49235. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49236. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49237. n += 3;
  49238. }
  49239. }
  49240. for (i = 0; i < meshInd.length; i++) {
  49241. indices.push(p + meshInd[i]);
  49242. }
  49243. if (this._pickable) {
  49244. var nbfaces = meshInd.length / 3;
  49245. for (i = 0; i < nbfaces; i++) {
  49246. this.pickedParticles.push({ idx: idx, faceId: i });
  49247. }
  49248. }
  49249. };
  49250. // returns a shape array from positions array
  49251. SolidParticleSystem.prototype._posToShape = function (positions) {
  49252. var shape = [];
  49253. for (var i = 0; i < positions.length; i += 3) {
  49254. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49255. }
  49256. return shape;
  49257. };
  49258. // returns a shapeUV array from a Vector4 uvs
  49259. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49260. var shapeUV = [];
  49261. if (uvs) {
  49262. for (var i = 0; i < uvs.length; i++)
  49263. shapeUV.push(uvs[i]);
  49264. }
  49265. return shapeUV;
  49266. };
  49267. // adds a new particle object in the particles array
  49268. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49269. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49270. };
  49271. /**
  49272. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49273. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49274. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49275. * `nb` (positive integer) the number of particles to be created from this model
  49276. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49277. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49278. */
  49279. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49280. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49281. var meshInd = mesh.getIndices();
  49282. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49283. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49284. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49285. var bbInfo;
  49286. if (this._particlesIntersect) {
  49287. bbInfo = mesh.getBoundingInfo();
  49288. }
  49289. var shape = this._posToShape(meshPos);
  49290. var shapeUV = this._uvsToShapeUV(meshUV);
  49291. var posfunc = options ? options.positionFunction : null;
  49292. var vtxfunc = options ? options.vertexFunction : null;
  49293. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49294. // particles
  49295. var idx = this.nbParticles;
  49296. for (var i = 0; i < nb; i++) {
  49297. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49298. if (this._updatable) {
  49299. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49300. }
  49301. this._index += shape.length;
  49302. idx++;
  49303. }
  49304. this.nbParticles += nb;
  49305. this._shapeCounter++;
  49306. return this._shapeCounter - 1;
  49307. };
  49308. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49309. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49310. this._resetCopy();
  49311. if (particle._model._positionFunction) {
  49312. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49313. }
  49314. if (this._copy.rotationQuaternion) {
  49315. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49316. }
  49317. else {
  49318. this._yaw = this._copy.rotation.y;
  49319. this._pitch = this._copy.rotation.x;
  49320. this._roll = this._copy.rotation.z;
  49321. this._quaternionRotationYPR();
  49322. }
  49323. this._quaternionToRotationMatrix();
  49324. this._shape = particle._model._shape;
  49325. for (var pt = 0; pt < this._shape.length; pt++) {
  49326. this._vertex.x = this._shape[pt].x;
  49327. this._vertex.y = this._shape[pt].y;
  49328. this._vertex.z = this._shape[pt].z;
  49329. if (particle._model._vertexFunction) {
  49330. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49331. }
  49332. this._vertex.x *= this._copy.scaling.x;
  49333. this._vertex.y *= this._copy.scaling.y;
  49334. this._vertex.z *= this._copy.scaling.z;
  49335. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49336. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49337. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49338. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49339. }
  49340. particle.position.x = 0.0;
  49341. particle.position.y = 0.0;
  49342. particle.position.z = 0.0;
  49343. particle.rotation.x = 0.0;
  49344. particle.rotation.y = 0.0;
  49345. particle.rotation.z = 0.0;
  49346. particle.rotationQuaternion = null;
  49347. particle.scaling.x = 1.0;
  49348. particle.scaling.y = 1.0;
  49349. particle.scaling.z = 1.0;
  49350. };
  49351. /**
  49352. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49353. */
  49354. SolidParticleSystem.prototype.rebuildMesh = function () {
  49355. for (var p = 0; p < this.particles.length; p++) {
  49356. this._rebuildParticle(this.particles[p]);
  49357. }
  49358. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49359. };
  49360. /**
  49361. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49362. * This method calls `updateParticle()` for each particle of the SPS.
  49363. * For an animated SPS, it is usually called within the render loop.
  49364. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49365. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49366. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49367. */
  49368. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49369. if (start === void 0) { start = 0; }
  49370. if (end === void 0) { end = this.nbParticles - 1; }
  49371. if (update === void 0) { update = true; }
  49372. if (!this._updatable) {
  49373. return;
  49374. }
  49375. // custom beforeUpdate
  49376. this.beforeUpdateParticles(start, end, update);
  49377. this._cam_axisX.x = 1.0;
  49378. this._cam_axisX.y = 0.0;
  49379. this._cam_axisX.z = 0.0;
  49380. this._cam_axisY.x = 0.0;
  49381. this._cam_axisY.y = 1.0;
  49382. this._cam_axisY.z = 0.0;
  49383. this._cam_axisZ.x = 0.0;
  49384. this._cam_axisZ.y = 0.0;
  49385. this._cam_axisZ.z = 1.0;
  49386. // if the particles will always face the camera
  49387. if (this.billboard) {
  49388. // compute the camera position and un-rotate it by the current mesh rotation
  49389. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49390. this._quaternionToRotationMatrix();
  49391. this._rotMatrix.invertToRef(this._invertMatrix);
  49392. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49393. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49394. this._cam_axisZ.normalize();
  49395. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49396. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49397. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49398. this._cam_axisY.normalize();
  49399. this._cam_axisX.normalize();
  49400. }
  49401. }
  49402. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49403. var idx = 0;
  49404. var index = 0;
  49405. var colidx = 0;
  49406. var colorIndex = 0;
  49407. var uvidx = 0;
  49408. var uvIndex = 0;
  49409. var pt = 0;
  49410. if (this._computeBoundingBox) {
  49411. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49412. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49413. }
  49414. // particle loop
  49415. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49416. for (var p = start; p <= end; p++) {
  49417. this._particle = this.particles[p];
  49418. this._shape = this._particle._model._shape;
  49419. this._shapeUV = this._particle._model._shapeUV;
  49420. // call to custom user function to update the particle properties
  49421. this.updateParticle(this._particle);
  49422. if (this._particle.isVisible) {
  49423. // particle rotation matrix
  49424. if (this.billboard) {
  49425. this._particle.rotation.x = 0.0;
  49426. this._particle.rotation.y = 0.0;
  49427. }
  49428. if (this._computeParticleRotation || this.billboard) {
  49429. if (this._particle.rotationQuaternion) {
  49430. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49431. }
  49432. else {
  49433. this._yaw = this._particle.rotation.y;
  49434. this._pitch = this._particle.rotation.x;
  49435. this._roll = this._particle.rotation.z;
  49436. this._quaternionRotationYPR();
  49437. }
  49438. this._quaternionToRotationMatrix();
  49439. }
  49440. // particle vertex loop
  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._vertex.x = this._shape[pt].x;
  49446. this._vertex.y = this._shape[pt].y;
  49447. this._vertex.z = this._shape[pt].z;
  49448. if (this._computeParticleVertex) {
  49449. this.updateParticleVertex(this._particle, this._vertex, pt);
  49450. }
  49451. // positions
  49452. this._vertex.x *= this._particle.scaling.x;
  49453. this._vertex.y *= this._particle.scaling.y;
  49454. this._vertex.z *= this._particle.scaling.z;
  49455. 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];
  49456. 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;
  49457. 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;
  49458. 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;
  49459. 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;
  49460. 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;
  49461. 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;
  49462. if (this._computeBoundingBox) {
  49463. if (this._positions32[idx] < this._minimum.x) {
  49464. this._minimum.x = this._positions32[idx];
  49465. }
  49466. if (this._positions32[idx] > this._maximum.x) {
  49467. this._maximum.x = this._positions32[idx];
  49468. }
  49469. if (this._positions32[idx + 1] < this._minimum.y) {
  49470. this._minimum.y = this._positions32[idx + 1];
  49471. }
  49472. if (this._positions32[idx + 1] > this._maximum.y) {
  49473. this._maximum.y = this._positions32[idx + 1];
  49474. }
  49475. if (this._positions32[idx + 2] < this._minimum.z) {
  49476. this._minimum.z = this._positions32[idx + 2];
  49477. }
  49478. if (this._positions32[idx + 2] > this._maximum.z) {
  49479. this._maximum.z = this._positions32[idx + 2];
  49480. }
  49481. }
  49482. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49483. if (!this._computeParticleVertex) {
  49484. this._normal.x = this._fixedNormal32[idx];
  49485. this._normal.y = this._fixedNormal32[idx + 1];
  49486. this._normal.z = this._fixedNormal32[idx + 2];
  49487. 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];
  49488. 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;
  49489. 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;
  49490. 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;
  49491. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49492. 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;
  49493. 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;
  49494. }
  49495. if (this._computeParticleColor) {
  49496. this._colors32[colidx] = this._particle.color.r;
  49497. this._colors32[colidx + 1] = this._particle.color.g;
  49498. this._colors32[colidx + 2] = this._particle.color.b;
  49499. this._colors32[colidx + 3] = this._particle.color.a;
  49500. }
  49501. if (this._computeParticleTexture) {
  49502. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49503. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49504. }
  49505. }
  49506. }
  49507. else {
  49508. for (pt = 0; pt < this._shape.length; pt++) {
  49509. idx = index + pt * 3;
  49510. colidx = colorIndex + pt * 4;
  49511. uvidx = uvIndex + pt * 2;
  49512. this._positions32[idx] = this._camera.position.x;
  49513. this._positions32[idx + 1] = this._camera.position.y;
  49514. this._positions32[idx + 2] = this._camera.position.z;
  49515. this._normals32[idx] = 0.0;
  49516. this._normals32[idx + 1] = 0.0;
  49517. this._normals32[idx + 2] = 0.0;
  49518. if (this._computeParticleColor) {
  49519. this._colors32[colidx] = this._particle.color.r;
  49520. this._colors32[colidx + 1] = this._particle.color.g;
  49521. this._colors32[colidx + 2] = this._particle.color.b;
  49522. this._colors32[colidx + 3] = this._particle.color.a;
  49523. }
  49524. if (this._computeParticleTexture) {
  49525. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49526. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49527. }
  49528. }
  49529. }
  49530. // if the particle intersections must be computed : update the bbInfo
  49531. if (this._particlesIntersect) {
  49532. var bInfo = this._particle._boundingInfo;
  49533. var bBox = bInfo.boundingBox;
  49534. var bSphere = bInfo.boundingSphere;
  49535. if (!this._bSphereOnly) {
  49536. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49537. for (var b = 0; b < bBox.vectors.length; b++) {
  49538. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49539. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49540. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49541. 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];
  49542. 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;
  49543. 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;
  49544. 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;
  49545. 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;
  49546. 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;
  49547. 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;
  49548. }
  49549. bBox._update(this.mesh._worldMatrix);
  49550. }
  49551. // place and scale the particle bouding sphere in the SPS local system, then update it
  49552. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49553. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49554. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49555. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49556. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49557. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49558. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49559. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49560. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49561. 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));
  49562. bSphere._update(this.mesh._worldMatrix);
  49563. }
  49564. // increment indexes for the next particle
  49565. index = idx + 3;
  49566. colorIndex = colidx + 4;
  49567. uvIndex = uvidx + 2;
  49568. }
  49569. // if the VBO must be updated
  49570. if (update) {
  49571. if (this._computeParticleColor) {
  49572. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49573. }
  49574. if (this._computeParticleTexture) {
  49575. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49576. }
  49577. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49578. if (!this.mesh.areNormalsFrozen) {
  49579. if (this._computeParticleVertex) {
  49580. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49581. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49582. for (var i = 0; i < this._normals32.length; i++) {
  49583. this._fixedNormal32[i] = this._normals32[i];
  49584. }
  49585. }
  49586. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49587. }
  49588. }
  49589. if (this._computeBoundingBox) {
  49590. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49591. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49592. }
  49593. this.afterUpdateParticles(start, end, update);
  49594. };
  49595. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49596. this._halfroll = this._roll * 0.5;
  49597. this._halfpitch = this._pitch * 0.5;
  49598. this._halfyaw = this._yaw * 0.5;
  49599. this._sinRoll = Math.sin(this._halfroll);
  49600. this._cosRoll = Math.cos(this._halfroll);
  49601. this._sinPitch = Math.sin(this._halfpitch);
  49602. this._cosPitch = Math.cos(this._halfpitch);
  49603. this._sinYaw = Math.sin(this._halfyaw);
  49604. this._cosYaw = Math.cos(this._halfyaw);
  49605. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49606. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49607. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49608. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49609. };
  49610. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49611. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49612. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49613. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49614. this._rotMatrix.m[3] = 0;
  49615. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49616. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49617. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49618. this._rotMatrix.m[7] = 0;
  49619. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49620. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49621. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49622. this._rotMatrix.m[11] = 0;
  49623. this._rotMatrix.m[12] = 0;
  49624. this._rotMatrix.m[13] = 0;
  49625. this._rotMatrix.m[14] = 0;
  49626. this._rotMatrix.m[15] = 1.0;
  49627. };
  49628. /**
  49629. * Disposes the SPS
  49630. */
  49631. SolidParticleSystem.prototype.dispose = function () {
  49632. this.mesh.dispose();
  49633. this.vars = null;
  49634. // drop references to internal big arrays for the GC
  49635. this._positions = null;
  49636. this._indices = null;
  49637. this._normals = null;
  49638. this._uvs = null;
  49639. this._colors = null;
  49640. this._positions32 = null;
  49641. this._normals32 = null;
  49642. this._fixedNormal32 = null;
  49643. this._uvs32 = null;
  49644. this._colors32 = null;
  49645. this.pickedParticles = null;
  49646. };
  49647. /**
  49648. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49649. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49650. */
  49651. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49652. if (!this._isVisibilityBoxLocked) {
  49653. this.mesh.refreshBoundingInfo();
  49654. }
  49655. };
  49656. /**
  49657. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49658. * @param size the size (float) of the visibility box
  49659. * note : this doesn't lock the SPS mesh bounding box.
  49660. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49661. */
  49662. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49663. var vis = size / 2;
  49664. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49665. };
  49666. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49667. // getter and setter
  49668. get: function () {
  49669. return this._alwaysVisible;
  49670. },
  49671. /**
  49672. * Sets the SPS as always visible or not
  49673. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49674. */
  49675. set: function (val) {
  49676. this._alwaysVisible = val;
  49677. this.mesh.alwaysSelectAsActiveMesh = val;
  49678. },
  49679. enumerable: true,
  49680. configurable: true
  49681. });
  49682. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49683. get: function () {
  49684. return this._isVisibilityBoxLocked;
  49685. },
  49686. /**
  49687. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49688. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49689. */
  49690. set: function (val) {
  49691. this._isVisibilityBoxLocked = val;
  49692. this.mesh.getBoundingInfo().isLocked = val;
  49693. },
  49694. enumerable: true,
  49695. configurable: true
  49696. });
  49697. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49698. // getters
  49699. get: function () {
  49700. return this._computeParticleRotation;
  49701. },
  49702. // Optimizer setters
  49703. /**
  49704. * Tells to `setParticles()` to compute the particle rotations or not.
  49705. * Default value : true. The SPS is faster when it's set to false.
  49706. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49707. */
  49708. set: function (val) {
  49709. this._computeParticleRotation = val;
  49710. },
  49711. enumerable: true,
  49712. configurable: true
  49713. });
  49714. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49715. get: function () {
  49716. return this._computeParticleColor;
  49717. },
  49718. /**
  49719. * Tells to `setParticles()` to compute the particle colors or not.
  49720. * Default value : true. The SPS is faster when it's set to false.
  49721. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49722. */
  49723. set: function (val) {
  49724. this._computeParticleColor = val;
  49725. },
  49726. enumerable: true,
  49727. configurable: true
  49728. });
  49729. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49730. get: function () {
  49731. return this._computeParticleTexture;
  49732. },
  49733. /**
  49734. * Tells to `setParticles()` to compute the particle textures or not.
  49735. * Default value : true. The SPS is faster when it's set to false.
  49736. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49737. */
  49738. set: function (val) {
  49739. this._computeParticleTexture = val;
  49740. },
  49741. enumerable: true,
  49742. configurable: true
  49743. });
  49744. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49745. get: function () {
  49746. return this._computeParticleVertex;
  49747. },
  49748. /**
  49749. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49750. * Default value : false. The SPS is faster when it's set to false.
  49751. * Note : the particle custom vertex positions aren't stored values.
  49752. */
  49753. set: function (val) {
  49754. this._computeParticleVertex = val;
  49755. },
  49756. enumerable: true,
  49757. configurable: true
  49758. });
  49759. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49760. get: function () {
  49761. return this._computeBoundingBox;
  49762. },
  49763. /**
  49764. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49765. */
  49766. set: function (val) {
  49767. this._computeBoundingBox = val;
  49768. },
  49769. enumerable: true,
  49770. configurable: true
  49771. });
  49772. // =======================================================================
  49773. // Particle behavior logic
  49774. // these following methods may be overwritten by the user to fit his needs
  49775. /**
  49776. * This function does nothing. It may be overwritten to set all the particle first values.
  49777. * The SPS doesn't call this function, you may have to call it by your own.
  49778. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49779. */
  49780. SolidParticleSystem.prototype.initParticles = function () {
  49781. };
  49782. /**
  49783. * This function does nothing. It may be overwritten to recycle a particle.
  49784. * The SPS doesn't call this function, you may have to call it by your own.
  49785. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49786. */
  49787. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49788. return particle;
  49789. };
  49790. /**
  49791. * Updates a particle : this function should be overwritten by the user.
  49792. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49793. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49794. * ex : just set a particle position or velocity and recycle conditions
  49795. */
  49796. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49797. return particle;
  49798. };
  49799. /**
  49800. * Updates a vertex of a particle : it can be overwritten by the user.
  49801. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49802. * @param particle the current particle
  49803. * @param vertex the current index of the current particle
  49804. * @param pt the index of the current vertex in the particle shape
  49805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49806. * ex : just set a vertex particle position
  49807. */
  49808. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49809. return vertex;
  49810. };
  49811. /**
  49812. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49813. * This does nothing and may be overwritten by the user.
  49814. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49815. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49816. * @param update the boolean update value actually passed to setParticles()
  49817. */
  49818. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49819. };
  49820. /**
  49821. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49822. * This will be passed three parameters.
  49823. * This does nothing and may be overwritten by the user.
  49824. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49825. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49826. * @param update the boolean update value actually passed to setParticles()
  49827. */
  49828. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49829. };
  49830. return SolidParticleSystem;
  49831. }());
  49832. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49833. })(BABYLON || (BABYLON = {}));
  49834. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49835. var BABYLON;
  49836. (function (BABYLON) {
  49837. var Internals;
  49838. (function (Internals) {
  49839. var FileFaceOrientation = (function () {
  49840. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49841. this.name = name;
  49842. this.worldAxisForNormal = worldAxisForNormal;
  49843. this.worldAxisForFileX = worldAxisForFileX;
  49844. this.worldAxisForFileY = worldAxisForFileY;
  49845. }
  49846. return FileFaceOrientation;
  49847. }());
  49848. ;
  49849. /**
  49850. * Helper class dealing with the extraction of spherical polynomial dataArray
  49851. * from a cube map.
  49852. */
  49853. var CubeMapToSphericalPolynomialTools = (function () {
  49854. function CubeMapToSphericalPolynomialTools() {
  49855. }
  49856. /**
  49857. * Converts a cubemap to the according Spherical Polynomial data.
  49858. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49859. *
  49860. * @param cubeInfo The Cube map to extract the information from.
  49861. * @return The Spherical Polynomial data.
  49862. */
  49863. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49864. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49865. var totalSolidAngle = 0.0;
  49866. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49867. var du = 2.0 / cubeInfo.size;
  49868. var dv = du;
  49869. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49870. var minUV = du * 0.5 - 1.0;
  49871. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49872. var fileFace = this.FileFaces[faceIndex];
  49873. var dataArray = cubeInfo[fileFace.name];
  49874. var v = minUV;
  49875. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49876. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49877. // Because SP is still linear, so summation is fine in that basis.
  49878. for (var y = 0; y < cubeInfo.size; y++) {
  49879. var u = minUV;
  49880. for (var x = 0; x < cubeInfo.size; x++) {
  49881. // World direction (not normalised)
  49882. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49883. worldDirection.normalize();
  49884. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49885. if (1) {
  49886. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49887. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49888. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49889. var color = new BABYLON.Color3(r, g, b);
  49890. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49891. }
  49892. else {
  49893. if (faceIndex == 0) {
  49894. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49895. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49896. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49897. }
  49898. else if (faceIndex == 1) {
  49899. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49900. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49901. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49902. }
  49903. else if (faceIndex == 2) {
  49904. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49905. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49906. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49907. }
  49908. else if (faceIndex == 3) {
  49909. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49910. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49911. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49912. }
  49913. else if (faceIndex == 4) {
  49914. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49915. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49916. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49917. }
  49918. else if (faceIndex == 5) {
  49919. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49920. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49921. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49922. }
  49923. 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]);
  49924. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49925. }
  49926. totalSolidAngle += deltaSolidAngle;
  49927. u += du;
  49928. }
  49929. v += dv;
  49930. }
  49931. }
  49932. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49933. var correction = correctSolidAngle / totalSolidAngle;
  49934. sphericalHarmonics.scale(correction);
  49935. // Additionally scale by pi -- audit needed
  49936. sphericalHarmonics.scale(1.0 / Math.PI);
  49937. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49938. };
  49939. CubeMapToSphericalPolynomialTools.FileFaces = [
  49940. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49941. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49942. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49943. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49944. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49945. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49946. ];
  49947. return CubeMapToSphericalPolynomialTools;
  49948. }());
  49949. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49950. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49951. })(BABYLON || (BABYLON = {}));
  49952. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  49953. var BABYLON;
  49954. (function (BABYLON) {
  49955. var Internals;
  49956. (function (Internals) {
  49957. /**
  49958. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49959. */
  49960. var PanoramaToCubeMapTools = (function () {
  49961. function PanoramaToCubeMapTools() {
  49962. }
  49963. /**
  49964. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49965. *
  49966. * @param float32Array The source data.
  49967. * @param inputWidth The width of the input panorama.
  49968. * @param inputhHeight The height of the input panorama.
  49969. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49970. * @return The cubemap data
  49971. */
  49972. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49973. if (!float32Array) {
  49974. throw "ConvertPanoramaToCubemap: input cannot be null";
  49975. }
  49976. if (float32Array.length != inputWidth * inputHeight * 3) {
  49977. throw "ConvertPanoramaToCubemap: input size is wrong";
  49978. }
  49979. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49980. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49981. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49982. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49983. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49984. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  49985. return {
  49986. front: textureFront,
  49987. back: textureBack,
  49988. left: textureLeft,
  49989. right: textureRight,
  49990. up: textureUp,
  49991. down: textureDown,
  49992. size: size
  49993. };
  49994. };
  49995. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49996. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49997. var textureArray = new Float32Array(buffer);
  49998. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49999. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50000. var dy = 1 / texSize;
  50001. var fy = 0;
  50002. for (var y = 0; y < texSize; y++) {
  50003. var xv1 = faceData[0];
  50004. var xv2 = faceData[2];
  50005. for (var x = 0; x < texSize; x++) {
  50006. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50007. v.normalize();
  50008. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50009. // 3 channels per pixels
  50010. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50011. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50012. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50013. xv1 = xv1.add(rotDX1);
  50014. xv2 = xv2.add(rotDX2);
  50015. }
  50016. fy += dy;
  50017. }
  50018. return textureArray;
  50019. };
  50020. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50021. var theta = Math.atan2(vDir.z, vDir.x);
  50022. var phi = Math.acos(vDir.y);
  50023. while (theta < -Math.PI)
  50024. theta += 2 * Math.PI;
  50025. while (theta > Math.PI)
  50026. theta -= 2 * Math.PI;
  50027. var dx = theta / Math.PI;
  50028. var dy = phi / Math.PI;
  50029. // recenter.
  50030. dx = dx * 0.5 + 0.5;
  50031. var px = Math.round(dx * inputWidth);
  50032. if (px < 0)
  50033. px = 0;
  50034. else if (px >= inputWidth)
  50035. px = inputWidth - 1;
  50036. var py = Math.round(dy * inputHeight);
  50037. if (py < 0)
  50038. py = 0;
  50039. else if (py >= inputHeight)
  50040. py = inputHeight - 1;
  50041. var inputY = (inputHeight - py - 1);
  50042. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50043. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50044. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50045. return {
  50046. r: r,
  50047. g: g,
  50048. b: b
  50049. };
  50050. };
  50051. PanoramaToCubeMapTools.FACE_FRONT = [
  50052. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50053. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50054. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50055. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50056. ];
  50057. PanoramaToCubeMapTools.FACE_BACK = [
  50058. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50059. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50060. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50061. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50062. ];
  50063. PanoramaToCubeMapTools.FACE_RIGHT = [
  50064. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50065. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50066. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50067. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50068. ];
  50069. PanoramaToCubeMapTools.FACE_LEFT = [
  50070. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50071. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50072. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50073. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50074. ];
  50075. PanoramaToCubeMapTools.FACE_DOWN = [
  50076. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50077. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50078. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50079. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50080. ];
  50081. PanoramaToCubeMapTools.FACE_UP = [
  50082. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50083. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50084. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50085. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50086. ];
  50087. return PanoramaToCubeMapTools;
  50088. }());
  50089. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50091. })(BABYLON || (BABYLON = {}));
  50092. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50093. var BABYLON;
  50094. (function (BABYLON) {
  50095. var Internals;
  50096. (function (Internals) {
  50097. ;
  50098. /**
  50099. * This groups tools to convert HDR texture to native colors array.
  50100. */
  50101. var HDRTools = (function () {
  50102. function HDRTools() {
  50103. }
  50104. HDRTools.Ldexp = function (mantissa, exponent) {
  50105. if (exponent > 1023) {
  50106. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50107. }
  50108. if (exponent < -1074) {
  50109. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50110. }
  50111. return mantissa * Math.pow(2, exponent);
  50112. };
  50113. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50114. if (exponent > 0) {
  50115. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50116. float32array[index + 0] = red * exponent;
  50117. float32array[index + 1] = green * exponent;
  50118. float32array[index + 2] = blue * exponent;
  50119. }
  50120. else {
  50121. float32array[index + 0] = 0;
  50122. float32array[index + 1] = 0;
  50123. float32array[index + 2] = 0;
  50124. }
  50125. };
  50126. HDRTools.readStringLine = function (uint8array, startIndex) {
  50127. var line = "";
  50128. var character = "";
  50129. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50130. character = String.fromCharCode(uint8array[i]);
  50131. if (character == "\n") {
  50132. break;
  50133. }
  50134. line += character;
  50135. }
  50136. return line;
  50137. };
  50138. /**
  50139. * Reads header information from an RGBE texture stored in a native array.
  50140. * More information on this format are available here:
  50141. * https://en.wikipedia.org/wiki/RGBE_image_format
  50142. *
  50143. * @param uint8array The binary file stored in native array.
  50144. * @return The header information.
  50145. */
  50146. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50147. var height = 0;
  50148. var width = 0;
  50149. var line = this.readStringLine(uint8array, 0);
  50150. if (line[0] != '#' || line[1] != '?') {
  50151. throw "Bad HDR Format.";
  50152. }
  50153. var endOfHeader = false;
  50154. var findFormat = false;
  50155. var lineIndex = 0;
  50156. do {
  50157. lineIndex += (line.length + 1);
  50158. line = this.readStringLine(uint8array, lineIndex);
  50159. if (line == "FORMAT=32-bit_rle_rgbe") {
  50160. findFormat = true;
  50161. }
  50162. else if (line.length == 0) {
  50163. endOfHeader = true;
  50164. }
  50165. } while (!endOfHeader);
  50166. if (!findFormat) {
  50167. throw "HDR Bad header format, unsupported FORMAT";
  50168. }
  50169. lineIndex += (line.length + 1);
  50170. line = this.readStringLine(uint8array, lineIndex);
  50171. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50172. var match = sizeRegexp.exec(line);
  50173. // TODO. Support +Y and -X if needed.
  50174. if (match.length < 3) {
  50175. throw "HDR Bad header format, no size";
  50176. }
  50177. width = parseInt(match[2]);
  50178. height = parseInt(match[1]);
  50179. if (width < 8 || width > 0x7fff) {
  50180. throw "HDR Bad header format, unsupported size";
  50181. }
  50182. lineIndex += (line.length + 1);
  50183. return {
  50184. height: height,
  50185. width: width,
  50186. dataPosition: lineIndex
  50187. };
  50188. };
  50189. /**
  50190. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50191. * This RGBE texture needs to store the information as a panorama.
  50192. *
  50193. * More information on this format are available here:
  50194. * https://en.wikipedia.org/wiki/RGBE_image_format
  50195. *
  50196. * @param buffer The binary file stored in an array buffer.
  50197. * @param size The expected size of the extracted cubemap.
  50198. * @return The Cube Map information.
  50199. */
  50200. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50201. var uint8array = new Uint8Array(buffer);
  50202. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50203. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50204. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50205. return cubeMapData;
  50206. };
  50207. /**
  50208. * Returns the pixels data extracted from an RGBE texture.
  50209. * This pixels will be stored left to right up to down in the R G B order in one array.
  50210. *
  50211. * More information on this format are available here:
  50212. * https://en.wikipedia.org/wiki/RGBE_image_format
  50213. *
  50214. * @param uint8array The binary file stored in an array buffer.
  50215. * @param hdrInfo The header information of the file.
  50216. * @return The pixels data in RGB right to left up to down order.
  50217. */
  50218. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50219. // Keep for multi format supports.
  50220. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50221. };
  50222. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50223. var num_scanlines = hdrInfo.height;
  50224. var scanline_width = hdrInfo.width;
  50225. var a, b, c, d, count;
  50226. var dataIndex = hdrInfo.dataPosition;
  50227. var index = 0, endIndex = 0, i = 0;
  50228. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50229. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50230. // 3 channels of 4 bytes per pixel in float.
  50231. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50232. var resultArray = new Float32Array(resultBuffer);
  50233. // read in each successive scanline
  50234. while (num_scanlines > 0) {
  50235. a = uint8array[dataIndex++];
  50236. b = uint8array[dataIndex++];
  50237. c = uint8array[dataIndex++];
  50238. d = uint8array[dataIndex++];
  50239. if (a != 2 || b != 2 || (c & 0x80)) {
  50240. // this file is not run length encoded
  50241. throw "HDR Bad header format, not RLE";
  50242. }
  50243. if (((c << 8) | d) != scanline_width) {
  50244. throw "HDR Bad header format, wrong scan line width";
  50245. }
  50246. index = 0;
  50247. // read each of the four channels for the scanline into the buffer
  50248. for (i = 0; i < 4; i++) {
  50249. endIndex = (i + 1) * scanline_width;
  50250. while (index < endIndex) {
  50251. a = uint8array[dataIndex++];
  50252. b = uint8array[dataIndex++];
  50253. if (a > 128) {
  50254. // a run of the same value
  50255. count = a - 128;
  50256. if ((count == 0) || (count > endIndex - index)) {
  50257. throw "HDR Bad Format, bad scanline data (run)";
  50258. }
  50259. while (count-- > 0) {
  50260. scanLineArray[index++] = b;
  50261. }
  50262. }
  50263. else {
  50264. // a non-run
  50265. count = a;
  50266. if ((count == 0) || (count > endIndex - index)) {
  50267. throw "HDR Bad Format, bad scanline data (non-run)";
  50268. }
  50269. scanLineArray[index++] = b;
  50270. if (--count > 0) {
  50271. for (var j = 0; j < count; j++) {
  50272. scanLineArray[index++] = uint8array[dataIndex++];
  50273. }
  50274. }
  50275. }
  50276. }
  50277. }
  50278. // now convert data from buffer into floats
  50279. for (i = 0; i < scanline_width; i++) {
  50280. a = scanLineArray[i];
  50281. b = scanLineArray[i + scanline_width];
  50282. c = scanLineArray[i + 2 * scanline_width];
  50283. d = scanLineArray[i + 3 * scanline_width];
  50284. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50285. }
  50286. num_scanlines--;
  50287. }
  50288. return resultArray;
  50289. };
  50290. return HDRTools;
  50291. }());
  50292. Internals.HDRTools = HDRTools;
  50293. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50294. })(BABYLON || (BABYLON = {}));
  50295. //# sourceMappingURL=babylon.tools.hdr.js.map
  50296. //_______________________________________________________________
  50297. // Extracted from CubeMapGen:
  50298. // https://code.google.com/archive/p/cubemapgen/
  50299. //
  50300. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50301. //_______________________________________________________________
  50302. var BABYLON;
  50303. (function (BABYLON) {
  50304. var Internals;
  50305. (function (Internals) {
  50306. /**
  50307. * The bounding box information used during the conversion process.
  50308. */
  50309. var CMGBoundinBox = (function () {
  50310. function CMGBoundinBox() {
  50311. this.min = new BABYLON.Vector3(0, 0, 0);
  50312. this.max = new BABYLON.Vector3(0, 0, 0);
  50313. this.clear();
  50314. }
  50315. CMGBoundinBox.prototype.clear = function () {
  50316. this.min.x = CMGBoundinBox.MAX;
  50317. this.min.y = CMGBoundinBox.MAX;
  50318. this.min.z = CMGBoundinBox.MAX;
  50319. this.max.x = CMGBoundinBox.MIN;
  50320. this.max.y = CMGBoundinBox.MIN;
  50321. this.max.z = CMGBoundinBox.MIN;
  50322. };
  50323. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50324. this.min.x = Math.min(this.min.x, x);
  50325. this.min.y = Math.min(this.min.y, y);
  50326. this.min.z = Math.min(this.min.z, z);
  50327. this.max.x = Math.max(this.max.x, x);
  50328. this.max.y = Math.max(this.max.y, y);
  50329. this.max.z = Math.max(this.max.z, z);
  50330. };
  50331. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50332. this.min.x = Math.max(this.min.x, x);
  50333. this.min.y = Math.max(this.min.y, y);
  50334. this.min.z = Math.max(this.min.z, z);
  50335. };
  50336. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50337. this.max.x = Math.min(this.max.x, x);
  50338. this.max.y = Math.min(this.max.y, y);
  50339. this.max.z = Math.min(this.max.z, z);
  50340. };
  50341. CMGBoundinBox.prototype.empty = function () {
  50342. if ((this.min.x > this.max.y) ||
  50343. (this.min.y > this.max.y) ||
  50344. (this.min.z > this.max.y)) {
  50345. return true;
  50346. }
  50347. else {
  50348. return false;
  50349. }
  50350. };
  50351. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50352. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50353. return CMGBoundinBox;
  50354. }());
  50355. /**
  50356. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50357. * required by the glossinees of a material.
  50358. *
  50359. * This only supports the cosine drop power as well as Warp fixup generation method.
  50360. *
  50361. * This is using the process from CubeMapGen described here:
  50362. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50363. */
  50364. var PMREMGenerator = (function () {
  50365. /**
  50366. * Constructor of the generator.
  50367. *
  50368. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50369. * @param inputSize The size of the cubemap faces
  50370. * @param outputSize The size of the output cubemap faces
  50371. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50372. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50373. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50374. * @param specularPower The max specular level of the desired cubemap
  50375. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50376. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50377. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50378. */
  50379. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50380. this.input = input;
  50381. this.inputSize = inputSize;
  50382. this.outputSize = outputSize;
  50383. this.maxNumMipLevels = maxNumMipLevels;
  50384. this.numChannels = numChannels;
  50385. this.isFloat = isFloat;
  50386. this.specularPower = specularPower;
  50387. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50388. this.excludeBase = excludeBase;
  50389. this.fixup = fixup;
  50390. this._outputSurface = [];
  50391. this._numMipLevels = 0;
  50392. }
  50393. /**
  50394. * Launches the filter process and return the result.
  50395. *
  50396. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50397. */
  50398. PMREMGenerator.prototype.filterCubeMap = function () {
  50399. // Init cubemap processor
  50400. this.init();
  50401. // Filters the cubemap
  50402. this.filterCubeMapMipChain();
  50403. // Returns the filtered mips.
  50404. return this._outputSurface;
  50405. };
  50406. PMREMGenerator.prototype.init = function () {
  50407. var i;
  50408. var j;
  50409. var mipLevelSize;
  50410. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50411. if (this.maxNumMipLevels == 0) {
  50412. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50413. }
  50414. //first miplevel size
  50415. mipLevelSize = this.outputSize;
  50416. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50417. for (j = 0; j < this.maxNumMipLevels; j++) {
  50418. this._outputSurface.length++;
  50419. this._outputSurface[j] = [];
  50420. //Iterate over faces for output images
  50421. for (i = 0; i < 6; i++) {
  50422. this._outputSurface[j].length++;
  50423. // Initializes a new array for the output.
  50424. if (this.isFloat) {
  50425. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50426. }
  50427. else {
  50428. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50429. }
  50430. }
  50431. //next mip level is half size
  50432. mipLevelSize >>= 1;
  50433. this._numMipLevels++;
  50434. //terminate if mip chain becomes too small
  50435. if (mipLevelSize == 0) {
  50436. this.maxNumMipLevels = j;
  50437. return;
  50438. }
  50439. }
  50440. };
  50441. //--------------------------------------------------------------------------------------
  50442. //Cube map filtering and mip chain generation.
  50443. // the cube map filtereing is specified using a number of parameters:
  50444. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50445. // indicates the region of the hemisphere to filter over for each tap.
  50446. //
  50447. // Note that the top mip level is also a filtered version of the original input images
  50448. // as well in order to create mip chains for diffuse environment illumination.
  50449. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50450. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50451. //
  50452. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50453. // is a_InitialMipAngle
  50454. //
  50455. // The angle for the subsequent levels of the mip chain are specified by their parents
  50456. // filtering angle and a per-level scale and bias
  50457. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50458. //
  50459. //--------------------------------------------------------------------------------------
  50460. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50461. // First, take count of the lighting model to modify SpecularPower
  50462. // 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;
  50463. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50464. //Cone angle start (for generating subsequent mip levels)
  50465. var currentSpecularPower = this.specularPower;
  50466. //Build filter lookup tables based on the source miplevel size
  50467. this.precomputeFilterLookupTables(this.inputSize);
  50468. // Note that we need to filter the first level before generating mipmap
  50469. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50470. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50471. // TODO : Write a function to copy and scale the base mipmap in output
  50472. // I am just lazy here and just put a high specular power value, and do some if.
  50473. if (this.excludeBase && (levelIndex == 0)) {
  50474. // 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).
  50475. currentSpecularPower = 100000.0;
  50476. }
  50477. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50478. var srcCubeImage = this.input;
  50479. var dstCubeImage = this._outputSurface[levelIndex];
  50480. var dstSize = this.outputSize >> levelIndex;
  50481. // Compute required angle.
  50482. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50483. // filter cube surfaces
  50484. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50485. // fix seams
  50486. if (this.fixup) {
  50487. this.fixupCubeEdges(dstCubeImage, dstSize);
  50488. }
  50489. // Decrease the specular power to generate the mipmap chain
  50490. // TODO : Use another method for Exclude (see first comment at start of the function
  50491. if (this.excludeBase && (levelIndex == 0)) {
  50492. currentSpecularPower = this.specularPower;
  50493. }
  50494. currentSpecularPower *= this.cosinePowerDropPerMip;
  50495. }
  50496. };
  50497. //--------------------------------------------------------------------------------------
  50498. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50499. // It allow to optimize the texel to access base on the specular power.
  50500. //--------------------------------------------------------------------------------------
  50501. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50502. // We want to find the alpha such that:
  50503. // cos(alpha)^cosinePower = epsilon
  50504. // That's: acos(epsilon^(1/cosinePower))
  50505. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50506. var angle = 180.0;
  50507. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50508. angle *= 180.0 / Math.PI; // Convert to degree
  50509. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50510. return angle;
  50511. };
  50512. //--------------------------------------------------------------------------------------
  50513. //Builds the following lookup tables prior to filtering:
  50514. // -normalizer cube map
  50515. // -tap weight lookup table
  50516. //
  50517. //--------------------------------------------------------------------------------------
  50518. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50519. var srcTexelAngle;
  50520. var iCubeFace;
  50521. //clear pre-existing normalizer cube map
  50522. this._normCubeMap = [];
  50523. //Normalized vectors per cubeface and per-texel solid angle
  50524. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50525. };
  50526. //--------------------------------------------------------------------------------------
  50527. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50528. //
  50529. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50530. //
  50531. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50532. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50533. // below
  50534. //--------------------------------------------------------------------------------------
  50535. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50536. var iCubeFace;
  50537. var u;
  50538. var v;
  50539. //iterate over cube faces
  50540. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50541. //First three channels for norm cube, and last channel for solid angle
  50542. this._normCubeMap.push(new Float32Array(size * size * 4));
  50543. //fast texture walk, build normalizer cube map
  50544. var facesData = this.input[iCubeFace];
  50545. for (v = 0; v < size; v++) {
  50546. for (u = 0; u < size; u++) {
  50547. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50548. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50549. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50550. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50551. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50552. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50553. }
  50554. }
  50555. }
  50556. };
  50557. //--------------------------------------------------------------------------------------
  50558. // Convert cubemap face texel coordinates and face idx to 3D vector
  50559. // note the U and V coords are integer coords and range from 0 to size-1
  50560. // this routine can be used to generate a normalizer cube map
  50561. //--------------------------------------------------------------------------------------
  50562. // SL BEGIN
  50563. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50564. var nvcU;
  50565. var nvcV;
  50566. var tempVec;
  50567. // Change from original AMD code
  50568. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50569. // + 0.5f is for texel center addressing
  50570. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50571. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50572. // warp fixup
  50573. if (fixup && size > 1) {
  50574. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50575. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50576. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50577. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50578. }
  50579. // Get current vector
  50580. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50581. // U contribution
  50582. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50583. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50584. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50585. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50586. // V contribution and Sum
  50587. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50588. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50589. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50590. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50591. //add face axis
  50592. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50593. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50594. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50595. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50596. //normalize vector
  50597. PMREMGenerator._vectorTemp.normalize();
  50598. return PMREMGenerator._vectorTemp;
  50599. };
  50600. //--------------------------------------------------------------------------------------
  50601. // Convert 3D vector to cubemap face texel coordinates and face idx
  50602. // note the U and V coords are integer coords and range from 0 to size-1
  50603. // this routine can be used to generate a normalizer cube map
  50604. //
  50605. // returns face IDX and texel coords
  50606. //--------------------------------------------------------------------------------------
  50607. // SL BEGIN
  50608. /*
  50609. Mapping Texture Coordinates to Cube Map Faces
  50610. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50611. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50612. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50613. map arrangement in Pixar's RenderMan package.
  50614. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50615. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50616. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50617. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50618. the major axis direction). The target column in the table below explains how the major axis direction
  50619. maps to the 2D image of a particular cube map target.
  50620. major axis
  50621. direction target sc tc ma
  50622. ---------- --------------------------------- --- --- ---
  50623. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50624. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50625. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50626. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50627. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50628. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50629. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50630. an updated (s,t) is calculated as follows
  50631. s = ( sc/|ma| + 1 ) / 2
  50632. t = ( tc/|ma| + 1 ) / 2
  50633. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50634. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50635. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50636. */
  50637. // Note this method return U and V in range from 0 to size-1
  50638. // SL END
  50639. // Store the information in vector3 for convenience (faceindex, u, v)
  50640. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50641. var maxCoord;
  50642. var faceIdx;
  50643. //absolute value 3
  50644. var absX = Math.abs(x);
  50645. var absY = Math.abs(y);
  50646. var absZ = Math.abs(z);
  50647. if (absX >= absY && absX >= absZ) {
  50648. maxCoord = absX;
  50649. if (x >= 0) {
  50650. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50651. }
  50652. else {
  50653. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50654. }
  50655. }
  50656. else if (absY >= absX && absY >= absZ) {
  50657. maxCoord = absY;
  50658. if (y >= 0) {
  50659. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50660. }
  50661. else {
  50662. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50663. }
  50664. }
  50665. else {
  50666. maxCoord = absZ;
  50667. if (z >= 0) {
  50668. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50669. }
  50670. else {
  50671. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50672. }
  50673. }
  50674. //divide through by max coord so face vector lies on cube face
  50675. var scale = 1 / maxCoord;
  50676. x *= scale;
  50677. y *= scale;
  50678. z *= scale;
  50679. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50680. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50681. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50682. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50683. // Modify original AMD code to return value from 0 to Size - 1
  50684. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50685. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50686. PMREMGenerator._vectorTemp.x = faceIdx;
  50687. PMREMGenerator._vectorTemp.y = u;
  50688. PMREMGenerator._vectorTemp.z = v;
  50689. return PMREMGenerator._vectorTemp;
  50690. };
  50691. //--------------------------------------------------------------------------------------
  50692. //Original code from Ignacio CastaÒo
  50693. // This formula is from Manne ÷hrstrˆm's thesis.
  50694. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50695. // cube face and return the area of the projection of that portion on the
  50696. // surface of the sphere.
  50697. //--------------------------------------------------------------------------------------
  50698. PMREMGenerator.prototype.areaElement = function (x, y) {
  50699. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50700. };
  50701. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50702. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50703. // (+ 0.5f is for texel center addressing)
  50704. u = (2.0 * (u + 0.5) / size) - 1.0;
  50705. v = (2.0 * (v + 0.5) / size) - 1.0;
  50706. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50707. var invResolution = 1.0 / size;
  50708. // U and V are the -1..1 texture coordinate on the current face.
  50709. // Get projected area for this texel
  50710. var x0 = u - invResolution;
  50711. var y0 = v - invResolution;
  50712. var x1 = u + invResolution;
  50713. var y1 = v + invResolution;
  50714. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50715. return solidAngle;
  50716. };
  50717. //--------------------------------------------------------------------------------------
  50718. //The key to the speed of these filtering routines is to quickly define a per-face
  50719. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50720. // Later these pixels are selectively processed based on their dot products to see if
  50721. // they reside within the filtering cone.
  50722. //
  50723. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50724. // of the number of texels needed to be covered in width and height order to filter the
  50725. // region. the bounding box for the center taps face is defined first, and if the
  50726. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50727. // defined next
  50728. //--------------------------------------------------------------------------------------
  50729. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50730. // note that pixels within these regions may be rejected
  50731. // based on the anlge
  50732. var iCubeFace;
  50733. var u;
  50734. var v;
  50735. // bounding box per face to specify region to process
  50736. var filterExtents = [];
  50737. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50738. filterExtents.push(new CMGBoundinBox());
  50739. }
  50740. // min angle a src texel can cover (in degrees)
  50741. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50742. // angle about center tap to define filter cone
  50743. // filter angle is 1/2 the cone angle
  50744. var filterAngle = filterConeAngle / 2.0;
  50745. //ensure filter angle is larger than a texel
  50746. if (filterAngle < srcTexelAngle) {
  50747. filterAngle = srcTexelAngle;
  50748. }
  50749. //ensure filter cone is always smaller than the hemisphere
  50750. if (filterAngle > 90.0) {
  50751. filterAngle = 90.0;
  50752. }
  50753. // the maximum number of texels in 1D the filter cone angle will cover
  50754. // used to determine bounding box size for filter extents
  50755. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50756. // ensure conservative region always covers at least one texel
  50757. if (filterSize < 1) {
  50758. filterSize = 1;
  50759. }
  50760. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50761. // reside within the cone angle
  50762. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50763. // process required faces
  50764. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50765. //iterate over dst cube map face texel
  50766. for (v = 0; v < dstSize; v++) {
  50767. for (u = 0; u < dstSize; u++) {
  50768. //get center tap direction
  50769. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50770. //clear old per-face filter extents
  50771. this.clearFilterExtents(filterExtents);
  50772. //define per-face filter extents
  50773. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50774. //perform filtering of src faces using filter extents
  50775. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50776. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50777. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50778. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50779. }
  50780. }
  50781. }
  50782. };
  50783. //--------------------------------------------------------------------------------------
  50784. //Clear filter extents for the 6 cube map faces
  50785. //--------------------------------------------------------------------------------------
  50786. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50787. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50788. filterExtents[iCubeFaces].clear();
  50789. }
  50790. };
  50791. //--------------------------------------------------------------------------------------
  50792. //Define per-face bounding box filter extents
  50793. //
  50794. // These define conservative texel regions in each of the faces the filter can possibly
  50795. // process. When the pixels in the regions are actually processed, the dot product
  50796. // between the tap vector and the center tap vector is used to determine the weight of
  50797. // the tap and whether or not the tap is within the cone.
  50798. //
  50799. //--------------------------------------------------------------------------------------
  50800. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50801. //neighboring face and bleed over amount, and width of BBOX for
  50802. // left, right, top, and bottom edges of this face
  50803. var bleedOverAmount = [0, 0, 0, 0];
  50804. var bleedOverBBoxMin = [0, 0, 0, 0];
  50805. var bleedOverBBoxMax = [0, 0, 0, 0];
  50806. var neighborFace;
  50807. var neighborEdge;
  50808. var oppositeFaceIdx;
  50809. //get face idx, and u, v info from center tap dir
  50810. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50811. var faceIdx = result.x;
  50812. var u = result.y;
  50813. var v = result.z;
  50814. //define bbox size within face
  50815. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50816. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50817. filterExtents[faceIdx].clampMin(0, 0, 0);
  50818. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50819. //u and v extent in face corresponding to center tap
  50820. var minU = filterExtents[faceIdx].min.x;
  50821. var minV = filterExtents[faceIdx].min.y;
  50822. var maxU = filterExtents[faceIdx].max.x;
  50823. var maxV = filterExtents[faceIdx].max.y;
  50824. //bleed over amounts for face across u=0 edge (left)
  50825. bleedOverAmount[0] = (bboxSize - u);
  50826. bleedOverBBoxMin[0] = minV;
  50827. bleedOverBBoxMax[0] = maxV;
  50828. //bleed over amounts for face across u=1 edge (right)
  50829. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50830. bleedOverBBoxMin[1] = minV;
  50831. bleedOverBBoxMax[1] = maxV;
  50832. //bleed over to face across v=0 edge (up)
  50833. bleedOverAmount[2] = (bboxSize - v);
  50834. bleedOverBBoxMin[2] = minU;
  50835. bleedOverBBoxMax[2] = maxU;
  50836. //bleed over to face across v=1 edge (down)
  50837. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50838. bleedOverBBoxMin[3] = minU;
  50839. bleedOverBBoxMax[3] = maxU;
  50840. //compute bleed over regions in neighboring faces
  50841. for (var i = 0; i < 4; i++) {
  50842. if (bleedOverAmount[i] > 0) {
  50843. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50844. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50845. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50846. // be flipped: the cases are
  50847. // if a left edge mates with a left or bottom edge on the neighbor
  50848. // if a top edge mates with a top or right edge on the neighbor
  50849. // if a right edge mates with a right or top edge on the neighbor
  50850. // if a bottom edge mates with a bottom or left edge on the neighbor
  50851. //Seeing as the edges are enumerated as follows
  50852. // left =0
  50853. // right =1
  50854. // top =2
  50855. // bottom =3
  50856. //
  50857. // so if the edge enums are the same, or the sum of the enums == 3,
  50858. // the bbox needs to be flipped
  50859. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50860. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50861. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50862. }
  50863. //The way the bounding box is extended onto the neighboring face
  50864. // depends on which edge of neighboring face abuts with this one
  50865. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50866. case PMREMGenerator.CP_EDGE_LEFT:
  50867. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50868. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50869. break;
  50870. case PMREMGenerator.CP_EDGE_RIGHT:
  50871. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50872. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50873. break;
  50874. case PMREMGenerator.CP_EDGE_TOP:
  50875. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50876. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50877. break;
  50878. case PMREMGenerator.CP_EDGE_BOTTOM:
  50879. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50880. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50881. break;
  50882. }
  50883. //clamp filter extents in non-center tap faces to remain within surface
  50884. filterExtents[neighborFace].clampMin(0, 0, 0);
  50885. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50886. }
  50887. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50888. // from the center tap face, then process the opposite face entirely for now.
  50889. //Note that the cases in which this happens, what usually happens is that
  50890. // more than one edge bleeds onto the opposite face, and the bounding box
  50891. // encompasses the entire cube map face.
  50892. if (bleedOverAmount[i] > srcSize) {
  50893. //determine opposite face
  50894. switch (faceIdx) {
  50895. case PMREMGenerator.CP_FACE_X_POS:
  50896. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50897. break;
  50898. case PMREMGenerator.CP_FACE_X_NEG:
  50899. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50900. break;
  50901. case PMREMGenerator.CP_FACE_Y_POS:
  50902. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50903. break;
  50904. case PMREMGenerator.CP_FACE_Y_NEG:
  50905. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50906. break;
  50907. case PMREMGenerator.CP_FACE_Z_POS:
  50908. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50909. break;
  50910. case PMREMGenerator.CP_FACE_Z_NEG:
  50911. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50912. break;
  50913. default:
  50914. break;
  50915. }
  50916. //just encompass entire face for now
  50917. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50918. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50919. }
  50920. }
  50921. };
  50922. //--------------------------------------------------------------------------------------
  50923. //ProcessFilterExtents
  50924. // Process bounding box in each cube face
  50925. //
  50926. //--------------------------------------------------------------------------------------
  50927. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50928. //accumulators are 64-bit floats in order to have the precision needed
  50929. // over a summation of a large number of pixels
  50930. var dstAccum = [0, 0, 0, 0];
  50931. var weightAccum = 0;
  50932. var k = 0;
  50933. var nSrcChannels = this.numChannels;
  50934. // norm cube map and srcCubeMap have same face width
  50935. var faceWidth = srcSize;
  50936. //amount to add to pointer to move to next scanline in images
  50937. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50938. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50939. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50940. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50941. // iterate over cubefaces
  50942. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50943. //if bbox is non empty
  50944. if (!filterExtents[iFaceIdx].empty()) {
  50945. var uStart = filterExtents[iFaceIdx].min.x;
  50946. var vStart = filterExtents[iFaceIdx].min.y;
  50947. var uEnd = filterExtents[iFaceIdx].max.x;
  50948. var vEnd = filterExtents[iFaceIdx].max.y;
  50949. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50950. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50951. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50952. for (var v = vStart; v <= vEnd; v++) {
  50953. var normCubeRowWalk = 0;
  50954. var srcCubeRowWalk = 0;
  50955. for (var u = uStart; u <= uEnd; u++) {
  50956. //pointer to direction in cube map associated with texel
  50957. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50958. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50959. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50960. //check dot product to see if texel is within cone
  50961. var tapDotProd = texelVectX * centerTapDir.x +
  50962. texelVectY * centerTapDir.y +
  50963. texelVectZ * centerTapDir.z;
  50964. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50965. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50966. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50967. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50968. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50969. // so just adding one to specularpower do the trick.
  50970. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50971. //iterate over channels
  50972. for (k = 0; k < nSrcChannels; k++) {
  50973. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50974. srcCubeRowWalk++;
  50975. }
  50976. weightAccum += weight; //accumulate weight
  50977. }
  50978. else {
  50979. //step across source pixel
  50980. srcCubeRowWalk += nSrcChannels;
  50981. }
  50982. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50983. }
  50984. startIndexNormCubeMap += normCubePitch;
  50985. startIndexSrcCubeMap += srcCubePitch;
  50986. }
  50987. }
  50988. }
  50989. //divide through by weights if weight is non zero
  50990. if (weightAccum != 0.0) {
  50991. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  50992. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  50993. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  50994. if (this.numChannels > 3) {
  50995. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50996. }
  50997. }
  50998. else {
  50999. // otherwise sample nearest
  51000. // get face idx and u, v texel coordinate in face
  51001. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51002. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51003. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51004. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51005. if (this.numChannels > 3) {
  51006. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51007. }
  51008. }
  51009. return PMREMGenerator._vectorTemp;
  51010. };
  51011. //--------------------------------------------------------------------------------------
  51012. // Fixup cube edges
  51013. //
  51014. // average texels on cube map faces across the edges
  51015. // WARP/BENT Method Only.
  51016. //--------------------------------------------------------------------------------------
  51017. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51018. var k;
  51019. var j;
  51020. var i;
  51021. var iFace;
  51022. var iCorner = 0;
  51023. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51024. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51025. // note that if functionality to filter across the three texels for each corner, then
  51026. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51027. var cornerPtr = [
  51028. [[], [], []],
  51029. [[], [], []],
  51030. [[], [], []],
  51031. [[], [], []],
  51032. [[], [], []],
  51033. [[], [], []],
  51034. [[], [], []],
  51035. [[], [], []]
  51036. ];
  51037. //if there is no fixup, or fixup width = 0, do nothing
  51038. if (cubeMapSize < 1) {
  51039. return;
  51040. }
  51041. //special case 1x1 cubemap, average face colors
  51042. if (cubeMapSize == 1) {
  51043. //iterate over channels
  51044. for (k = 0; k < this.numChannels; k++) {
  51045. var accum = 0.0;
  51046. //iterate over faces to accumulate face colors
  51047. for (iFace = 0; iFace < 6; iFace++) {
  51048. accum += cubeMap[iFace][k];
  51049. }
  51050. //compute average over 6 face colors
  51051. accum /= 6.0;
  51052. //iterate over faces to distribute face colors
  51053. for (iFace = 0; iFace < 6; iFace++) {
  51054. cubeMap[iFace][k] = accum;
  51055. }
  51056. }
  51057. return;
  51058. }
  51059. //iterate over faces to collect list of corner texel pointers
  51060. for (iFace = 0; iFace < 6; iFace++) {
  51061. //the 4 corner pointers for this face
  51062. faceCornerStartIndicies[0] = [iFace, 0];
  51063. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51064. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51065. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51066. //iterate over face corners to collect cube corner pointers
  51067. for (iCorner = 0; iCorner < 4; iCorner++) {
  51068. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51069. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51070. cornerNumPtrs[corner]++;
  51071. }
  51072. }
  51073. //iterate over corners to average across corner tap values
  51074. for (iCorner = 0; iCorner < 8; iCorner++) {
  51075. for (k = 0; k < this.numChannels; k++) {
  51076. var cornerTapAccum = 0.0;
  51077. //iterate over corner texels and average results
  51078. for (i = 0; i < 3; i++) {
  51079. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51080. }
  51081. //divide by 3 to compute average of corner tap values
  51082. cornerTapAccum *= (1.0 / 3.0);
  51083. //iterate over corner texels and average results
  51084. for (i = 0; i < 3; i++) {
  51085. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51086. }
  51087. }
  51088. }
  51089. //iterate over the twelve edges of the cube to average across edges
  51090. for (i = 0; i < 12; i++) {
  51091. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51092. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51093. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51094. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51095. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51096. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51097. var edgeWalk = 0;
  51098. var neighborEdgeWalk = 0;
  51099. //Determine walking pointers based on edge type
  51100. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51101. switch (edge) {
  51102. case PMREMGenerator.CP_EDGE_LEFT:
  51103. // no change to faceEdgeStartPtr
  51104. edgeWalk = this.numChannels * cubeMapSize;
  51105. break;
  51106. case PMREMGenerator.CP_EDGE_RIGHT:
  51107. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51108. edgeWalk = this.numChannels * cubeMapSize;
  51109. break;
  51110. case PMREMGenerator.CP_EDGE_TOP:
  51111. // no change to faceEdgeStartPtr
  51112. edgeWalk = this.numChannels;
  51113. break;
  51114. case PMREMGenerator.CP_EDGE_BOTTOM:
  51115. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51116. edgeWalk = this.numChannels;
  51117. break;
  51118. }
  51119. //For certain types of edge abutments, the neighbor edge walk needs to
  51120. // be flipped: the cases are
  51121. // if a left edge mates with a left or bottom edge on the neighbor
  51122. // if a top edge mates with a top or right edge on the neighbor
  51123. // if a right edge mates with a right or top edge on the neighbor
  51124. // if a bottom edge mates with a bottom or left edge on the neighbor
  51125. //Seeing as the edges are enumerated as follows
  51126. // left =0
  51127. // right =1
  51128. // top =2
  51129. // bottom =3
  51130. //
  51131. //If the edge enums are the same, or the sum of the enums == 3,
  51132. // the neighbor edge walk needs to be flipped
  51133. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51134. switch (neighborEdge) {
  51135. case PMREMGenerator.CP_EDGE_LEFT:
  51136. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51137. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51138. break;
  51139. case PMREMGenerator.CP_EDGE_RIGHT:
  51140. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51141. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51142. break;
  51143. case PMREMGenerator.CP_EDGE_TOP:
  51144. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51145. neighborEdgeWalk = -this.numChannels;
  51146. break;
  51147. case PMREMGenerator.CP_EDGE_BOTTOM:
  51148. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51149. neighborEdgeWalk = -this.numChannels;
  51150. break;
  51151. }
  51152. }
  51153. else {
  51154. //swapped direction neighbor edge walk
  51155. switch (neighborEdge) {
  51156. case PMREMGenerator.CP_EDGE_LEFT:
  51157. //no change to neighborEdgeStartPtr for this case since it points
  51158. // to the upper left corner already
  51159. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51160. break;
  51161. case PMREMGenerator.CP_EDGE_RIGHT:
  51162. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51163. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51164. break;
  51165. case PMREMGenerator.CP_EDGE_TOP:
  51166. //no change to neighborEdgeStartPtr for this case since it points
  51167. // to the upper left corner already
  51168. neighborEdgeWalk = this.numChannels;
  51169. break;
  51170. case PMREMGenerator.CP_EDGE_BOTTOM:
  51171. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51172. neighborEdgeWalk = this.numChannels;
  51173. break;
  51174. }
  51175. }
  51176. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51177. //nearby neighborhood
  51178. //step ahead one texel on edge
  51179. edgeStartIndex += edgeWalk;
  51180. neighborEdgeStartIndex += neighborEdgeWalk;
  51181. // note that this loop does not process the corner texels, since they have already been
  51182. // averaged across faces across earlier
  51183. for (j = 1; j < (cubeMapSize - 1); j++) {
  51184. //for each set of taps along edge, average them
  51185. // and rewrite the results into the edges
  51186. for (k = 0; k < this.numChannels; k++) {
  51187. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51188. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51189. //compute average of tap intensity values
  51190. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51191. //propagate average of taps to edge taps
  51192. cubeMap[face][edgeStartIndex + k] = avgTap;
  51193. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51194. }
  51195. edgeStartIndex += edgeWalk;
  51196. neighborEdgeStartIndex += neighborEdgeWalk;
  51197. }
  51198. }
  51199. };
  51200. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51201. PMREMGenerator.CP_UDIR = 0;
  51202. PMREMGenerator.CP_VDIR = 1;
  51203. PMREMGenerator.CP_FACEAXIS = 2;
  51204. //used to index cube faces
  51205. PMREMGenerator.CP_FACE_X_POS = 0;
  51206. PMREMGenerator.CP_FACE_X_NEG = 1;
  51207. PMREMGenerator.CP_FACE_Y_POS = 2;
  51208. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51209. PMREMGenerator.CP_FACE_Z_POS = 4;
  51210. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51211. //used to index image edges
  51212. // NOTE.. the actual number corresponding to the edge is important
  51213. // do not change these, or the code will break
  51214. //
  51215. // CP_EDGE_LEFT is u = 0
  51216. // CP_EDGE_RIGHT is u = width-1
  51217. // CP_EDGE_TOP is v = 0
  51218. // CP_EDGE_BOTTOM is v = height-1
  51219. PMREMGenerator.CP_EDGE_LEFT = 0;
  51220. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51221. PMREMGenerator.CP_EDGE_TOP = 2;
  51222. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51223. //corners of CUBE map (P or N specifys if it corresponds to the
  51224. // positive or negative direction each of X, Y, and Z
  51225. PMREMGenerator.CP_CORNER_NNN = 0;
  51226. PMREMGenerator.CP_CORNER_NNP = 1;
  51227. PMREMGenerator.CP_CORNER_NPN = 2;
  51228. PMREMGenerator.CP_CORNER_NPP = 3;
  51229. PMREMGenerator.CP_CORNER_PNN = 4;
  51230. PMREMGenerator.CP_CORNER_PNP = 5;
  51231. PMREMGenerator.CP_CORNER_PPN = 6;
  51232. PMREMGenerator.CP_CORNER_PPP = 7;
  51233. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51234. //3x2 matrices that map cube map indexing vectors in 3d
  51235. // (after face selection and divide through by the
  51236. // _ABSOLUTE VALUE_ of the max coord)
  51237. // into NVC space
  51238. //Note this currently assumes the D3D cube face ordering and orientation
  51239. PMREMGenerator._sgFace2DMapping = [
  51240. //XPOS face
  51241. [[0, 0, -1],
  51242. [0, -1, 0],
  51243. [1, 0, 0]],
  51244. //XNEG face
  51245. [[0, 0, 1],
  51246. [0, -1, 0],
  51247. [-1, 0, 0]],
  51248. //YPOS face
  51249. [[1, 0, 0],
  51250. [0, 0, 1],
  51251. [0, 1, 0]],
  51252. //YNEG face
  51253. [[1, 0, 0],
  51254. [0, 0, -1],
  51255. [0, -1, 0]],
  51256. //ZPOS face
  51257. [[1, 0, 0],
  51258. [0, -1, 0],
  51259. [0, 0, 1]],
  51260. //ZNEG face
  51261. [[-1, 0, 0],
  51262. [0, -1, 0],
  51263. [0, 0, -1]],
  51264. ];
  51265. //------------------------------------------------------------------------------
  51266. // D3D cube map face specification
  51267. // mapping from 3D x,y,z cube map lookup coordinates
  51268. // to 2D within face u,v coordinates
  51269. //
  51270. // --------------------> U direction
  51271. // | (within-face texture space)
  51272. // | _____
  51273. // | | |
  51274. // | | +Y |
  51275. // | _____|_____|_____ _____
  51276. // | | | | | |
  51277. // | | -X | +Z | +X | -Z |
  51278. // | |_____|_____|_____|_____|
  51279. // | | |
  51280. // | | -Y |
  51281. // | |_____|
  51282. // |
  51283. // v V direction
  51284. // (within-face texture space)
  51285. //------------------------------------------------------------------------------
  51286. //Information about neighbors and how texture coorrdinates change across faces
  51287. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51288. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51289. //Note this currently assumes the D3D cube face ordering and orientation
  51290. PMREMGenerator._sgCubeNgh = [
  51291. //XPOS face
  51292. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51293. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51294. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51295. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51296. //XNEG face
  51297. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51298. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51299. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51300. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51301. //YPOS face
  51302. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51303. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51304. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51305. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51306. //YNEG face
  51307. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51308. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51309. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51310. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51311. //ZPOS face
  51312. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51313. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51314. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51315. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51316. //ZNEG face
  51317. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51318. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51319. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51320. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51321. ];
  51322. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51323. // this table is used to average over the edges.
  51324. PMREMGenerator._sgCubeEdgeList = [
  51325. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51326. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51327. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51328. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51329. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51330. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51331. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51332. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51333. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51334. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51335. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51336. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51337. ];
  51338. //Information about which of the 8 cube corners are correspond to the
  51339. // the 4 corners in each cube face
  51340. // the order is upper left, upper right, lower left, lower right
  51341. PMREMGenerator._sgCubeCornerList = [
  51342. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51343. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51344. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51345. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51346. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51347. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51348. ];
  51349. return PMREMGenerator;
  51350. }());
  51351. Internals.PMREMGenerator = PMREMGenerator;
  51352. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51353. })(BABYLON || (BABYLON = {}));
  51354. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  51355. var BABYLON;
  51356. (function (BABYLON) {
  51357. /**
  51358. * This represents a texture coming from an HDR input.
  51359. *
  51360. * The only supported format is currently panorama picture stored in RGBE format.
  51361. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51362. */
  51363. var HDRCubeTexture = (function (_super) {
  51364. __extends(HDRCubeTexture, _super);
  51365. /**
  51366. * Instantiates an HDRTexture from the following parameters.
  51367. *
  51368. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51369. * @param scene The scene the texture will be used in
  51370. * @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.
  51371. * @param noMipmap Forces to not generate the mipmap if true
  51372. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51373. * @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)
  51374. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51375. */
  51376. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51377. if (noMipmap === void 0) { noMipmap = false; }
  51378. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51379. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51380. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51381. _super.call(this, scene);
  51382. this._useInGammaSpace = false;
  51383. this._generateHarmonics = true;
  51384. this._isBABYLONPreprocessed = false;
  51385. /**
  51386. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51387. */
  51388. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51389. /**
  51390. * The spherical polynomial data extracted from the texture.
  51391. */
  51392. this.sphericalPolynomial = null;
  51393. /**
  51394. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51395. * This is usefull at run time to apply the good shader.
  51396. */
  51397. this.isPMREM = false;
  51398. if (!url) {
  51399. return;
  51400. }
  51401. this.name = url;
  51402. this.url = url;
  51403. this.hasAlpha = false;
  51404. this.isCube = true;
  51405. this._textureMatrix = BABYLON.Matrix.Identity();
  51406. if (size) {
  51407. this._isBABYLONPreprocessed = false;
  51408. this._noMipmap = noMipmap;
  51409. this._size = size;
  51410. this._useInGammaSpace = useInGammaSpace;
  51411. this._usePMREMGenerator = usePMREMGenerator &&
  51412. scene.getEngine().getCaps().textureLOD &&
  51413. this.getScene().getEngine().getCaps().textureFloat &&
  51414. !this._useInGammaSpace;
  51415. }
  51416. else {
  51417. this._isBABYLONPreprocessed = true;
  51418. this._noMipmap = false;
  51419. this._useInGammaSpace = false;
  51420. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51421. this.getScene().getEngine().getCaps().textureFloat &&
  51422. !this._useInGammaSpace;
  51423. }
  51424. this.isPMREM = this._usePMREMGenerator;
  51425. this._texture = this._getFromCache(url, this._noMipmap);
  51426. if (!this._texture) {
  51427. if (!scene.useDelayedTextureLoading) {
  51428. this.loadTexture();
  51429. }
  51430. else {
  51431. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51432. }
  51433. }
  51434. }
  51435. /**
  51436. * Occurs when the file is a preprocessed .babylon.hdr file.
  51437. */
  51438. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51439. var _this = this;
  51440. var mipLevels = 0;
  51441. var floatArrayView = null;
  51442. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51443. var mips = [];
  51444. var startIndex = 30;
  51445. for (var level = 0; level < mipLevels; level++) {
  51446. mips.push([]);
  51447. // Fill each pixel of the mip level.
  51448. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51449. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51450. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51451. mips[level].push(faceData);
  51452. startIndex += faceSize;
  51453. }
  51454. }
  51455. return mips;
  51456. } : null;
  51457. var callback = function (buffer) {
  51458. // Create Native Array Views
  51459. var intArrayView = new Int32Array(buffer);
  51460. floatArrayView = new Float32Array(buffer);
  51461. // Fill header.
  51462. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51463. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51464. // Update Texture Information.
  51465. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51466. // Fill polynomial information.
  51467. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51468. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51469. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51470. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51471. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51472. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51473. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51474. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51475. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51476. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51477. // Fill pixel data.
  51478. mipLevels = intArrayView[29]; // Number of mip levels.
  51479. var startIndex = 30;
  51480. var data = [];
  51481. var faceSize = Math.pow(_this._size, 2) * 3;
  51482. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51483. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51484. startIndex += faceSize;
  51485. }
  51486. var results = [];
  51487. var byteArray = null;
  51488. // Push each faces.
  51489. for (var k = 0; k < 6; k++) {
  51490. var dataFace = null;
  51491. // If special cases.
  51492. if (!mipmapGenerator) {
  51493. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51494. dataFace = data[j];
  51495. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51496. // 3 channels of 1 bytes per pixel in bytes.
  51497. var byteBuffer = new ArrayBuffer(faceSize);
  51498. byteArray = new Uint8Array(byteBuffer);
  51499. }
  51500. for (var i = 0; i < _this._size * _this._size; i++) {
  51501. // Put in gamma space if requested.
  51502. if (_this._useInGammaSpace) {
  51503. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51504. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51505. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51506. }
  51507. // Convert to int texture for fallback.
  51508. if (byteArray) {
  51509. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51510. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51511. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51512. // May use luminance instead if the result is not accurate.
  51513. var max = Math.max(Math.max(r, g), b);
  51514. if (max > 255) {
  51515. var scale = 255 / max;
  51516. r *= scale;
  51517. g *= scale;
  51518. b *= scale;
  51519. }
  51520. byteArray[(i * 3) + 0] = r;
  51521. byteArray[(i * 3) + 1] = g;
  51522. byteArray[(i * 3) + 2] = b;
  51523. }
  51524. }
  51525. }
  51526. else {
  51527. dataFace = data[k];
  51528. }
  51529. // Fill the array accordingly.
  51530. if (byteArray) {
  51531. results.push(byteArray);
  51532. }
  51533. else {
  51534. results.push(dataFace);
  51535. }
  51536. }
  51537. return results;
  51538. };
  51539. 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);
  51540. };
  51541. /**
  51542. * Occurs when the file is raw .hdr file.
  51543. */
  51544. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51545. var _this = this;
  51546. var callback = function (buffer) {
  51547. // Extract the raw linear data.
  51548. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51549. // Generate harmonics if needed.
  51550. if (_this._generateHarmonics) {
  51551. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51552. }
  51553. var results = [];
  51554. var byteArray = null;
  51555. // Push each faces.
  51556. for (var j = 0; j < 6; j++) {
  51557. // Create uintarray fallback.
  51558. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51559. // 3 channels of 1 bytes per pixel in bytes.
  51560. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51561. byteArray = new Uint8Array(byteBuffer);
  51562. }
  51563. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51564. // If special cases.
  51565. if (_this._useInGammaSpace || byteArray) {
  51566. for (var i = 0; i < _this._size * _this._size; i++) {
  51567. // Put in gamma space if requested.
  51568. if (_this._useInGammaSpace) {
  51569. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51570. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51571. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51572. }
  51573. // Convert to int texture for fallback.
  51574. if (byteArray) {
  51575. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51576. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51577. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51578. // May use luminance instead if the result is not accurate.
  51579. var max = Math.max(Math.max(r, g), b);
  51580. if (max > 255) {
  51581. var scale = 255 / max;
  51582. r *= scale;
  51583. g *= scale;
  51584. b *= scale;
  51585. }
  51586. byteArray[(i * 3) + 0] = r;
  51587. byteArray[(i * 3) + 1] = g;
  51588. byteArray[(i * 3) + 2] = b;
  51589. }
  51590. }
  51591. }
  51592. if (byteArray) {
  51593. results.push(byteArray);
  51594. }
  51595. else {
  51596. results.push(dataFace);
  51597. }
  51598. }
  51599. return results;
  51600. };
  51601. var mipmapGenerator = null;
  51602. if (!this._noMipmap &&
  51603. this._usePMREMGenerator) {
  51604. mipmapGenerator = function (data) {
  51605. // Custom setup of the generator matching with the PBR shader values.
  51606. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51607. return generator.filterCubeMap();
  51608. };
  51609. }
  51610. 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);
  51611. };
  51612. /**
  51613. * Starts the loading process of the texture.
  51614. */
  51615. HDRCubeTexture.prototype.loadTexture = function () {
  51616. if (this._isBABYLONPreprocessed) {
  51617. this.loadBabylonTexture();
  51618. }
  51619. else {
  51620. this.loadHDRTexture();
  51621. }
  51622. };
  51623. HDRCubeTexture.prototype.clone = function () {
  51624. var size = this._isBABYLONPreprocessed ? null : this._size;
  51625. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51626. // Base texture
  51627. newTexture.level = this.level;
  51628. newTexture.wrapU = this.wrapU;
  51629. newTexture.wrapV = this.wrapV;
  51630. newTexture.coordinatesIndex = this.coordinatesIndex;
  51631. newTexture.coordinatesMode = this.coordinatesMode;
  51632. return newTexture;
  51633. };
  51634. // Methods
  51635. HDRCubeTexture.prototype.delayLoad = function () {
  51636. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51637. return;
  51638. }
  51639. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51640. this._texture = this._getFromCache(this.url, this._noMipmap);
  51641. if (!this._texture) {
  51642. this.loadTexture();
  51643. }
  51644. };
  51645. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51646. return this._textureMatrix;
  51647. };
  51648. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51649. var texture = null;
  51650. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51651. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51652. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51653. texture.name = parsedTexture.name;
  51654. texture.hasAlpha = parsedTexture.hasAlpha;
  51655. texture.level = parsedTexture.level;
  51656. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51657. }
  51658. return texture;
  51659. };
  51660. HDRCubeTexture.prototype.serialize = function () {
  51661. if (!this.name) {
  51662. return null;
  51663. }
  51664. var serializationObject = {};
  51665. serializationObject.name = this.name;
  51666. serializationObject.hasAlpha = this.hasAlpha;
  51667. serializationObject.isCube = true;
  51668. serializationObject.level = this.level;
  51669. serializationObject.size = this._size;
  51670. serializationObject.coordinatesMode = this.coordinatesMode;
  51671. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51672. serializationObject.generateHarmonics = this._generateHarmonics;
  51673. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51674. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51675. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51676. return serializationObject;
  51677. };
  51678. /**
  51679. * Saves as a file the data contained in the texture in a binary format.
  51680. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51681. * as the spherical used in the lighting.
  51682. * @param url The HDR file url.
  51683. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51684. * @param onError Method called if any error happens during download.
  51685. * @return The packed binary data.
  51686. */
  51687. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51688. if (onError === void 0) { onError = null; }
  51689. var callback = function (buffer) {
  51690. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51691. // Returns a URL you can use as a href.
  51692. var objUrl = window.URL.createObjectURL(data);
  51693. // Simulates a link to it and click to dowload.
  51694. var a = document.createElement("a");
  51695. document.body.appendChild(a);
  51696. a.style.display = "none";
  51697. a.href = objUrl;
  51698. a.download = "envmap.babylon.hdr";
  51699. a.click();
  51700. };
  51701. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51702. };
  51703. /**
  51704. * Serializes the data contained in the texture in a binary format.
  51705. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51706. * as the spherical used in the lighting.
  51707. * @param url The HDR file url.
  51708. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51709. * @param onError Method called if any error happens during download.
  51710. * @return The packed binary data.
  51711. */
  51712. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51713. if (onError === void 0) { onError = null; }
  51714. // Needs the url tho create the texture.
  51715. if (!url) {
  51716. return null;
  51717. }
  51718. // Check Power of two size.
  51719. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51720. return null;
  51721. }
  51722. var getDataCallback = function (dataBuffer) {
  51723. // Extract the raw linear data.
  51724. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51725. // Generate harmonics if needed.
  51726. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51727. // Generate seamless faces
  51728. var mipGeneratorArray = [];
  51729. // Data are known to be in +X +Y +Z -X -Y -Z
  51730. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51731. mipGeneratorArray.push(cubeData.right); // +X
  51732. mipGeneratorArray.push(cubeData.left); // -X
  51733. mipGeneratorArray.push(cubeData.up); // +Y
  51734. mipGeneratorArray.push(cubeData.down); // -Y
  51735. mipGeneratorArray.push(cubeData.front); // +Z
  51736. mipGeneratorArray.push(cubeData.back); // -Z
  51737. // Custom setup of the generator matching with the PBR shader values.
  51738. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51739. var mippedData = generator.filterCubeMap();
  51740. // Compute required byte length.
  51741. var byteLength = 1 * 4; // Raw Data Version int32.
  51742. byteLength += 4; // CubeMap max mip face size int32.
  51743. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51744. // Add data size.
  51745. byteLength += 4; // Number of mip levels int32.
  51746. for (var level = 0; level < mippedData.length; level++) {
  51747. var mipSize = size >> level;
  51748. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51749. }
  51750. // Prepare binary structure.
  51751. var buffer = new ArrayBuffer(byteLength);
  51752. var intArrayView = new Int32Array(buffer);
  51753. var floatArrayView = new Float32Array(buffer);
  51754. // Fill header.
  51755. intArrayView[0] = 1; // Version 1.
  51756. intArrayView[1] = size; // CubeMap max mip face size.
  51757. // Fill polynomial information.
  51758. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51759. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51760. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51761. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51762. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51763. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51764. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51765. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51766. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51767. // Fill pixel data.
  51768. intArrayView[29] = mippedData.length; // Number of mip levels.
  51769. var startIndex = 30;
  51770. for (var level = 0; level < mippedData.length; level++) {
  51771. // Fill each pixel of the mip level.
  51772. var faceSize = Math.pow(size >> level, 2) * 3;
  51773. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51774. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51775. startIndex += faceSize;
  51776. }
  51777. }
  51778. // Callback.
  51779. callback(buffer);
  51780. };
  51781. // Download and process.
  51782. BABYLON.Tools.LoadFile(url, function (data) {
  51783. getDataCallback(data);
  51784. }, null, null, true, onError);
  51785. };
  51786. HDRCubeTexture._facesMapping = [
  51787. "right",
  51788. "up",
  51789. "front",
  51790. "left",
  51791. "down",
  51792. "back"
  51793. ];
  51794. return HDRCubeTexture;
  51795. }(BABYLON.BaseTexture));
  51796. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51797. })(BABYLON || (BABYLON = {}));
  51798. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51799. var BABYLON;
  51800. (function (BABYLON) {
  51801. var Debug;
  51802. (function (Debug) {
  51803. /**
  51804. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51805. */
  51806. var SkeletonViewer = (function () {
  51807. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51808. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51809. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51810. this.skeleton = skeleton;
  51811. this.mesh = mesh;
  51812. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51813. this.renderingGroupId = renderingGroupId;
  51814. this.color = BABYLON.Color3.White();
  51815. this._debugLines = [];
  51816. this._isEnabled = false;
  51817. this._scene = scene;
  51818. this.update();
  51819. this._renderFunction = this.update.bind(this);
  51820. }
  51821. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51822. get: function () {
  51823. return this._isEnabled;
  51824. },
  51825. set: function (value) {
  51826. if (this._isEnabled === value) {
  51827. return;
  51828. }
  51829. this._isEnabled = value;
  51830. if (value) {
  51831. this._scene.registerBeforeRender(this._renderFunction);
  51832. }
  51833. else {
  51834. this._scene.unregisterBeforeRender(this._renderFunction);
  51835. }
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51841. if (x === void 0) { x = 0; }
  51842. if (y === void 0) { y = 0; }
  51843. if (z === void 0) { z = 0; }
  51844. var tmat = BABYLON.Tmp.Matrix[0];
  51845. var parentBone = bone.getParent();
  51846. tmat.copyFrom(bone.getLocalMatrix());
  51847. if (x !== 0 || y !== 0 || z !== 0) {
  51848. var tmat2 = BABYLON.Tmp.Matrix[1];
  51849. BABYLON.Matrix.IdentityToRef(tmat2);
  51850. tmat2.m[12] = x;
  51851. tmat2.m[13] = y;
  51852. tmat2.m[14] = z;
  51853. tmat2.multiplyToRef(tmat, tmat);
  51854. }
  51855. if (parentBone) {
  51856. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51857. }
  51858. tmat.multiplyToRef(meshMat, tmat);
  51859. position.x = tmat.m[12];
  51860. position.y = tmat.m[13];
  51861. position.z = tmat.m[14];
  51862. };
  51863. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  51864. var len = bones.length;
  51865. for (var i = 0; i < len; i++) {
  51866. var bone = bones[i];
  51867. var points = this._debugLines[i];
  51868. if (!points) {
  51869. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51870. this._debugLines[i] = points;
  51871. }
  51872. this._getBonePosition(points[0], bone, meshMat);
  51873. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  51874. }
  51875. };
  51876. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  51877. var len = bones.length;
  51878. var boneNum = 0;
  51879. for (var i = len - 1; i >= 0; i--) {
  51880. var childBone = bones[i];
  51881. var parentBone = childBone.getParent();
  51882. if (!parentBone) {
  51883. continue;
  51884. }
  51885. var points = this._debugLines[boneNum];
  51886. if (!points) {
  51887. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51888. this._debugLines[boneNum] = points;
  51889. }
  51890. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  51891. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  51892. boneNum++;
  51893. }
  51894. };
  51895. SkeletonViewer.prototype.update = function () {
  51896. if (this.autoUpdateBonesMatrices) {
  51897. this.skeleton.computeAbsoluteTransforms();
  51898. }
  51899. if (this.skeleton.bones[0].length === undefined) {
  51900. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51901. }
  51902. else {
  51903. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51904. }
  51905. if (!this._debugMesh) {
  51906. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  51907. this._debugMesh.renderingGroupId = this.renderingGroupId;
  51908. }
  51909. else {
  51910. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  51911. }
  51912. this._debugMesh.color = this.color;
  51913. };
  51914. SkeletonViewer.prototype.dispose = function () {
  51915. if (this._debugMesh) {
  51916. this.isEnabled = false;
  51917. this._debugMesh.dispose();
  51918. this._debugMesh = null;
  51919. }
  51920. };
  51921. return SkeletonViewer;
  51922. }());
  51923. Debug.SkeletonViewer = SkeletonViewer;
  51924. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51925. })(BABYLON || (BABYLON = {}));
  51926. //# sourceMappingURL=babylon.skeletonViewer.js.map
  51927. var BABYLON;
  51928. (function (BABYLON) {
  51929. var Debug;
  51930. (function (Debug) {
  51931. var AxesViewer = (function () {
  51932. function AxesViewer(scene, scaleLines) {
  51933. if (scaleLines === void 0) { scaleLines = 1; }
  51934. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51935. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51936. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51937. this.scaleLines = 1;
  51938. this.scaleLines = scaleLines;
  51939. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  51940. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  51941. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  51942. this._xmesh.renderingGroupId = 2;
  51943. this._ymesh.renderingGroupId = 2;
  51944. this._zmesh.renderingGroupId = 2;
  51945. this._xmesh.material.checkReadyOnlyOnce = true;
  51946. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  51947. this._ymesh.material.checkReadyOnlyOnce = true;
  51948. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  51949. this._zmesh.material.checkReadyOnlyOnce = true;
  51950. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  51951. this.scene = scene;
  51952. }
  51953. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  51954. var scaleLines = this.scaleLines;
  51955. var point1 = this._xline[0];
  51956. var point2 = this._xline[1];
  51957. point1.x = position.x;
  51958. point1.y = position.y;
  51959. point1.z = position.z;
  51960. point2.x = point1.x + xaxis.x * scaleLines;
  51961. point2.y = point1.y + xaxis.y * scaleLines;
  51962. point2.z = point1.z + xaxis.z * scaleLines;
  51963. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  51964. point1 = this._yline[0];
  51965. point2 = this._yline[1];
  51966. point1.x = position.x;
  51967. point1.y = position.y;
  51968. point1.z = position.z;
  51969. point2.x = point1.x + yaxis.x * scaleLines;
  51970. point2.y = point1.y + yaxis.y * scaleLines;
  51971. point2.z = point1.z + yaxis.z * scaleLines;
  51972. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  51973. point1 = this._zline[0];
  51974. point2 = this._zline[1];
  51975. point1.x = position.x;
  51976. point1.y = position.y;
  51977. point1.z = position.z;
  51978. point2.x = point1.x + zaxis.x * scaleLines;
  51979. point2.y = point1.y + zaxis.y * scaleLines;
  51980. point2.z = point1.z + zaxis.z * scaleLines;
  51981. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  51982. };
  51983. AxesViewer.prototype.dispose = function () {
  51984. if (this._xmesh) {
  51985. this._xmesh.dispose();
  51986. this._ymesh.dispose();
  51987. this._zmesh.dispose();
  51988. this._xmesh = null;
  51989. this._ymesh = null;
  51990. this._zmesh = null;
  51991. this._xline = null;
  51992. this._yline = null;
  51993. this._zline = null;
  51994. this.scene = null;
  51995. }
  51996. };
  51997. return AxesViewer;
  51998. }());
  51999. Debug.AxesViewer = AxesViewer;
  52000. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52001. })(BABYLON || (BABYLON = {}));
  52002. //# sourceMappingURL=babylon.axesViewer.js.map
  52003. var BABYLON;
  52004. (function (BABYLON) {
  52005. var Debug;
  52006. (function (Debug) {
  52007. var BoneAxesViewer = (function (_super) {
  52008. __extends(BoneAxesViewer, _super);
  52009. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52010. if (scaleLines === void 0) { scaleLines = 1; }
  52011. _super.call(this, scene, scaleLines);
  52012. this.pos = BABYLON.Vector3.Zero();
  52013. this.xaxis = BABYLON.Vector3.Zero();
  52014. this.yaxis = BABYLON.Vector3.Zero();
  52015. this.zaxis = BABYLON.Vector3.Zero();
  52016. this.mesh = mesh;
  52017. this.bone = bone;
  52018. }
  52019. BoneAxesViewer.prototype.update = function () {
  52020. var bone = this.bone;
  52021. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52022. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52023. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52024. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52025. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52026. };
  52027. BoneAxesViewer.prototype.dispose = function () {
  52028. if (this.pos) {
  52029. this.pos = null;
  52030. this.xaxis = null;
  52031. this.yaxis = null;
  52032. this.zaxis = null;
  52033. this.mesh = null;
  52034. this.bone = null;
  52035. _super.prototype.dispose.call(this);
  52036. }
  52037. };
  52038. return BoneAxesViewer;
  52039. }(Debug.AxesViewer));
  52040. Debug.BoneAxesViewer = BoneAxesViewer;
  52041. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52042. })(BABYLON || (BABYLON = {}));
  52043. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52044. var BABYLON;
  52045. (function (BABYLON) {
  52046. /**
  52047. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52048. * It can help converting any input color in a desired output one. This can then be used to create effects
  52049. * from sepia, black and white to sixties or futuristic rendering...
  52050. *
  52051. * The only supported format is currently 3dl.
  52052. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52053. */
  52054. var ColorGradingTexture = (function (_super) {
  52055. __extends(ColorGradingTexture, _super);
  52056. /**
  52057. * Instantiates a ColorGradingTexture from the following parameters.
  52058. *
  52059. * @param url The location of the color gradind data (currently only supporting 3dl)
  52060. * @param scene The scene the texture will be used in
  52061. */
  52062. function ColorGradingTexture(url, scene) {
  52063. _super.call(this, scene);
  52064. if (!url) {
  52065. return;
  52066. }
  52067. this._textureMatrix = BABYLON.Matrix.Identity();
  52068. this.name = url;
  52069. this.url = url;
  52070. this.hasAlpha = false;
  52071. this.isCube = false;
  52072. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52073. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52074. this.anisotropicFilteringLevel = 1;
  52075. this._texture = this._getFromCache(url, true);
  52076. if (!this._texture) {
  52077. if (!scene.useDelayedTextureLoading) {
  52078. this.loadTexture();
  52079. }
  52080. else {
  52081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52082. }
  52083. }
  52084. }
  52085. /**
  52086. * Returns the texture matrix used in most of the material.
  52087. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52088. */
  52089. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52090. return this._textureMatrix;
  52091. };
  52092. /**
  52093. * Occurs when the file being loaded is a .3dl LUT file.
  52094. */
  52095. ColorGradingTexture.prototype.load3dlTexture = function () {
  52096. var _this = this;
  52097. var mipLevels = 0;
  52098. var floatArrayView = null;
  52099. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52100. this._texture = texture;
  52101. var callback = function (text) {
  52102. var data;
  52103. var tempData;
  52104. var line;
  52105. var lines = text.split('\n');
  52106. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52107. var maxColor = 0;
  52108. for (var i = 0; i < lines.length; i++) {
  52109. line = lines[i];
  52110. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52111. continue;
  52112. if (line.indexOf('#') === 0)
  52113. continue;
  52114. var words = line.split(" ");
  52115. if (size === 0) {
  52116. // Number of space + one
  52117. size = words.length;
  52118. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52119. tempData = new Float32Array(size * size * size * 4);
  52120. continue;
  52121. }
  52122. if (size != 0) {
  52123. var r = Math.max(parseInt(words[0]), 0);
  52124. var g = Math.max(parseInt(words[1]), 0);
  52125. var b = Math.max(parseInt(words[2]), 0);
  52126. maxColor = Math.max(r, maxColor);
  52127. maxColor = Math.max(g, maxColor);
  52128. maxColor = Math.max(b, maxColor);
  52129. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52130. tempData[pixelStorageIndex + 0] = r;
  52131. tempData[pixelStorageIndex + 1] = g;
  52132. tempData[pixelStorageIndex + 2] = b;
  52133. tempData[pixelStorageIndex + 3] = 0;
  52134. pixelIndexSlice++;
  52135. if (pixelIndexSlice % size == 0) {
  52136. pixelIndexH++;
  52137. pixelIndexSlice = 0;
  52138. if (pixelIndexH % size == 0) {
  52139. pixelIndexW++;
  52140. pixelIndexH = 0;
  52141. }
  52142. }
  52143. }
  52144. }
  52145. for (var i = 0; i < tempData.length; i++) {
  52146. var value = tempData[i];
  52147. data[i] = (value / maxColor * 255);
  52148. }
  52149. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52150. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52151. };
  52152. BABYLON.Tools.LoadFile(this.url, callback);
  52153. return this._texture;
  52154. };
  52155. /**
  52156. * Starts the loading process of the texture.
  52157. */
  52158. ColorGradingTexture.prototype.loadTexture = function () {
  52159. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52160. this.load3dlTexture();
  52161. }
  52162. };
  52163. /**
  52164. * Clones the color gradind texture.
  52165. */
  52166. ColorGradingTexture.prototype.clone = function () {
  52167. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52168. // Base texture
  52169. newTexture.level = this.level;
  52170. return newTexture;
  52171. };
  52172. /**
  52173. * Called during delayed load for textures.
  52174. */
  52175. ColorGradingTexture.prototype.delayLoad = function () {
  52176. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52177. return;
  52178. }
  52179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52180. this._texture = this._getFromCache(this.url, true);
  52181. if (!this._texture) {
  52182. this.loadTexture();
  52183. }
  52184. };
  52185. /**
  52186. * Binds the color grading to the shader.
  52187. * @param colorGrading The texture to bind
  52188. * @param effect The effect to bind to
  52189. */
  52190. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52191. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52192. var x = colorGrading.level; // Texture Level
  52193. var y = colorGrading.getSize().height; // Texture Size example with 8
  52194. var z = y - 1.0; // SizeMinusOne 8 - 1
  52195. var w = 1 / y; // Space of 1 slice 1 / 8
  52196. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52197. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52198. 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
  52199. 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
  52200. 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
  52201. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52202. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52203. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52204. };
  52205. /**
  52206. * Prepare the list of uniforms associated with the ColorGrading effects.
  52207. * @param uniformsList The list of uniforms used in the effect
  52208. * @param samplersList The list of samplers used in the effect
  52209. */
  52210. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52211. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52212. samplersList.push("cameraColorGrading2DSampler");
  52213. };
  52214. /**
  52215. * Parses a color grading texture serialized by Babylon.
  52216. * @param parsedTexture The texture information being parsedTexture
  52217. * @param scene The scene to load the texture in
  52218. * @param rootUrl The root url of the data assets to load
  52219. * @return A color gradind texture
  52220. */
  52221. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52222. var texture = null;
  52223. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52224. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52225. texture.name = parsedTexture.name;
  52226. texture.level = parsedTexture.level;
  52227. }
  52228. return texture;
  52229. };
  52230. /**
  52231. * Serializes the LUT texture to json format.
  52232. */
  52233. ColorGradingTexture.prototype.serialize = function () {
  52234. if (!this.name) {
  52235. return null;
  52236. }
  52237. var serializationObject = {};
  52238. serializationObject.name = this.name;
  52239. serializationObject.level = this.level;
  52240. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52241. return serializationObject;
  52242. };
  52243. /**
  52244. * Empty line regex stored for GC.
  52245. */
  52246. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52247. return ColorGradingTexture;
  52248. }(BABYLON.BaseTexture));
  52249. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52250. })(BABYLON || (BABYLON = {}));
  52251. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52252. var BABYLON;
  52253. (function (BABYLON) {
  52254. /**
  52255. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52256. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52257. * 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;
  52258. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52259. */
  52260. var ColorCurves = (function () {
  52261. function ColorCurves() {
  52262. this._dirty = true;
  52263. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52264. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52265. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52266. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52267. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52268. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52269. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52270. this._globalHue = 30;
  52271. this._globalDensity = 0;
  52272. this._globalSaturation = 0;
  52273. this._globalExposure = 0;
  52274. this._highlightsHue = 30;
  52275. this._highlightsDensity = 0;
  52276. this._highlightsSaturation = 0;
  52277. this._highlightsExposure = 0;
  52278. this._midtonesHue = 30;
  52279. this._midtonesDensity = 0;
  52280. this._midtonesSaturation = 0;
  52281. this._midtonesExposure = 0;
  52282. this._shadowsHue = 30;
  52283. this._shadowsDensity = 0;
  52284. this._shadowsSaturation = 0;
  52285. this._shadowsExposure = 0;
  52286. }
  52287. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52288. /**
  52289. * Gets the global Hue value.
  52290. * 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).
  52291. */
  52292. get: function () {
  52293. return this._globalHue;
  52294. },
  52295. /**
  52296. * Sets the global Hue value.
  52297. * 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).
  52298. */
  52299. set: function (value) {
  52300. this._globalHue = value;
  52301. this._dirty = true;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52307. /**
  52308. * Gets the global 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. get: function () {
  52313. return this._globalDensity;
  52314. },
  52315. /**
  52316. * Sets the global Density value.
  52317. * 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.
  52318. * Values less than zero provide a filter of opposite hue.
  52319. */
  52320. set: function (value) {
  52321. this._globalDensity = value;
  52322. this._dirty = true;
  52323. },
  52324. enumerable: true,
  52325. configurable: true
  52326. });
  52327. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52328. /**
  52329. * Gets the global Saturation value.
  52330. * 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.
  52331. */
  52332. get: function () {
  52333. return this._globalSaturation;
  52334. },
  52335. /**
  52336. * Sets the global Saturation value.
  52337. * 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.
  52338. */
  52339. set: function (value) {
  52340. this._globalSaturation = value;
  52341. this._dirty = true;
  52342. },
  52343. enumerable: true,
  52344. configurable: true
  52345. });
  52346. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52347. /**
  52348. * Gets the highlights Hue value.
  52349. * 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).
  52350. */
  52351. get: function () {
  52352. return this._highlightsHue;
  52353. },
  52354. /**
  52355. * Sets the highlights Hue value.
  52356. * 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).
  52357. */
  52358. set: function (value) {
  52359. this._highlightsHue = value;
  52360. this._dirty = true;
  52361. },
  52362. enumerable: true,
  52363. configurable: true
  52364. });
  52365. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52366. /**
  52367. * Gets the highlights Density value.
  52368. * 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.
  52369. * Values less than zero provide a filter of opposite hue.
  52370. */
  52371. get: function () {
  52372. return this._highlightsDensity;
  52373. },
  52374. /**
  52375. * Sets the highlights Density value.
  52376. * 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.
  52377. * Values less than zero provide a filter of opposite hue.
  52378. */
  52379. set: function (value) {
  52380. this._highlightsDensity = value;
  52381. this._dirty = true;
  52382. },
  52383. enumerable: true,
  52384. configurable: true
  52385. });
  52386. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52387. /**
  52388. * Gets the highlights Saturation value.
  52389. * 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.
  52390. */
  52391. get: function () {
  52392. return this._highlightsSaturation;
  52393. },
  52394. /**
  52395. * Sets the highlights Saturation value.
  52396. * 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.
  52397. */
  52398. set: function (value) {
  52399. this._highlightsSaturation = value;
  52400. this._dirty = true;
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52406. /**
  52407. * Gets the highlights Exposure value.
  52408. * 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.
  52409. */
  52410. get: function () {
  52411. return this._highlightsExposure;
  52412. },
  52413. /**
  52414. * Sets the highlights Exposure value.
  52415. * 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.
  52416. */
  52417. set: function (value) {
  52418. this._highlightsExposure = value;
  52419. this._dirty = true;
  52420. },
  52421. enumerable: true,
  52422. configurable: true
  52423. });
  52424. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52425. /**
  52426. * Gets the midtones Hue value.
  52427. * 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).
  52428. */
  52429. get: function () {
  52430. return this._midtonesHue;
  52431. },
  52432. /**
  52433. * Sets the midtones Hue value.
  52434. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52435. */
  52436. set: function (value) {
  52437. this._midtonesHue = value;
  52438. this._dirty = true;
  52439. },
  52440. enumerable: true,
  52441. configurable: true
  52442. });
  52443. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52444. /**
  52445. * Gets the midtones Density value.
  52446. * 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.
  52447. * Values less than zero provide a filter of opposite hue.
  52448. */
  52449. get: function () {
  52450. return this._midtonesDensity;
  52451. },
  52452. /**
  52453. * Sets the midtones Density value.
  52454. * 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.
  52455. * Values less than zero provide a filter of opposite hue.
  52456. */
  52457. set: function (value) {
  52458. this._midtonesDensity = value;
  52459. this._dirty = true;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52465. /**
  52466. * Gets the midtones Saturation value.
  52467. * 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.
  52468. */
  52469. get: function () {
  52470. return this._midtonesSaturation;
  52471. },
  52472. /**
  52473. * Sets the midtones Saturation value.
  52474. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52475. */
  52476. set: function (value) {
  52477. this._midtonesSaturation = value;
  52478. this._dirty = true;
  52479. },
  52480. enumerable: true,
  52481. configurable: true
  52482. });
  52483. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52484. /**
  52485. * Gets the midtones Exposure value.
  52486. * 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.
  52487. */
  52488. get: function () {
  52489. return this._midtonesExposure;
  52490. },
  52491. /**
  52492. * Sets the midtones Exposure value.
  52493. * 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.
  52494. */
  52495. set: function (value) {
  52496. this._midtonesExposure = value;
  52497. this._dirty = true;
  52498. },
  52499. enumerable: true,
  52500. configurable: true
  52501. });
  52502. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52503. /**
  52504. * Gets the shadows Hue value.
  52505. * 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).
  52506. */
  52507. get: function () {
  52508. return this._shadowsHue;
  52509. },
  52510. /**
  52511. * Sets the shadows Hue value.
  52512. * 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).
  52513. */
  52514. set: function (value) {
  52515. this._shadowsHue = value;
  52516. this._dirty = true;
  52517. },
  52518. enumerable: true,
  52519. configurable: true
  52520. });
  52521. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52522. /**
  52523. * Gets the shadows Density value.
  52524. * 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.
  52525. * Values less than zero provide a filter of opposite hue.
  52526. */
  52527. get: function () {
  52528. return this._shadowsDensity;
  52529. },
  52530. /**
  52531. * Sets the shadows Density value.
  52532. * 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.
  52533. * Values less than zero provide a filter of opposite hue.
  52534. */
  52535. set: function (value) {
  52536. this._shadowsDensity = value;
  52537. this._dirty = true;
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52543. /**
  52544. * Gets the shadows Saturation value.
  52545. * 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.
  52546. */
  52547. get: function () {
  52548. return this._shadowsSaturation;
  52549. },
  52550. /**
  52551. * Sets the shadows Saturation value.
  52552. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52553. */
  52554. set: function (value) {
  52555. this._shadowsSaturation = value;
  52556. this._dirty = true;
  52557. },
  52558. enumerable: true,
  52559. configurable: true
  52560. });
  52561. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52562. /**
  52563. * Gets the shadows Exposure value.
  52564. * 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.
  52565. */
  52566. get: function () {
  52567. return this._shadowsExposure;
  52568. },
  52569. /**
  52570. * Sets the shadows Exposure value.
  52571. * 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.
  52572. */
  52573. set: function (value) {
  52574. this._shadowsExposure = value;
  52575. this._dirty = true;
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. /**
  52581. * Binds the color curves to the shader.
  52582. * @param colorCurves The color curve to bind
  52583. * @param effect The effect to bind to
  52584. */
  52585. ColorCurves.Bind = function (colorCurves, effect) {
  52586. if (colorCurves._dirty) {
  52587. colorCurves._dirty = false;
  52588. // Fill in global info.
  52589. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52590. // Compute highlights info.
  52591. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52592. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52593. // Compute midtones info.
  52594. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52595. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52596. // Compute shadows info.
  52597. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52598. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52599. // Compute deltas (neutral is midtones).
  52600. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52601. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52602. }
  52603. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52604. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52605. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52606. };
  52607. /**
  52608. * Prepare the list of uniforms associated with the ColorCurves effects.
  52609. * @param uniformsList The list of uniforms used in the effect
  52610. */
  52611. ColorCurves.PrepareUniforms = function (uniformsList) {
  52612. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52613. };
  52614. /**
  52615. * Returns color grading data based on a hue, density, saturation and exposure value.
  52616. * @param filterHue The hue of the color filter.
  52617. * @param filterDensity The density of the color filter.
  52618. * @param saturation The saturation.
  52619. * @param exposure The exposure.
  52620. * @param result The result data container.
  52621. */
  52622. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52623. if (hue == null) {
  52624. return;
  52625. }
  52626. hue = ColorCurves.clamp(hue, 0, 360);
  52627. density = ColorCurves.clamp(density, -100, 100);
  52628. saturation = ColorCurves.clamp(saturation, -100, 100);
  52629. exposure = ColorCurves.clamp(exposure, -100, 100);
  52630. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52631. // so that the maximum filter density is only 50% control. This provides fine control
  52632. // for small values and reasonable range.
  52633. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52634. density *= 0.5;
  52635. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52636. if (density < 0) {
  52637. density *= -1;
  52638. hue = (hue + 180) % 360;
  52639. }
  52640. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52641. result.scaleToRef(2, result);
  52642. result.a = 1 + 0.01 * saturation;
  52643. };
  52644. /**
  52645. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52646. * @param value The input slider value in range [-100,100].
  52647. * @returns Adjusted value.
  52648. */
  52649. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52650. value /= 100;
  52651. var x = Math.abs(value);
  52652. x = Math.pow(x, 2);
  52653. if (value < 0) {
  52654. x *= -1;
  52655. }
  52656. x *= 100;
  52657. return x;
  52658. };
  52659. /**
  52660. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52661. * @param hue The hue (H) input.
  52662. * @param saturation The saturation (S) input.
  52663. * @param brightness The brightness (B) input.
  52664. * @result An RGBA color represented as Vector4.
  52665. */
  52666. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52667. var h = ColorCurves.clamp(hue, 0, 360);
  52668. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52669. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52670. if (s === 0) {
  52671. result.r = v;
  52672. result.g = v;
  52673. result.b = v;
  52674. }
  52675. else {
  52676. // sector 0 to 5
  52677. h /= 60;
  52678. var i = Math.floor(h);
  52679. // fractional part of h
  52680. var f = h - i;
  52681. var p = v * (1 - s);
  52682. var q = v * (1 - s * f);
  52683. var t = v * (1 - s * (1 - f));
  52684. switch (i) {
  52685. case 0:
  52686. result.r = v;
  52687. result.g = t;
  52688. result.b = p;
  52689. break;
  52690. case 1:
  52691. result.r = q;
  52692. result.g = v;
  52693. result.b = p;
  52694. break;
  52695. case 2:
  52696. result.r = p;
  52697. result.g = v;
  52698. result.b = t;
  52699. break;
  52700. case 3:
  52701. result.r = p;
  52702. result.g = q;
  52703. result.b = v;
  52704. break;
  52705. case 4:
  52706. result.r = t;
  52707. result.g = p;
  52708. result.b = v;
  52709. break;
  52710. default:
  52711. result.r = v;
  52712. result.g = p;
  52713. result.b = q;
  52714. break;
  52715. }
  52716. }
  52717. result.a = 1;
  52718. };
  52719. /**
  52720. * Returns a value clamped between min and max
  52721. * @param value The value to clamp
  52722. * @param min The minimum of value
  52723. * @param max The maximum of value
  52724. * @returns The clamped value.
  52725. */
  52726. ColorCurves.clamp = function (value, min, max) {
  52727. return Math.min(Math.max(value, min), max);
  52728. };
  52729. /**
  52730. * Clones the current color curve instance.
  52731. * @return The cloned curves
  52732. */
  52733. ColorCurves.prototype.clone = function () {
  52734. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52735. };
  52736. /**
  52737. * Serializes the current color curve instance to a json representation.
  52738. * @return a JSON representation
  52739. */
  52740. ColorCurves.prototype.serialize = function () {
  52741. return BABYLON.SerializationHelper.Serialize(this);
  52742. };
  52743. /**
  52744. * Parses the color curve from a json representation.
  52745. * @param source the JSON source to parse
  52746. * @return The parsed curves
  52747. */
  52748. ColorCurves.Parse = function (source) {
  52749. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52750. };
  52751. __decorate([
  52752. BABYLON.serialize()
  52753. ], ColorCurves.prototype, "_globalHue", void 0);
  52754. __decorate([
  52755. BABYLON.serialize()
  52756. ], ColorCurves.prototype, "_globalDensity", void 0);
  52757. __decorate([
  52758. BABYLON.serialize()
  52759. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52760. __decorate([
  52761. BABYLON.serialize()
  52762. ], ColorCurves.prototype, "_globalExposure", void 0);
  52763. __decorate([
  52764. BABYLON.serialize()
  52765. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52766. __decorate([
  52767. BABYLON.serialize()
  52768. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52769. __decorate([
  52770. BABYLON.serialize()
  52771. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52772. __decorate([
  52773. BABYLON.serialize()
  52774. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52775. __decorate([
  52776. BABYLON.serialize()
  52777. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52778. __decorate([
  52779. BABYLON.serialize()
  52780. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52781. __decorate([
  52782. BABYLON.serialize()
  52783. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52784. __decorate([
  52785. BABYLON.serialize()
  52786. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52787. return ColorCurves;
  52788. }());
  52789. BABYLON.ColorCurves = ColorCurves;
  52790. })(BABYLON || (BABYLON = {}));
  52791. //# sourceMappingURL=babylon.colorCurves.js.map
  52792. var BABYLON;
  52793. (function (BABYLON) {
  52794. var PBRMaterialDefines = (function (_super) {
  52795. __extends(PBRMaterialDefines, _super);
  52796. function PBRMaterialDefines() {
  52797. _super.call(this);
  52798. this.ALBEDO = false;
  52799. this.AMBIENT = false;
  52800. this.OPACITY = false;
  52801. this.OPACITYRGB = false;
  52802. this.REFLECTION = false;
  52803. this.EMISSIVE = false;
  52804. this.REFLECTIVITY = false;
  52805. this.BUMP = false;
  52806. this.PARALLAX = false;
  52807. this.PARALLAXOCCLUSION = false;
  52808. this.SPECULAROVERALPHA = false;
  52809. this.CLIPPLANE = false;
  52810. this.ALPHATEST = false;
  52811. this.ALPHAFROMALBEDO = false;
  52812. this.POINTSIZE = false;
  52813. this.FOG = false;
  52814. this.SPECULARTERM = false;
  52815. this.OPACITYFRESNEL = false;
  52816. this.EMISSIVEFRESNEL = false;
  52817. this.FRESNEL = false;
  52818. this.NORMAL = false;
  52819. this.UV1 = false;
  52820. this.UV2 = false;
  52821. this.VERTEXCOLOR = false;
  52822. this.VERTEXALPHA = false;
  52823. this.NUM_BONE_INFLUENCERS = 0;
  52824. this.BonesPerMesh = 0;
  52825. this.INSTANCES = false;
  52826. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52827. this.MICROSURFACEAUTOMATIC = false;
  52828. this.EMISSIVEASILLUMINATION = false;
  52829. this.LINKEMISSIVEWITHALBEDO = false;
  52830. this.LIGHTMAP = false;
  52831. this.USELIGHTMAPASSHADOWMAP = false;
  52832. this.REFLECTIONMAP_3D = false;
  52833. this.REFLECTIONMAP_SPHERICAL = false;
  52834. this.REFLECTIONMAP_PLANAR = false;
  52835. this.REFLECTIONMAP_CUBIC = false;
  52836. this.REFLECTIONMAP_PROJECTION = false;
  52837. this.REFLECTIONMAP_SKYBOX = false;
  52838. this.REFLECTIONMAP_EXPLICIT = false;
  52839. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52840. this.INVERTCUBICMAP = false;
  52841. this.LOGARITHMICDEPTH = false;
  52842. this.CAMERATONEMAP = false;
  52843. this.CAMERACONTRAST = false;
  52844. this.CAMERACOLORGRADING = false;
  52845. this.CAMERACOLORCURVES = false;
  52846. this.OVERLOADEDVALUES = false;
  52847. this.OVERLOADEDSHADOWVALUES = false;
  52848. this.USESPHERICALFROMREFLECTIONMAP = false;
  52849. this.REFRACTION = false;
  52850. this.REFRACTIONMAP_3D = false;
  52851. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52852. this.REFRACTIONMAPINLINEARSPACE = false;
  52853. this.LODBASEDMICROSFURACE = false;
  52854. this.USEPHYSICALLIGHTFALLOFF = false;
  52855. this.RADIANCEOVERALPHA = false;
  52856. this.USEPMREMREFLECTION = false;
  52857. this.USEPMREMREFRACTION = false;
  52858. this.OPENGLNORMALMAP = false;
  52859. this.INVERTNORMALMAPX = false;
  52860. this.INVERTNORMALMAPY = false;
  52861. this.SHADOWFULLFLOAT = false;
  52862. this.METALLICWORKFLOW = false;
  52863. this.METALLICROUGHNESSGSTOREINALPHA = false;
  52864. this.METALLICROUGHNESSGSTOREINGREEN = false;
  52865. this.rebuild();
  52866. }
  52867. return PBRMaterialDefines;
  52868. }(BABYLON.MaterialDefines));
  52869. /**
  52870. * The Physically based material of BJS.
  52871. *
  52872. * This offers the main features of a standard PBR material.
  52873. * For more information, please refer to the documentation :
  52874. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52875. */
  52876. var PBRMaterial = (function (_super) {
  52877. __extends(PBRMaterial, _super);
  52878. /**
  52879. * Instantiates a new PBRMaterial instance.
  52880. *
  52881. * @param name The material name
  52882. * @param scene The scene the material will be use in.
  52883. */
  52884. function PBRMaterial(name, scene) {
  52885. var _this = this;
  52886. _super.call(this, name, scene);
  52887. /**
  52888. * Intensity of the direct lights e.g. the four lights available in your scene.
  52889. * This impacts both the direct diffuse and specular highlights.
  52890. */
  52891. this.directIntensity = 1.0;
  52892. /**
  52893. * Intensity of the emissive part of the material.
  52894. * This helps controlling the emissive effect without modifying the emissive color.
  52895. */
  52896. this.emissiveIntensity = 1.0;
  52897. /**
  52898. * Intensity of the environment e.g. how much the environment will light the object
  52899. * either through harmonics for rough material or through the refelction for shiny ones.
  52900. */
  52901. this.environmentIntensity = 1.0;
  52902. /**
  52903. * This is a special control allowing the reduction of the specular highlights coming from the
  52904. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52905. */
  52906. this.specularIntensity = 1.0;
  52907. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52908. /**
  52909. * Debug Control allowing disabling the bump map on this material.
  52910. */
  52911. this.disableBumpMap = false;
  52912. /**
  52913. * Debug Control helping enforcing or dropping the darkness of shadows.
  52914. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52915. */
  52916. this.overloadedShadowIntensity = 1.0;
  52917. /**
  52918. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52919. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52920. */
  52921. this.overloadedShadeIntensity = 1.0;
  52922. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52923. /**
  52924. * The camera exposure used on this material.
  52925. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52926. * This corresponds to a photographic exposure.
  52927. */
  52928. this.cameraExposure = 1.0;
  52929. /**
  52930. * The camera contrast used on this material.
  52931. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52932. */
  52933. this.cameraContrast = 1.0;
  52934. /**
  52935. * Color Grading 2D Lookup Texture.
  52936. * This allows special effects like sepia, black and white to sixties rendering style.
  52937. */
  52938. this.cameraColorGradingTexture = null;
  52939. /**
  52940. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52941. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52942. * 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;
  52943. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52944. */
  52945. this.cameraColorCurves = null;
  52946. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52947. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52948. /**
  52949. * Debug Control allowing to overload the ambient color.
  52950. * This as to be use with the overloadedAmbientIntensity parameter.
  52951. */
  52952. this.overloadedAmbient = BABYLON.Color3.White();
  52953. /**
  52954. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  52955. */
  52956. this.overloadedAmbientIntensity = 0.0;
  52957. /**
  52958. * Debug Control allowing to overload the albedo color.
  52959. * This as to be use with the overloadedAlbedoIntensity parameter.
  52960. */
  52961. this.overloadedAlbedo = BABYLON.Color3.White();
  52962. /**
  52963. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  52964. */
  52965. this.overloadedAlbedoIntensity = 0.0;
  52966. /**
  52967. * Debug Control allowing to overload the reflectivity color.
  52968. * This as to be use with the overloadedReflectivityIntensity parameter.
  52969. */
  52970. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  52971. /**
  52972. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  52973. */
  52974. this.overloadedReflectivityIntensity = 0.0;
  52975. /**
  52976. * Debug Control allowing to overload the emissive color.
  52977. * This as to be use with the overloadedEmissiveIntensity parameter.
  52978. */
  52979. this.overloadedEmissive = BABYLON.Color3.White();
  52980. /**
  52981. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  52982. */
  52983. this.overloadedEmissiveIntensity = 0.0;
  52984. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  52985. /**
  52986. * Debug Control allowing to overload the reflection color.
  52987. * This as to be use with the overloadedReflectionIntensity parameter.
  52988. */
  52989. this.overloadedReflection = BABYLON.Color3.White();
  52990. /**
  52991. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  52992. */
  52993. this.overloadedReflectionIntensity = 0.0;
  52994. /**
  52995. * Debug Control allowing to overload the microsurface.
  52996. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  52997. */
  52998. this.overloadedMicroSurface = 0.0;
  52999. /**
  53000. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53001. */
  53002. this.overloadedMicroSurfaceIntensity = 0.0;
  53003. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  53004. /**
  53005. * AKA Occlusion Texture Intensity in other nomenclature.
  53006. */
  53007. this.ambientTextureStrength = 1.0;
  53008. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53009. /**
  53010. * AKA Diffuse Color in other nomenclature.
  53011. */
  53012. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53013. /**
  53014. * AKA Specular Color in other nomenclature.
  53015. */
  53016. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53017. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53018. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53019. /**
  53020. * AKA Glossiness in other nomenclature.
  53021. */
  53022. this.microSurface = 0.9;
  53023. /**
  53024. * source material index of refraction (IOR)' / 'destination material IOR.
  53025. */
  53026. this.indexOfRefraction = 0.66;
  53027. /**
  53028. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53029. */
  53030. this.invertRefractionY = false;
  53031. /**
  53032. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53033. * Materials half opaque for instance using refraction could benefit from this control.
  53034. */
  53035. this.linkRefractionWithTransparency = false;
  53036. /**
  53037. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53038. */
  53039. this.linkEmissiveWithAlbedo = false;
  53040. this.useLightmapAsShadowmap = false;
  53041. /**
  53042. * In this mode, the emissive informtaion will always be added to the lighting once.
  53043. * A light for instance can be thought as emissive.
  53044. */
  53045. this.useEmissiveAsIllumination = false;
  53046. /**
  53047. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53048. */
  53049. this.useAlphaFromAlbedoTexture = false;
  53050. /**
  53051. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53052. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53053. */
  53054. this.useSpecularOverAlpha = true;
  53055. /**
  53056. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53057. */
  53058. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53059. /**
  53060. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53061. */
  53062. this.useRoughnessFromMetallicTextureAlpha = true;
  53063. /**
  53064. * Specifies if the metallic texture contains the roughness information in its green channel.
  53065. */
  53066. this.useRoughnessFromMetallicTextureGreen = false;
  53067. /**
  53068. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53069. * The material will try to infer what glossiness each pixel should be.
  53070. */
  53071. this.useAutoMicroSurfaceFromReflectivityMap = false;
  53072. /**
  53073. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53074. * the creation of the material.
  53075. */
  53076. this.useScalarInLinearSpace = false;
  53077. /**
  53078. * BJS is using an harcoded light falloff based on a manually sets up range.
  53079. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53080. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53081. */
  53082. this.usePhysicalLightFalloff = true;
  53083. /**
  53084. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53085. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53086. */
  53087. this.useRadianceOverAlpha = true;
  53088. /**
  53089. * Allows using the bump map in parallax mode.
  53090. */
  53091. this.useParallax = false;
  53092. /**
  53093. * Allows using the bump map in parallax occlusion mode.
  53094. */
  53095. this.useParallaxOcclusion = false;
  53096. /**
  53097. * Controls the scale bias of the parallax mode.
  53098. */
  53099. this.parallaxScaleBias = 0.05;
  53100. /**
  53101. * If sets to true, disables all the lights affecting the material.
  53102. */
  53103. this.disableLighting = false;
  53104. /**
  53105. * Number of Simultaneous lights allowed on the material.
  53106. */
  53107. this.maxSimultaneousLights = 4;
  53108. /**
  53109. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53110. */
  53111. this.invertNormalMapX = false;
  53112. /**
  53113. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53114. */
  53115. this.invertNormalMapY = false;
  53116. this._renderTargets = new BABYLON.SmartArray(16);
  53117. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53118. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53119. this._tempColor = new BABYLON.Color3();
  53120. this._defines = new PBRMaterialDefines();
  53121. this._cachedDefines = new PBRMaterialDefines();
  53122. this._myScene = null;
  53123. this._myShadowGenerator = null;
  53124. this._cachedDefines.BonesPerMesh = -1;
  53125. this.getRenderTargetTextures = function () {
  53126. _this._renderTargets.reset();
  53127. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53128. _this._renderTargets.push(_this.reflectionTexture);
  53129. }
  53130. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53131. _this._renderTargets.push(_this.refractionTexture);
  53132. }
  53133. return _this._renderTargets;
  53134. };
  53135. }
  53136. PBRMaterial.prototype.getClassName = function () {
  53137. return "PBRMaterial";
  53138. };
  53139. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53140. get: function () {
  53141. return this._useLogarithmicDepth;
  53142. },
  53143. set: function (value) {
  53144. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53145. },
  53146. enumerable: true,
  53147. configurable: true
  53148. });
  53149. PBRMaterial.prototype.needAlphaBlending = function () {
  53150. if (this.linkRefractionWithTransparency) {
  53151. return false;
  53152. }
  53153. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53154. };
  53155. PBRMaterial.prototype.needAlphaTesting = function () {
  53156. if (this.linkRefractionWithTransparency) {
  53157. return false;
  53158. }
  53159. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53160. };
  53161. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53162. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53163. };
  53164. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53165. return this.albedoTexture;
  53166. };
  53167. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53168. if (!mesh) {
  53169. return true;
  53170. }
  53171. if (this._defines.INSTANCES !== useInstances) {
  53172. return false;
  53173. }
  53174. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53175. return true;
  53176. }
  53177. return false;
  53178. };
  53179. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53180. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53181. };
  53182. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53183. if (!useScalarInLinear) {
  53184. color.toLinearSpaceToRef(ref);
  53185. }
  53186. else {
  53187. ref.r = color.r;
  53188. ref.g = color.g;
  53189. ref.b = color.b;
  53190. }
  53191. };
  53192. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53193. var lightIndex = 0;
  53194. var depthValuesAlreadySet = false;
  53195. for (var index = 0; index < scene.lights.length; index++) {
  53196. var light = scene.lights[index];
  53197. if (!light.isEnabled()) {
  53198. continue;
  53199. }
  53200. if (!light.canAffectMesh(mesh)) {
  53201. continue;
  53202. }
  53203. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53204. // GAMMA CORRECTION.
  53205. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53206. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53207. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53208. if (defines["SPECULARTERM"]) {
  53209. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53210. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53211. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53212. }
  53213. // Shadows
  53214. if (scene.shadowsEnabled) {
  53215. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53216. }
  53217. lightIndex++;
  53218. if (lightIndex === maxSimultaneousLights)
  53219. break;
  53220. }
  53221. };
  53222. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53223. if (this.checkReadyOnlyOnce) {
  53224. if (this._wasPreviouslyReady) {
  53225. return true;
  53226. }
  53227. }
  53228. var scene = this.getScene();
  53229. var engine = scene.getEngine();
  53230. var needNormals = false;
  53231. var needUVs = false;
  53232. this._defines.reset();
  53233. if (scene.lightsEnabled && !this.disableLighting) {
  53234. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53235. }
  53236. if (!this.checkReadyOnEveryCall) {
  53237. if (this._renderId === scene.getRenderId()) {
  53238. if (this._checkCache(scene, mesh, useInstances)) {
  53239. return true;
  53240. }
  53241. }
  53242. }
  53243. if (scene.texturesEnabled) {
  53244. if (scene.getEngine().getCaps().textureLOD) {
  53245. this._defines.LODBASEDMICROSFURACE = true;
  53246. }
  53247. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53248. if (!this.albedoTexture.isReady()) {
  53249. return false;
  53250. }
  53251. else {
  53252. needUVs = true;
  53253. this._defines.ALBEDO = true;
  53254. }
  53255. }
  53256. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53257. if (!this.ambientTexture.isReady()) {
  53258. return false;
  53259. }
  53260. else {
  53261. needUVs = true;
  53262. this._defines.AMBIENT = true;
  53263. }
  53264. }
  53265. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53266. if (!this.opacityTexture.isReady()) {
  53267. return false;
  53268. }
  53269. else {
  53270. needUVs = true;
  53271. this._defines.OPACITY = true;
  53272. if (this.opacityTexture.getAlphaFromRGB) {
  53273. this._defines.OPACITYRGB = true;
  53274. }
  53275. }
  53276. }
  53277. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53278. if (!this.reflectionTexture.isReady()) {
  53279. return false;
  53280. }
  53281. else {
  53282. needNormals = true;
  53283. this._defines.REFLECTION = true;
  53284. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53285. this._defines.INVERTCUBICMAP = true;
  53286. }
  53287. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53288. switch (this.reflectionTexture.coordinatesMode) {
  53289. case BABYLON.Texture.CUBIC_MODE:
  53290. case BABYLON.Texture.INVCUBIC_MODE:
  53291. this._defines.REFLECTIONMAP_CUBIC = true;
  53292. break;
  53293. case BABYLON.Texture.EXPLICIT_MODE:
  53294. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53295. break;
  53296. case BABYLON.Texture.PLANAR_MODE:
  53297. this._defines.REFLECTIONMAP_PLANAR = true;
  53298. break;
  53299. case BABYLON.Texture.PROJECTION_MODE:
  53300. this._defines.REFLECTIONMAP_PROJECTION = true;
  53301. break;
  53302. case BABYLON.Texture.SKYBOX_MODE:
  53303. this._defines.REFLECTIONMAP_SKYBOX = true;
  53304. break;
  53305. case BABYLON.Texture.SPHERICAL_MODE:
  53306. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53307. break;
  53308. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53309. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53310. break;
  53311. }
  53312. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53313. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53314. needNormals = true;
  53315. if (this.reflectionTexture.isPMREM) {
  53316. this._defines.USEPMREMREFLECTION = true;
  53317. }
  53318. }
  53319. }
  53320. }
  53321. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53322. if (!this.lightmapTexture.isReady()) {
  53323. return false;
  53324. }
  53325. else {
  53326. needUVs = true;
  53327. this._defines.LIGHTMAP = true;
  53328. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53329. }
  53330. }
  53331. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53332. if (!this.emissiveTexture.isReady()) {
  53333. return false;
  53334. }
  53335. else {
  53336. needUVs = true;
  53337. this._defines.EMISSIVE = true;
  53338. }
  53339. }
  53340. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53341. if (this.metallicTexture) {
  53342. if (!this.metallicTexture.isReady()) {
  53343. return false;
  53344. }
  53345. else {
  53346. needUVs = true;
  53347. this._defines.METALLICWORKFLOW = true;
  53348. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53349. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53350. }
  53351. }
  53352. else if (this.reflectivityTexture) {
  53353. if (!this.reflectivityTexture.isReady()) {
  53354. return false;
  53355. }
  53356. else {
  53357. needUVs = true;
  53358. this._defines.REFLECTIVITY = true;
  53359. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53360. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53361. }
  53362. }
  53363. }
  53364. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53365. if (!this.bumpTexture.isReady()) {
  53366. return false;
  53367. }
  53368. else {
  53369. needUVs = true;
  53370. this._defines.BUMP = true;
  53371. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53372. this._defines.PARALLAX = true;
  53373. if (this.useParallaxOcclusion) {
  53374. this._defines.PARALLAXOCCLUSION = true;
  53375. }
  53376. }
  53377. if (this.invertNormalMapX) {
  53378. this._defines.INVERTNORMALMAPX = true;
  53379. }
  53380. if (this.invertNormalMapY) {
  53381. this._defines.INVERTNORMALMAPY = true;
  53382. }
  53383. }
  53384. }
  53385. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53386. if (!this.refractionTexture.isReady()) {
  53387. return false;
  53388. }
  53389. else {
  53390. needUVs = true;
  53391. this._defines.REFRACTION = true;
  53392. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53393. if (this.linkRefractionWithTransparency) {
  53394. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53395. }
  53396. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53397. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53398. if (this.refractionTexture.isPMREM) {
  53399. this._defines.USEPMREMREFRACTION = true;
  53400. }
  53401. }
  53402. }
  53403. }
  53404. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53405. if (!this.cameraColorGradingTexture.isReady()) {
  53406. return false;
  53407. }
  53408. else {
  53409. this._defines.CAMERACOLORGRADING = true;
  53410. }
  53411. }
  53412. }
  53413. // Effect
  53414. if (scene.clipPlane) {
  53415. this._defines.CLIPPLANE = true;
  53416. }
  53417. if (engine.getAlphaTesting()) {
  53418. this._defines.ALPHATEST = true;
  53419. }
  53420. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53421. this._defines.ALPHAFROMALBEDO = true;
  53422. }
  53423. if (this.useEmissiveAsIllumination) {
  53424. this._defines.EMISSIVEASILLUMINATION = true;
  53425. }
  53426. if (this.linkEmissiveWithAlbedo) {
  53427. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53428. }
  53429. if (this.useLogarithmicDepth) {
  53430. this._defines.LOGARITHMICDEPTH = true;
  53431. }
  53432. if (this.cameraContrast != 1) {
  53433. this._defines.CAMERACONTRAST = true;
  53434. }
  53435. if (this.cameraExposure != 1) {
  53436. this._defines.CAMERATONEMAP = true;
  53437. }
  53438. if (this.cameraColorCurves) {
  53439. this._defines.CAMERACOLORCURVES = true;
  53440. }
  53441. if (this.overloadedShadeIntensity != 1 ||
  53442. this.overloadedShadowIntensity != 1) {
  53443. this._defines.OVERLOADEDSHADOWVALUES = true;
  53444. }
  53445. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53446. this.overloadedEmissiveIntensity > 0 ||
  53447. this.overloadedReflectivityIntensity > 0 ||
  53448. this.overloadedAlbedoIntensity > 0 ||
  53449. this.overloadedAmbientIntensity > 0 ||
  53450. this.overloadedReflectionIntensity > 0) {
  53451. this._defines.OVERLOADEDVALUES = true;
  53452. }
  53453. // Point size
  53454. if (this.pointsCloud || scene.forcePointsCloud) {
  53455. this._defines.POINTSIZE = true;
  53456. }
  53457. // Fog
  53458. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53459. this._defines.FOG = true;
  53460. }
  53461. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53462. // Fresnel
  53463. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53464. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53465. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53466. this._defines.OPACITYFRESNEL = true;
  53467. }
  53468. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53469. this._defines.EMISSIVEFRESNEL = true;
  53470. }
  53471. needNormals = true;
  53472. this._defines.FRESNEL = true;
  53473. }
  53474. }
  53475. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53476. this._defines.SPECULAROVERALPHA = true;
  53477. }
  53478. if (this.usePhysicalLightFalloff) {
  53479. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53480. }
  53481. if (this.useRadianceOverAlpha) {
  53482. this._defines.RADIANCEOVERALPHA = true;
  53483. }
  53484. // Attribs
  53485. if (mesh) {
  53486. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53487. this._defines.NORMAL = true;
  53488. }
  53489. if (needUVs) {
  53490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53491. this._defines.UV1 = true;
  53492. }
  53493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53494. this._defines.UV2 = true;
  53495. }
  53496. }
  53497. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53498. this._defines.VERTEXCOLOR = true;
  53499. if (mesh.hasVertexAlpha) {
  53500. this._defines.VERTEXALPHA = true;
  53501. }
  53502. }
  53503. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53504. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53505. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53506. }
  53507. // Instances
  53508. if (useInstances) {
  53509. this._defines.INSTANCES = true;
  53510. }
  53511. }
  53512. // Get correct effect
  53513. if (!this._defines.isEqual(this._cachedDefines)) {
  53514. this._defines.cloneTo(this._cachedDefines);
  53515. scene.resetCachedMaterial();
  53516. // Fallbacks
  53517. var fallbacks = new BABYLON.EffectFallbacks();
  53518. if (this._defines.REFLECTION) {
  53519. fallbacks.addFallback(0, "REFLECTION");
  53520. }
  53521. if (this._defines.REFRACTION) {
  53522. fallbacks.addFallback(0, "REFRACTION");
  53523. }
  53524. if (this._defines.REFLECTIVITY) {
  53525. fallbacks.addFallback(0, "REFLECTIVITY");
  53526. }
  53527. if (this._defines.BUMP) {
  53528. fallbacks.addFallback(0, "BUMP");
  53529. }
  53530. if (this._defines.PARALLAX) {
  53531. fallbacks.addFallback(1, "PARALLAX");
  53532. }
  53533. if (this._defines.PARALLAXOCCLUSION) {
  53534. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53535. }
  53536. if (this._defines.SPECULAROVERALPHA) {
  53537. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53538. }
  53539. if (this._defines.FOG) {
  53540. fallbacks.addFallback(1, "FOG");
  53541. }
  53542. if (this._defines.POINTSIZE) {
  53543. fallbacks.addFallback(0, "POINTSIZE");
  53544. }
  53545. if (this._defines.LOGARITHMICDEPTH) {
  53546. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53547. }
  53548. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53549. if (this._defines.SPECULARTERM) {
  53550. fallbacks.addFallback(0, "SPECULARTERM");
  53551. }
  53552. if (this._defines.OPACITYFRESNEL) {
  53553. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53554. }
  53555. if (this._defines.EMISSIVEFRESNEL) {
  53556. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53557. }
  53558. if (this._defines.FRESNEL) {
  53559. fallbacks.addFallback(3, "FRESNEL");
  53560. }
  53561. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53562. fallbacks.addCPUSkinningFallback(0, mesh);
  53563. }
  53564. //Attributes
  53565. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53566. if (this._defines.NORMAL) {
  53567. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53568. }
  53569. if (this._defines.UV1) {
  53570. attribs.push(BABYLON.VertexBuffer.UVKind);
  53571. }
  53572. if (this._defines.UV2) {
  53573. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53574. }
  53575. if (this._defines.VERTEXCOLOR) {
  53576. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53577. }
  53578. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53579. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53580. // Legacy browser patch
  53581. var join = this._defines.toString();
  53582. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53583. "vFogInfos", "vFogColor", "pointSize",
  53584. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53585. "mBones",
  53586. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53587. "depthValues",
  53588. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53589. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53590. "logarithmicDepthConstant",
  53591. "vSphericalX", "vSphericalY", "vSphericalZ",
  53592. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53593. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53594. "vMicrosurfaceTextureLods",
  53595. "vCameraInfos"
  53596. ];
  53597. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53598. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53599. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53600. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53601. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53602. }
  53603. if (!this._effect.isReady()) {
  53604. return false;
  53605. }
  53606. this._renderId = scene.getRenderId();
  53607. this._wasPreviouslyReady = true;
  53608. if (mesh) {
  53609. if (!mesh._materialDefines) {
  53610. mesh._materialDefines = new PBRMaterialDefines();
  53611. }
  53612. this._defines.cloneTo(mesh._materialDefines);
  53613. }
  53614. return true;
  53615. };
  53616. PBRMaterial.prototype.unbind = function () {
  53617. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53618. this._effect.setTexture("reflection2DSampler", null);
  53619. }
  53620. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53621. this._effect.setTexture("refraction2DSampler", null);
  53622. }
  53623. _super.prototype.unbind.call(this);
  53624. };
  53625. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53626. this._effect.setMatrix("world", world);
  53627. };
  53628. PBRMaterial.prototype.bind = function (world, mesh) {
  53629. this._myScene = this.getScene();
  53630. // Matrices
  53631. this.bindOnlyWorldMatrix(world);
  53632. // Bones
  53633. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53634. if (this._myScene.getCachedMaterial() !== this) {
  53635. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53636. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53637. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53638. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53639. }
  53640. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53641. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53642. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53643. }
  53644. }
  53645. // Textures
  53646. if (this._myScene.texturesEnabled) {
  53647. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53648. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53649. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53650. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53651. }
  53652. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53653. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53654. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53655. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53656. }
  53657. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53658. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53659. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53660. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53661. }
  53662. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53663. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53664. if (this.reflectionTexture.isCube) {
  53665. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53666. }
  53667. else {
  53668. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53669. }
  53670. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53671. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53672. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53673. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53674. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53675. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53676. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53677. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53678. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53679. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53680. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53681. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53682. }
  53683. }
  53684. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53685. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53686. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53687. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53688. }
  53689. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53690. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53691. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53692. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53693. }
  53694. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53695. if (this.metallicTexture) {
  53696. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53697. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53698. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53699. }
  53700. else if (this.reflectivityTexture) {
  53701. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53702. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53703. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53704. }
  53705. }
  53706. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53707. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53708. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53709. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53710. }
  53711. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53712. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53713. var depth = 1.0;
  53714. if (this.refractionTexture.isCube) {
  53715. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53716. }
  53717. else {
  53718. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53719. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53720. if (this.refractionTexture.depth) {
  53721. depth = this.refractionTexture.depth;
  53722. }
  53723. }
  53724. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53725. }
  53726. if ((this.reflectionTexture || this.refractionTexture)) {
  53727. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53728. }
  53729. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53730. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53731. }
  53732. }
  53733. // Clip plane
  53734. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53735. // Point size
  53736. if (this.pointsCloud) {
  53737. this._effect.setFloat("pointSize", this.pointSize);
  53738. }
  53739. // Colors
  53740. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53741. // GAMMA CORRECTION.
  53742. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53743. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53744. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53745. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53746. // GAMMA CORRECTION.
  53747. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53748. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53749. // GAMMA CORRECTION.
  53750. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53751. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53752. }
  53753. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53754. // GAMMA CORRECTION.
  53755. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53756. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53757. // Lights
  53758. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53759. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53760. }
  53761. // View
  53762. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53763. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53764. }
  53765. // Fog
  53766. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53767. this._lightingInfos.x = this.directIntensity;
  53768. this._lightingInfos.y = this.emissiveIntensity;
  53769. this._lightingInfos.z = this.environmentIntensity;
  53770. this._lightingInfos.w = this.specularIntensity;
  53771. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53772. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53773. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53774. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53775. this._cameraInfos.x = this.cameraExposure;
  53776. this._cameraInfos.y = this.cameraContrast;
  53777. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53778. if (this.cameraColorCurves) {
  53779. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53780. }
  53781. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53782. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53783. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53784. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53785. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53786. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53787. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53788. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53789. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53790. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53791. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53792. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53793. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53794. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53795. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53796. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53797. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53798. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53799. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53800. // Log. depth
  53801. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53802. }
  53803. _super.prototype.bind.call(this, world, mesh);
  53804. this._myScene = null;
  53805. };
  53806. PBRMaterial.prototype.getAnimatables = function () {
  53807. var results = [];
  53808. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53809. results.push(this.albedoTexture);
  53810. }
  53811. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53812. results.push(this.ambientTexture);
  53813. }
  53814. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53815. results.push(this.opacityTexture);
  53816. }
  53817. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53818. results.push(this.reflectionTexture);
  53819. }
  53820. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53821. results.push(this.emissiveTexture);
  53822. }
  53823. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53824. results.push(this.metallicTexture);
  53825. }
  53826. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53827. results.push(this.reflectivityTexture);
  53828. }
  53829. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53830. results.push(this.bumpTexture);
  53831. }
  53832. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53833. results.push(this.lightmapTexture);
  53834. }
  53835. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53836. results.push(this.refractionTexture);
  53837. }
  53838. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53839. results.push(this.cameraColorGradingTexture);
  53840. }
  53841. return results;
  53842. };
  53843. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53844. if (forceDisposeTextures) {
  53845. if (this.albedoTexture) {
  53846. this.albedoTexture.dispose();
  53847. }
  53848. if (this.ambientTexture) {
  53849. this.ambientTexture.dispose();
  53850. }
  53851. if (this.opacityTexture) {
  53852. this.opacityTexture.dispose();
  53853. }
  53854. if (this.reflectionTexture) {
  53855. this.reflectionTexture.dispose();
  53856. }
  53857. if (this.emissiveTexture) {
  53858. this.emissiveTexture.dispose();
  53859. }
  53860. if (this.metallicTexture) {
  53861. this.metallicTexture.dispose();
  53862. }
  53863. if (this.reflectivityTexture) {
  53864. this.reflectivityTexture.dispose();
  53865. }
  53866. if (this.bumpTexture) {
  53867. this.bumpTexture.dispose();
  53868. }
  53869. if (this.lightmapTexture) {
  53870. this.lightmapTexture.dispose();
  53871. }
  53872. if (this.refractionTexture) {
  53873. this.refractionTexture.dispose();
  53874. }
  53875. if (this.cameraColorGradingTexture) {
  53876. this.cameraColorGradingTexture.dispose();
  53877. }
  53878. }
  53879. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53880. };
  53881. PBRMaterial.prototype.clone = function (name) {
  53882. var _this = this;
  53883. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53884. };
  53885. PBRMaterial.prototype.serialize = function () {
  53886. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53887. serializationObject.customType = "BABYLON.PBRMaterial";
  53888. return serializationObject;
  53889. };
  53890. // Statics
  53891. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53892. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53893. };
  53894. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53895. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53896. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53897. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53898. __decorate([
  53899. BABYLON.serialize()
  53900. ], PBRMaterial.prototype, "directIntensity", void 0);
  53901. __decorate([
  53902. BABYLON.serialize()
  53903. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53904. __decorate([
  53905. BABYLON.serialize()
  53906. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53907. __decorate([
  53908. BABYLON.serialize()
  53909. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53910. __decorate([
  53911. BABYLON.serialize()
  53912. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53913. __decorate([
  53914. BABYLON.serialize()
  53915. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53916. __decorate([
  53917. BABYLON.serialize()
  53918. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53919. __decorate([
  53920. BABYLON.serialize()
  53921. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53922. __decorate([
  53923. BABYLON.serialize()
  53924. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53925. __decorate([
  53926. BABYLON.serializeAsTexture()
  53927. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53928. __decorate([
  53929. BABYLON.serializeAsColorCurves()
  53930. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53931. __decorate([
  53932. BABYLON.serializeAsColor3()
  53933. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53934. __decorate([
  53935. BABYLON.serialize()
  53936. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53937. __decorate([
  53938. BABYLON.serializeAsColor3()
  53939. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53940. __decorate([
  53941. BABYLON.serialize()
  53942. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53943. __decorate([
  53944. BABYLON.serializeAsColor3()
  53945. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53946. __decorate([
  53947. BABYLON.serialize()
  53948. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53949. __decorate([
  53950. BABYLON.serializeAsColor3()
  53951. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  53952. __decorate([
  53953. BABYLON.serialize()
  53954. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  53955. __decorate([
  53956. BABYLON.serializeAsColor3()
  53957. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  53958. __decorate([
  53959. BABYLON.serialize()
  53960. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  53961. __decorate([
  53962. BABYLON.serialize()
  53963. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  53964. __decorate([
  53965. BABYLON.serialize()
  53966. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  53967. __decorate([
  53968. BABYLON.serializeAsTexture()
  53969. ], PBRMaterial.prototype, "albedoTexture", void 0);
  53970. __decorate([
  53971. BABYLON.serializeAsTexture()
  53972. ], PBRMaterial.prototype, "ambientTexture", void 0);
  53973. __decorate([
  53974. BABYLON.serialize()
  53975. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  53976. __decorate([
  53977. BABYLON.serializeAsTexture()
  53978. ], PBRMaterial.prototype, "opacityTexture", void 0);
  53979. __decorate([
  53980. BABYLON.serializeAsTexture()
  53981. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  53982. __decorate([
  53983. BABYLON.serializeAsTexture()
  53984. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  53985. __decorate([
  53986. BABYLON.serializeAsTexture()
  53987. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  53988. __decorate([
  53989. BABYLON.serializeAsTexture()
  53990. ], PBRMaterial.prototype, "metallicTexture", void 0);
  53991. __decorate([
  53992. BABYLON.serializeAsTexture()
  53993. ], PBRMaterial.prototype, "bumpTexture", void 0);
  53994. __decorate([
  53995. BABYLON.serializeAsTexture()
  53996. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  53997. __decorate([
  53998. BABYLON.serializeAsTexture()
  53999. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54000. __decorate([
  54001. BABYLON.serializeAsColor3("ambient")
  54002. ], PBRMaterial.prototype, "ambientColor", void 0);
  54003. __decorate([
  54004. BABYLON.serializeAsColor3("albedo")
  54005. ], PBRMaterial.prototype, "albedoColor", void 0);
  54006. __decorate([
  54007. BABYLON.serializeAsColor3("reflectivity")
  54008. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54009. __decorate([
  54010. BABYLON.serializeAsColor3("reflection")
  54011. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54012. __decorate([
  54013. BABYLON.serializeAsColor3("emissive")
  54014. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54015. __decorate([
  54016. BABYLON.serialize()
  54017. ], PBRMaterial.prototype, "microSurface", void 0);
  54018. __decorate([
  54019. BABYLON.serialize()
  54020. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54021. __decorate([
  54022. BABYLON.serialize()
  54023. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54024. __decorate([
  54025. BABYLON.serializeAsFresnelParameters()
  54026. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54027. __decorate([
  54028. BABYLON.serializeAsFresnelParameters()
  54029. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54030. __decorate([
  54031. BABYLON.serialize()
  54032. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54033. __decorate([
  54034. BABYLON.serialize()
  54035. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54036. __decorate([
  54037. BABYLON.serialize()
  54038. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54039. __decorate([
  54040. BABYLON.serialize()
  54041. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54042. __decorate([
  54043. BABYLON.serialize()
  54044. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54045. __decorate([
  54046. BABYLON.serialize()
  54047. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54048. __decorate([
  54049. BABYLON.serialize()
  54050. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54051. __decorate([
  54052. BABYLON.serialize()
  54053. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54054. __decorate([
  54055. BABYLON.serialize()
  54056. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54057. __decorate([
  54058. BABYLON.serialize()
  54059. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54066. __decorate([
  54067. BABYLON.serialize()
  54068. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54069. __decorate([
  54070. BABYLON.serialize()
  54071. ], PBRMaterial.prototype, "useParallax", void 0);
  54072. __decorate([
  54073. BABYLON.serialize()
  54074. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54075. __decorate([
  54076. BABYLON.serialize()
  54077. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54078. __decorate([
  54079. BABYLON.serialize()
  54080. ], PBRMaterial.prototype, "disableLighting", void 0);
  54081. __decorate([
  54082. BABYLON.serialize()
  54083. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54084. __decorate([
  54085. BABYLON.serialize()
  54086. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54087. __decorate([
  54088. BABYLON.serialize()
  54089. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54090. __decorate([
  54091. BABYLON.serialize()
  54092. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54093. return PBRMaterial;
  54094. }(BABYLON.Material));
  54095. BABYLON.PBRMaterial = PBRMaterial;
  54096. })(BABYLON || (BABYLON = {}));
  54097. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54098. var BABYLON;
  54099. (function (BABYLON) {
  54100. var DebugLayer = (function () {
  54101. function DebugLayer(scene) {
  54102. this._scene = scene;
  54103. }
  54104. /** Creates the inspector window. */
  54105. DebugLayer.prototype._createInspector = function () {
  54106. if (!this._inspector) {
  54107. this._inspector = new INSPECTOR.Inspector(this._scene);
  54108. } // else nothing to do,; instance is already existing
  54109. };
  54110. DebugLayer.prototype.isVisible = function () {
  54111. return false;
  54112. };
  54113. DebugLayer.prototype.hide = function () {
  54114. if (this._inspector) {
  54115. this._inspector.dispose();
  54116. this._inspector = null;
  54117. }
  54118. };
  54119. DebugLayer.prototype.show = function () {
  54120. if (typeof INSPECTOR == 'undefined') {
  54121. // Load inspector and add it to the DOM
  54122. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this));
  54123. }
  54124. else {
  54125. // Otherwise creates the inspector
  54126. this._createInspector();
  54127. }
  54128. };
  54129. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54130. return DebugLayer;
  54131. }());
  54132. BABYLON.DebugLayer = DebugLayer;
  54133. })(BABYLON || (BABYLON = {}));
  54134. //# sourceMappingURL=babylon.debugLayer.js.map
  54135. var BABYLON;
  54136. (function (BABYLON) {
  54137. var StandardRenderingPipeline = (function (_super) {
  54138. __extends(StandardRenderingPipeline, _super);
  54139. /**
  54140. * @constructor
  54141. * @param {string} name - The rendering pipeline name
  54142. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54143. * @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)
  54144. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54145. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54146. */
  54147. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54148. var _this = this;
  54149. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54150. _super.call(this, scene.getEngine(), name);
  54151. this.downSampleX4PostProcess = null;
  54152. this.brightPassPostProcess = null;
  54153. this.gaussianBlurHPostProcesses = [];
  54154. this.gaussianBlurVPostProcesses = [];
  54155. this.textureAdderPostProcess = null;
  54156. this.textureAdderFinalPostProcess = null;
  54157. this.lensFlarePostProcess = null;
  54158. this.lensFlareComposePostProcess = null;
  54159. this.depthOfFieldPostProcess = null;
  54160. // Values
  54161. this.brightThreshold = 1.0;
  54162. this.blurWidth = 2.0;
  54163. this.gaussianCoefficient = 0.25;
  54164. this.gaussianMean = 1.0;
  54165. this.gaussianStandardDeviation = 1.0;
  54166. this.exposure = 1.0;
  54167. this.lensTexture = null;
  54168. this.lensColorTexture = null;
  54169. this.lensFlareStrength = 20.0;
  54170. this.lensFlareGhostDispersal = 1.4;
  54171. this.lensFlareHaloWidth = 0.7;
  54172. this.lensFlareDistortionStrength = 16.0;
  54173. this.lensStarTexture = null;
  54174. this.lensFlareDirtTexture = null;
  54175. this.depthOfFieldDistance = 10.0;
  54176. // IAnimatable
  54177. this.animations = [];
  54178. this._depthRenderer = null;
  54179. // Getters and setters
  54180. this._depthOfFieldEnabled = true;
  54181. this._lensFlareEnabled = true;
  54182. // Initialize
  54183. this._scene = scene;
  54184. // Create pass post-processe
  54185. if (!originalPostProcess) {
  54186. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54187. }
  54188. else {
  54189. this.originalPostProcess = originalPostProcess;
  54190. }
  54191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54192. // Create down sample X4 post-process
  54193. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54194. // Create bright pass post-process
  54195. this._createBrightPassPostProcess(scene, ratio / 2);
  54196. // Create gaussian blur post-processes (down sampling blurs)
  54197. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54198. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54199. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54200. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54201. // Create texture adder post-process
  54202. this._createTextureAdderPostProcess(scene, ratio);
  54203. // Create depth-of-field source post-process
  54204. 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);
  54205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54206. // Create lens flare post-process
  54207. this._createLensFlarePostProcess(scene, ratio);
  54208. // Create gaussian blur used by depth-of-field
  54209. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54210. // Create depth-of-field post-process
  54211. this._createDepthOfFieldPostProcess(scene, ratio);
  54212. // Finish
  54213. scene.postProcessRenderPipelineManager.addPipeline(this);
  54214. if (cameras !== null) {
  54215. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54216. }
  54217. // Deactivate
  54218. this.LensFlareEnabled = false;
  54219. this.DepthOfFieldEnabled = false;
  54220. }
  54221. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54222. get: function () {
  54223. return this._depthOfFieldEnabled;
  54224. },
  54225. set: function (enabled) {
  54226. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54227. if (enabled && !this._depthOfFieldEnabled) {
  54228. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54229. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54230. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54231. this._depthRenderer = this._scene.enableDepthRenderer();
  54232. }
  54233. else if (!enabled && this._depthOfFieldEnabled) {
  54234. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54235. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54236. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54237. }
  54238. this._depthOfFieldEnabled = enabled;
  54239. },
  54240. enumerable: true,
  54241. configurable: true
  54242. });
  54243. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54244. get: function () {
  54245. return this._lensFlareEnabled;
  54246. },
  54247. set: function (enabled) {
  54248. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54249. if (enabled && !this._lensFlareEnabled) {
  54250. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54251. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54252. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54253. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54254. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54255. }
  54256. else if (!enabled && this._lensFlareEnabled) {
  54257. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54258. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54259. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54260. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54261. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54262. }
  54263. this._lensFlareEnabled = enabled;
  54264. },
  54265. enumerable: true,
  54266. configurable: true
  54267. });
  54268. // Down Sample X4 Post-Processs
  54269. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54270. var _this = this;
  54271. var downSampleX4Offsets = new Array(32);
  54272. 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);
  54273. this.downSampleX4PostProcess.onApply = function (effect) {
  54274. var id = 0;
  54275. for (var i = -2; i < 2; i++) {
  54276. for (var j = -2; j < 2; j++) {
  54277. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54278. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54279. id += 2;
  54280. }
  54281. }
  54282. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54283. };
  54284. // Add to pipeline
  54285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54286. };
  54287. // Brightpass Post-Process
  54288. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54289. var _this = this;
  54290. var brightOffsets = new Array(8);
  54291. 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);
  54292. this.brightPassPostProcess.onApply = function (effect) {
  54293. var sU = (1.0 / _this.brightPassPostProcess.width);
  54294. var sV = (1.0 / _this.brightPassPostProcess.height);
  54295. brightOffsets[0] = -0.5 * sU;
  54296. brightOffsets[1] = 0.5 * sV;
  54297. brightOffsets[2] = 0.5 * sU;
  54298. brightOffsets[3] = 0.5 * sV;
  54299. brightOffsets[4] = -0.5 * sU;
  54300. brightOffsets[5] = -0.5 * sV;
  54301. brightOffsets[6] = 0.5 * sU;
  54302. brightOffsets[7] = -0.5 * sV;
  54303. effect.setArray2("dsOffsets", brightOffsets);
  54304. effect.setFloat("brightThreshold", _this.brightThreshold);
  54305. };
  54306. // Add to pipeline
  54307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54308. };
  54309. // Create gaussian blur H&V post-processes
  54310. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54311. var _this = this;
  54312. var blurOffsets = new Array(9);
  54313. var blurWeights = new Array(9);
  54314. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54315. var callback = function (height) {
  54316. return function (effect) {
  54317. // Weights
  54318. var x = 0.0;
  54319. for (var i = 0; i < 9; i++) {
  54320. x = (i - 4.0) / 4.0;
  54321. blurWeights[i] =
  54322. _this.gaussianCoefficient
  54323. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54324. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54325. }
  54326. var lastOutputDimensions = {
  54327. width: scene.getEngine().getRenderWidth(),
  54328. height: scene.getEngine().getRenderHeight()
  54329. };
  54330. for (var i = 0; i < 9; i++) {
  54331. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54332. blurOffsets[i] = value;
  54333. }
  54334. effect.setArray("blurOffsets", blurOffsets);
  54335. effect.setArray("blurWeights", blurWeights);
  54336. effect.setFloat("blurWidth", _this.blurWidth);
  54337. };
  54338. };
  54339. // Create horizontal gaussian blur post-processes
  54340. 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);
  54341. gaussianBlurHPostProcess.onApply = callback(false);
  54342. // Create vertical gaussian blur post-process
  54343. 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);
  54344. gaussianBlurVPostProcess.onApply = callback(true);
  54345. // Add to pipeline
  54346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54348. // Finish
  54349. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54350. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54351. };
  54352. // Create texture adder post-process
  54353. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54354. var _this = this;
  54355. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54356. 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);
  54357. this.textureAdderPostProcess.onApply = function (effect) {
  54358. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54359. effect.setTexture("lensSampler", _this.lensTexture);
  54360. effect.setFloat("exposure", _this.exposure);
  54361. };
  54362. // Add to pipeline
  54363. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54364. };
  54365. // Create lens flare post-process
  54366. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54367. var _this = this;
  54368. 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);
  54369. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54370. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54371. 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);
  54372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54373. var resolution = new BABYLON.Vector2(0, 0);
  54374. // Lens flare
  54375. this.lensFlarePostProcess.onApply = function (effect) {
  54376. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54377. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54378. effect.setFloat("strength", _this.lensFlareStrength);
  54379. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54380. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54381. // Shift
  54382. resolution.x = _this.lensFlarePostProcess.width;
  54383. resolution.y = _this.lensFlarePostProcess.height;
  54384. effect.setVector2("resolution", resolution);
  54385. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54386. };
  54387. // Compose
  54388. 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);
  54389. 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);
  54390. this.lensFlareComposePostProcess.onApply = function (effect) {
  54391. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54392. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54393. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54394. // Lens start rotation matrix
  54395. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54396. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54397. 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));
  54398. camRot *= 4.0;
  54399. 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);
  54400. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54401. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54402. };
  54403. };
  54404. // Create depth-of-field post-process
  54405. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54406. var _this = this;
  54407. 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);
  54408. this.depthOfFieldPostProcess.onApply = function (effect) {
  54409. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54410. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54411. effect.setFloat("distance", _this.depthOfFieldDistance);
  54412. };
  54413. // Add to pipeline
  54414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54415. };
  54416. // Dispose
  54417. StandardRenderingPipeline.prototype.dispose = function () {
  54418. for (var i = 0; i < this._scene.cameras.length; i++) {
  54419. var camera = this._scene.cameras[i];
  54420. this.originalPostProcess.dispose(camera);
  54421. this.downSampleX4PostProcess.dispose(camera);
  54422. this.brightPassPostProcess.dispose(camera);
  54423. this.textureAdderPostProcess.dispose(camera);
  54424. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54425. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54426. }
  54427. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54428. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54429. }
  54430. this.textureAdderFinalPostProcess.dispose(camera);
  54431. this.lensFlarePostProcess.dispose(camera);
  54432. this.lensFlareComposePostProcess.dispose(camera);
  54433. this.depthOfFieldPostProcess.dispose(camera);
  54434. }
  54435. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54436. _super.prototype.dispose.call(this);
  54437. };
  54438. return StandardRenderingPipeline;
  54439. }(BABYLON.PostProcessRenderPipeline));
  54440. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54441. })(BABYLON || (BABYLON = {}));
  54442. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54443. 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}"};
  54444. 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"};
  54445. 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={}));";
  54446. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54447. module.exports = BABYLON;
  54448. };