babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289
  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. var defineIndex = this.defines.indexOf("#define " + node.define);
  25475. if (defineIndex === -1) {
  25476. return null;
  25477. }
  25478. var nextComma = this.defines.indexOf("\n", defineIndex);
  25479. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25480. var condition = defineValue + node.condition;
  25481. if (!eval(condition)) {
  25482. return null;
  25483. }
  25484. }
  25485. else if (node.ndef) {
  25486. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25487. return null;
  25488. }
  25489. }
  25490. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25491. return null;
  25492. }
  25493. }
  25494. var result = "";
  25495. for (var index = 0; index < node.children.length; index++) {
  25496. var line = node.children[index];
  25497. if (line.children) {
  25498. var combined = this._recombineShader(line);
  25499. if (combined !== null) {
  25500. result += combined + "\r\n";
  25501. }
  25502. continue;
  25503. }
  25504. if (line.length > 0) {
  25505. result += line + "\r\n";
  25506. }
  25507. }
  25508. return result;
  25509. };
  25510. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25511. var root = {
  25512. children: []
  25513. };
  25514. var currentNode = root;
  25515. var lines = shaderString.split("\n");
  25516. for (var index = 0; index < lines.length; index++) {
  25517. var line = lines[index].trim();
  25518. // #ifdef
  25519. var pos = line.indexOf("#ifdef ");
  25520. if (pos !== -1) {
  25521. var define = line.substr(pos + 7);
  25522. var newNode = {
  25523. condition: null,
  25524. ndef: false,
  25525. define: define,
  25526. children: [],
  25527. parent: currentNode
  25528. };
  25529. currentNode.children.push(newNode);
  25530. currentNode = newNode;
  25531. continue;
  25532. }
  25533. // #ifndef
  25534. var pos = line.indexOf("#ifndef ");
  25535. if (pos !== -1) {
  25536. var define = line.substr(pos + 8);
  25537. newNode = {
  25538. condition: null,
  25539. define: define,
  25540. ndef: true,
  25541. children: [],
  25542. parent: currentNode
  25543. };
  25544. currentNode.children.push(newNode);
  25545. currentNode = newNode;
  25546. continue;
  25547. }
  25548. // #if
  25549. var pos = line.indexOf("#if ");
  25550. if (pos !== -1) {
  25551. var define = line.substr(pos + 4).trim();
  25552. var conditionPos = define.indexOf(" ");
  25553. newNode = {
  25554. condition: define.substr(conditionPos + 1),
  25555. define: define.substr(0, conditionPos),
  25556. ndef: false,
  25557. children: [],
  25558. parent: currentNode
  25559. };
  25560. currentNode.children.push(newNode);
  25561. currentNode = newNode;
  25562. continue;
  25563. }
  25564. // #endif
  25565. pos = line.indexOf("#endif");
  25566. if (pos !== -1) {
  25567. currentNode = currentNode.parent;
  25568. continue;
  25569. }
  25570. currentNode.children.push(line);
  25571. }
  25572. // Recombine
  25573. return this._recombineShader(root);
  25574. };
  25575. // Statics
  25576. Effect.ShadersStore = {};
  25577. Effect.IncludesShadersStore = {};
  25578. return Effect;
  25579. }());
  25580. BABYLON.Effect = Effect;
  25581. })(BABYLON || (BABYLON = {}));
  25582. //# sourceMappingURL=babylon.effect.js.map
  25583. var BABYLON;
  25584. (function (BABYLON) {
  25585. var MaterialHelper = (function () {
  25586. function MaterialHelper() {
  25587. }
  25588. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25589. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25590. var lightIndex = 0;
  25591. var needNormals = false;
  25592. var needRebuild = false;
  25593. var needShadows = false;
  25594. var lightmapMode = false;
  25595. for (var index = 0; index < scene.lights.length; index++) {
  25596. var light = scene.lights[index];
  25597. if (!light.isEnabled()) {
  25598. continue;
  25599. }
  25600. // Excluded check
  25601. if (light._excludedMeshesIds.length > 0) {
  25602. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25603. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25604. if (excludedMesh) {
  25605. light.excludedMeshes.push(excludedMesh);
  25606. }
  25607. }
  25608. light._excludedMeshesIds = [];
  25609. }
  25610. // Included check
  25611. if (light._includedOnlyMeshesIds.length > 0) {
  25612. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25613. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25614. if (includedOnlyMesh) {
  25615. light.includedOnlyMeshes.push(includedOnlyMesh);
  25616. }
  25617. }
  25618. light._includedOnlyMeshesIds = [];
  25619. }
  25620. if (!light.canAffectMesh(mesh)) {
  25621. continue;
  25622. }
  25623. needNormals = true;
  25624. if (defines["LIGHT" + lightIndex] === undefined) {
  25625. needRebuild = true;
  25626. }
  25627. defines["LIGHT" + lightIndex] = true;
  25628. var type;
  25629. if (light instanceof BABYLON.SpotLight) {
  25630. type = "SPOTLIGHT" + lightIndex;
  25631. }
  25632. else if (light instanceof BABYLON.HemisphericLight) {
  25633. type = "HEMILIGHT" + lightIndex;
  25634. }
  25635. else if (light instanceof BABYLON.PointLight) {
  25636. type = "POINTLIGHT" + lightIndex;
  25637. }
  25638. else {
  25639. type = "DIRLIGHT" + lightIndex;
  25640. }
  25641. if (defines[type] === undefined) {
  25642. needRebuild = true;
  25643. }
  25644. defines[type] = true;
  25645. // Specular
  25646. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25647. defines["SPECULARTERM"] = true;
  25648. }
  25649. // Shadows
  25650. if (scene.shadowsEnabled) {
  25651. var shadowGenerator = light.getShadowGenerator();
  25652. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25653. if (defines["SHADOW" + lightIndex] === undefined) {
  25654. needRebuild = true;
  25655. }
  25656. defines["SHADOW" + lightIndex] = true;
  25657. defines["SHADOWS"] = true;
  25658. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25659. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25660. needRebuild = true;
  25661. }
  25662. defines["SHADOWVSM" + lightIndex] = true;
  25663. }
  25664. if (shadowGenerator.usePoissonSampling) {
  25665. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25666. needRebuild = true;
  25667. }
  25668. defines["SHADOWPCF" + lightIndex] = true;
  25669. }
  25670. needShadows = true;
  25671. }
  25672. }
  25673. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25674. lightmapMode = true;
  25675. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25676. needRebuild = true;
  25677. }
  25678. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25679. needRebuild = true;
  25680. }
  25681. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25682. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25683. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25684. }
  25685. }
  25686. lightIndex++;
  25687. if (lightIndex === maxSimultaneousLights)
  25688. break;
  25689. }
  25690. var caps = scene.getEngine().getCaps();
  25691. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25692. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25693. needRebuild = true;
  25694. }
  25695. defines["SHADOWFULLFLOAT"] = true;
  25696. }
  25697. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25698. needRebuild = true;
  25699. }
  25700. if (lightmapMode) {
  25701. defines["LIGHTMAPEXCLUDED"] = true;
  25702. }
  25703. if (needRebuild) {
  25704. defines.rebuild();
  25705. }
  25706. return needNormals;
  25707. };
  25708. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25709. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25710. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25711. if (!defines["LIGHT" + lightIndex]) {
  25712. break;
  25713. }
  25714. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25715. samplersList.push("shadowSampler" + lightIndex);
  25716. }
  25717. };
  25718. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25719. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25720. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25721. if (!defines["LIGHT" + lightIndex]) {
  25722. break;
  25723. }
  25724. if (lightIndex > 0) {
  25725. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25726. }
  25727. if (defines["SHADOW" + lightIndex]) {
  25728. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25729. }
  25730. if (defines["SHADOWPCF" + lightIndex]) {
  25731. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25732. }
  25733. if (defines["SHADOWVSM" + lightIndex]) {
  25734. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25735. }
  25736. }
  25737. };
  25738. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25739. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25740. fallbacks.addCPUSkinningFallback(0, mesh);
  25741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25743. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25746. }
  25747. }
  25748. };
  25749. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25750. if (defines["INSTANCES"]) {
  25751. attribs.push("world0");
  25752. attribs.push("world1");
  25753. attribs.push("world2");
  25754. attribs.push("world3");
  25755. }
  25756. };
  25757. // Bindings
  25758. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25759. var shadowGenerator = light.getShadowGenerator();
  25760. if (mesh.receiveShadows && shadowGenerator) {
  25761. if (!light.needCube()) {
  25762. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25763. }
  25764. else {
  25765. if (!depthValuesAlreadySet) {
  25766. depthValuesAlreadySet = true;
  25767. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25768. }
  25769. }
  25770. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25771. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25772. }
  25773. return depthValuesAlreadySet;
  25774. };
  25775. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25776. if (light instanceof BABYLON.PointLight) {
  25777. // Point Light
  25778. light.transferToEffect(effect, "vLightData" + lightIndex);
  25779. }
  25780. else if (light instanceof BABYLON.DirectionalLight) {
  25781. // Directional Light
  25782. light.transferToEffect(effect, "vLightData" + lightIndex);
  25783. }
  25784. else if (light instanceof BABYLON.SpotLight) {
  25785. // Spot Light
  25786. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25787. }
  25788. else if (light instanceof BABYLON.HemisphericLight) {
  25789. // Hemispheric Light
  25790. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25791. }
  25792. };
  25793. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25794. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25795. var lightIndex = 0;
  25796. var depthValuesAlreadySet = false;
  25797. for (var index = 0; index < scene.lights.length; index++) {
  25798. var light = scene.lights[index];
  25799. if (!light.isEnabled()) {
  25800. continue;
  25801. }
  25802. if (!light.canAffectMesh(mesh)) {
  25803. continue;
  25804. }
  25805. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25806. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25807. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25808. if (defines["SPECULARTERM"]) {
  25809. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25810. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25811. }
  25812. // Shadows
  25813. if (scene.shadowsEnabled) {
  25814. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25815. }
  25816. lightIndex++;
  25817. if (lightIndex === maxSimultaneousLights)
  25818. break;
  25819. }
  25820. };
  25821. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25822. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25823. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25824. effect.setColor3("vFogColor", scene.fogColor);
  25825. }
  25826. };
  25827. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25828. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25829. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25830. if (matrices) {
  25831. effect.setMatrices("mBones", matrices);
  25832. }
  25833. }
  25834. };
  25835. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25836. if (defines["LOGARITHMICDEPTH"]) {
  25837. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25838. }
  25839. };
  25840. MaterialHelper.BindClipPlane = function (effect, scene) {
  25841. if (scene.clipPlane) {
  25842. var clipPlane = scene.clipPlane;
  25843. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25844. }
  25845. };
  25846. return MaterialHelper;
  25847. }());
  25848. BABYLON.MaterialHelper = MaterialHelper;
  25849. })(BABYLON || (BABYLON = {}));
  25850. //# sourceMappingURL=babylon.materialHelper.js.map
  25851. var BABYLON;
  25852. (function (BABYLON) {
  25853. var FresnelParameters = (function () {
  25854. function FresnelParameters() {
  25855. this.isEnabled = true;
  25856. this.leftColor = BABYLON.Color3.White();
  25857. this.rightColor = BABYLON.Color3.Black();
  25858. this.bias = 0;
  25859. this.power = 1;
  25860. }
  25861. FresnelParameters.prototype.clone = function () {
  25862. var newFresnelParameters = new FresnelParameters();
  25863. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25864. return newFresnelParameters;
  25865. };
  25866. FresnelParameters.prototype.serialize = function () {
  25867. var serializationObject = {};
  25868. serializationObject.isEnabled = this.isEnabled;
  25869. serializationObject.leftColor = this.leftColor;
  25870. serializationObject.rightColor = this.rightColor;
  25871. serializationObject.bias = this.bias;
  25872. serializationObject.power = this.power;
  25873. return serializationObject;
  25874. };
  25875. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25876. var fresnelParameters = new FresnelParameters();
  25877. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25878. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25879. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25880. fresnelParameters.bias = parsedFresnelParameters.bias;
  25881. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25882. return fresnelParameters;
  25883. };
  25884. return FresnelParameters;
  25885. }());
  25886. BABYLON.FresnelParameters = FresnelParameters;
  25887. })(BABYLON || (BABYLON = {}));
  25888. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25889. var BABYLON;
  25890. (function (BABYLON) {
  25891. var MaterialDefines = (function () {
  25892. function MaterialDefines() {
  25893. }
  25894. MaterialDefines.prototype.rebuild = function () {
  25895. if (this._keys) {
  25896. delete this._keys;
  25897. }
  25898. this._keys = Object.keys(this);
  25899. };
  25900. MaterialDefines.prototype.isEqual = function (other) {
  25901. if (this._keys.length !== other._keys.length) {
  25902. return false;
  25903. }
  25904. for (var index = 0; index < this._keys.length; index++) {
  25905. var prop = this._keys[index];
  25906. if (this[prop] !== other[prop]) {
  25907. return false;
  25908. }
  25909. }
  25910. return true;
  25911. };
  25912. MaterialDefines.prototype.cloneTo = function (other) {
  25913. if (this._keys.length !== other._keys.length) {
  25914. other._keys = this._keys.slice(0);
  25915. }
  25916. for (var index = 0; index < this._keys.length; index++) {
  25917. var prop = this._keys[index];
  25918. other[prop] = this[prop];
  25919. }
  25920. };
  25921. MaterialDefines.prototype.reset = function () {
  25922. for (var index = 0; index < this._keys.length; index++) {
  25923. var prop = this._keys[index];
  25924. if (typeof (this[prop]) === "number") {
  25925. this[prop] = 0;
  25926. }
  25927. else {
  25928. this[prop] = false;
  25929. }
  25930. }
  25931. };
  25932. MaterialDefines.prototype.toString = function () {
  25933. var result = "";
  25934. for (var index = 0; index < this._keys.length; index++) {
  25935. var prop = this._keys[index];
  25936. if (typeof (this[prop]) === "number") {
  25937. result += "#define " + prop + " " + this[prop] + "\n";
  25938. }
  25939. else if (this[prop]) {
  25940. result += "#define " + prop + "\n";
  25941. }
  25942. }
  25943. return result;
  25944. };
  25945. return MaterialDefines;
  25946. }());
  25947. BABYLON.MaterialDefines = MaterialDefines;
  25948. var Material = (function () {
  25949. function Material(name, scene, doNotAdd) {
  25950. this.checkReadyOnEveryCall = false;
  25951. this.checkReadyOnlyOnce = false;
  25952. this.state = "";
  25953. this.alpha = 1.0;
  25954. this.backFaceCulling = true;
  25955. this.doNotSerialize = false;
  25956. /**
  25957. * An event triggered when the material is disposed.
  25958. * @type {BABYLON.Observable}
  25959. */
  25960. this.onDisposeObservable = new BABYLON.Observable();
  25961. /**
  25962. * An event triggered when the material is bound.
  25963. * @type {BABYLON.Observable}
  25964. */
  25965. this.onBindObservable = new BABYLON.Observable();
  25966. /**
  25967. * An event triggered when the material is unbound.
  25968. * @type {BABYLON.Observable}
  25969. */
  25970. this.onUnBindObservable = new BABYLON.Observable();
  25971. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25972. this.disableDepthWrite = false;
  25973. this.fogEnabled = true;
  25974. this.pointSize = 1.0;
  25975. this.zOffset = 0;
  25976. this._wasPreviouslyReady = false;
  25977. this._fillMode = Material.TriangleFillMode;
  25978. this.name = name;
  25979. this.id = name;
  25980. this._scene = scene;
  25981. if (scene.useRightHandedSystem) {
  25982. this.sideOrientation = Material.ClockWiseSideOrientation;
  25983. }
  25984. else {
  25985. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25986. }
  25987. if (!doNotAdd) {
  25988. scene.materials.push(this);
  25989. }
  25990. }
  25991. Object.defineProperty(Material, "TriangleFillMode", {
  25992. get: function () {
  25993. return Material._TriangleFillMode;
  25994. },
  25995. enumerable: true,
  25996. configurable: true
  25997. });
  25998. Object.defineProperty(Material, "WireFrameFillMode", {
  25999. get: function () {
  26000. return Material._WireFrameFillMode;
  26001. },
  26002. enumerable: true,
  26003. configurable: true
  26004. });
  26005. Object.defineProperty(Material, "PointFillMode", {
  26006. get: function () {
  26007. return Material._PointFillMode;
  26008. },
  26009. enumerable: true,
  26010. configurable: true
  26011. });
  26012. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26013. get: function () {
  26014. return Material._ClockWiseSideOrientation;
  26015. },
  26016. enumerable: true,
  26017. configurable: true
  26018. });
  26019. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26020. get: function () {
  26021. return Material._CounterClockWiseSideOrientation;
  26022. },
  26023. enumerable: true,
  26024. configurable: true
  26025. });
  26026. Object.defineProperty(Material.prototype, "onDispose", {
  26027. set: function (callback) {
  26028. if (this._onDisposeObserver) {
  26029. this.onDisposeObservable.remove(this._onDisposeObserver);
  26030. }
  26031. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. Object.defineProperty(Material.prototype, "onBind", {
  26037. set: function (callback) {
  26038. if (this._onBindObserver) {
  26039. this.onBindObservable.remove(this._onBindObserver);
  26040. }
  26041. this._onBindObserver = this.onBindObservable.add(callback);
  26042. },
  26043. enumerable: true,
  26044. configurable: true
  26045. });
  26046. Object.defineProperty(Material.prototype, "wireframe", {
  26047. get: function () {
  26048. return this._fillMode === Material.WireFrameFillMode;
  26049. },
  26050. set: function (value) {
  26051. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26052. },
  26053. enumerable: true,
  26054. configurable: true
  26055. });
  26056. Object.defineProperty(Material.prototype, "pointsCloud", {
  26057. get: function () {
  26058. return this._fillMode === Material.PointFillMode;
  26059. },
  26060. set: function (value) {
  26061. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26062. },
  26063. enumerable: true,
  26064. configurable: true
  26065. });
  26066. Object.defineProperty(Material.prototype, "fillMode", {
  26067. get: function () {
  26068. return this._fillMode;
  26069. },
  26070. set: function (value) {
  26071. this._fillMode = value;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. /**
  26077. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26078. * subclasses should override adding information pertainent to themselves
  26079. */
  26080. Material.prototype.toString = function (fullDetails) {
  26081. var ret = "Name: " + this.name;
  26082. if (fullDetails) {
  26083. }
  26084. return ret;
  26085. };
  26086. Material.prototype.getClassName = function () {
  26087. return "Material";
  26088. };
  26089. Object.defineProperty(Material.prototype, "isFrozen", {
  26090. get: function () {
  26091. return this.checkReadyOnlyOnce;
  26092. },
  26093. enumerable: true,
  26094. configurable: true
  26095. });
  26096. Material.prototype.freeze = function () {
  26097. this.checkReadyOnlyOnce = true;
  26098. };
  26099. Material.prototype.unfreeze = function () {
  26100. this.checkReadyOnlyOnce = false;
  26101. };
  26102. Material.prototype.isReady = function (mesh, useInstances) {
  26103. return true;
  26104. };
  26105. Material.prototype.getEffect = function () {
  26106. return this._effect;
  26107. };
  26108. Material.prototype.getScene = function () {
  26109. return this._scene;
  26110. };
  26111. Material.prototype.needAlphaBlending = function () {
  26112. return (this.alpha < 1.0);
  26113. };
  26114. Material.prototype.needAlphaTesting = function () {
  26115. return false;
  26116. };
  26117. Material.prototype.getAlphaTestTexture = function () {
  26118. return null;
  26119. };
  26120. Material.prototype.markDirty = function () {
  26121. this._wasPreviouslyReady = false;
  26122. };
  26123. Material.prototype._preBind = function () {
  26124. var engine = this._scene.getEngine();
  26125. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26126. engine.enableEffect(this._effect);
  26127. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26128. };
  26129. Material.prototype.bind = function (world, mesh) {
  26130. this._scene._cachedMaterial = this;
  26131. this.onBindObservable.notifyObservers(mesh);
  26132. if (this.disableDepthWrite) {
  26133. var engine = this._scene.getEngine();
  26134. this._cachedDepthWriteState = engine.getDepthWrite();
  26135. engine.setDepthWrite(false);
  26136. }
  26137. };
  26138. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26139. };
  26140. Material.prototype.unbind = function () {
  26141. this.onUnBindObservable.notifyObservers(this);
  26142. if (this.disableDepthWrite) {
  26143. var engine = this._scene.getEngine();
  26144. engine.setDepthWrite(this._cachedDepthWriteState);
  26145. }
  26146. };
  26147. Material.prototype.clone = function (name) {
  26148. return null;
  26149. };
  26150. Material.prototype.getBindedMeshes = function () {
  26151. var result = new Array();
  26152. for (var index = 0; index < this._scene.meshes.length; index++) {
  26153. var mesh = this._scene.meshes[index];
  26154. if (mesh.material === this) {
  26155. result.push(mesh);
  26156. }
  26157. }
  26158. return result;
  26159. };
  26160. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26161. // Animations
  26162. this.getScene().stopAnimation(this);
  26163. // Remove from scene
  26164. var index = this._scene.materials.indexOf(this);
  26165. if (index >= 0) {
  26166. this._scene.materials.splice(index, 1);
  26167. }
  26168. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26169. if (forceDisposeEffect && this._effect) {
  26170. this._scene.getEngine()._releaseEffect(this._effect);
  26171. this._effect = null;
  26172. }
  26173. // Remove from meshes
  26174. for (index = 0; index < this._scene.meshes.length; index++) {
  26175. var mesh = this._scene.meshes[index];
  26176. if (mesh.material === this) {
  26177. mesh.material = null;
  26178. }
  26179. }
  26180. // Callback
  26181. this.onDisposeObservable.notifyObservers(this);
  26182. this.onDisposeObservable.clear();
  26183. this.onBindObservable.clear();
  26184. this.onUnBindObservable.clear();
  26185. };
  26186. Material.prototype.serialize = function () {
  26187. return BABYLON.SerializationHelper.Serialize(this);
  26188. };
  26189. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26190. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26191. multiMaterial.id = parsedMultiMaterial.id;
  26192. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26193. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26194. var subMatId = parsedMultiMaterial.materials[matIndex];
  26195. if (subMatId) {
  26196. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26197. }
  26198. else {
  26199. multiMaterial.subMaterials.push(null);
  26200. }
  26201. }
  26202. return multiMaterial;
  26203. };
  26204. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26205. if (!parsedMaterial.customType) {
  26206. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26207. }
  26208. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26209. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26210. ;
  26211. };
  26212. Material._TriangleFillMode = 0;
  26213. Material._WireFrameFillMode = 1;
  26214. Material._PointFillMode = 2;
  26215. Material._ClockWiseSideOrientation = 0;
  26216. Material._CounterClockWiseSideOrientation = 1;
  26217. __decorate([
  26218. BABYLON.serialize()
  26219. ], Material.prototype, "id", void 0);
  26220. __decorate([
  26221. BABYLON.serialize()
  26222. ], Material.prototype, "name", void 0);
  26223. __decorate([
  26224. BABYLON.serialize()
  26225. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26226. __decorate([
  26227. BABYLON.serialize()
  26228. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26229. __decorate([
  26230. BABYLON.serialize()
  26231. ], Material.prototype, "state", void 0);
  26232. __decorate([
  26233. BABYLON.serialize()
  26234. ], Material.prototype, "alpha", void 0);
  26235. __decorate([
  26236. BABYLON.serialize()
  26237. ], Material.prototype, "backFaceCulling", void 0);
  26238. __decorate([
  26239. BABYLON.serialize()
  26240. ], Material.prototype, "sideOrientation", void 0);
  26241. __decorate([
  26242. BABYLON.serialize()
  26243. ], Material.prototype, "alphaMode", void 0);
  26244. __decorate([
  26245. BABYLON.serialize()
  26246. ], Material.prototype, "disableDepthWrite", void 0);
  26247. __decorate([
  26248. BABYLON.serialize()
  26249. ], Material.prototype, "fogEnabled", void 0);
  26250. __decorate([
  26251. BABYLON.serialize()
  26252. ], Material.prototype, "pointSize", void 0);
  26253. __decorate([
  26254. BABYLON.serialize()
  26255. ], Material.prototype, "zOffset", void 0);
  26256. __decorate([
  26257. BABYLON.serialize()
  26258. ], Material.prototype, "wireframe", null);
  26259. __decorate([
  26260. BABYLON.serialize()
  26261. ], Material.prototype, "pointsCloud", null);
  26262. __decorate([
  26263. BABYLON.serialize()
  26264. ], Material.prototype, "fillMode", null);
  26265. return Material;
  26266. }());
  26267. BABYLON.Material = Material;
  26268. })(BABYLON || (BABYLON = {}));
  26269. //# sourceMappingURL=babylon.material.js.map
  26270. var BABYLON;
  26271. (function (BABYLON) {
  26272. var StandardMaterialDefines = (function (_super) {
  26273. __extends(StandardMaterialDefines, _super);
  26274. function StandardMaterialDefines() {
  26275. _super.call(this);
  26276. this.DIFFUSE = false;
  26277. this.AMBIENT = false;
  26278. this.OPACITY = false;
  26279. this.OPACITYRGB = false;
  26280. this.REFLECTION = false;
  26281. this.EMISSIVE = false;
  26282. this.SPECULAR = false;
  26283. this.BUMP = false;
  26284. this.PARALLAX = false;
  26285. this.PARALLAXOCCLUSION = false;
  26286. this.SPECULAROVERALPHA = false;
  26287. this.CLIPPLANE = false;
  26288. this.ALPHATEST = false;
  26289. this.ALPHAFROMDIFFUSE = false;
  26290. this.POINTSIZE = false;
  26291. this.FOG = false;
  26292. this.SPECULARTERM = false;
  26293. this.DIFFUSEFRESNEL = false;
  26294. this.OPACITYFRESNEL = false;
  26295. this.REFLECTIONFRESNEL = false;
  26296. this.REFRACTIONFRESNEL = false;
  26297. this.EMISSIVEFRESNEL = false;
  26298. this.FRESNEL = false;
  26299. this.NORMAL = false;
  26300. this.UV1 = false;
  26301. this.UV2 = false;
  26302. this.VERTEXCOLOR = false;
  26303. this.VERTEXALPHA = false;
  26304. this.NUM_BONE_INFLUENCERS = 0;
  26305. this.BonesPerMesh = 0;
  26306. this.INSTANCES = false;
  26307. this.GLOSSINESS = false;
  26308. this.ROUGHNESS = false;
  26309. this.EMISSIVEASILLUMINATION = false;
  26310. this.LINKEMISSIVEWITHDIFFUSE = false;
  26311. this.REFLECTIONFRESNELFROMSPECULAR = false;
  26312. this.LIGHTMAP = false;
  26313. this.USELIGHTMAPASSHADOWMAP = false;
  26314. this.REFLECTIONMAP_3D = false;
  26315. this.REFLECTIONMAP_SPHERICAL = false;
  26316. this.REFLECTIONMAP_PLANAR = false;
  26317. this.REFLECTIONMAP_CUBIC = false;
  26318. this.REFLECTIONMAP_PROJECTION = false;
  26319. this.REFLECTIONMAP_SKYBOX = false;
  26320. this.REFLECTIONMAP_EXPLICIT = false;
  26321. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26322. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26323. this.INVERTCUBICMAP = false;
  26324. this.LOGARITHMICDEPTH = false;
  26325. this.REFRACTION = false;
  26326. this.REFRACTIONMAP_3D = false;
  26327. this.REFLECTIONOVERALPHA = false;
  26328. this.INVERTNORMALMAPX = false;
  26329. this.INVERTNORMALMAPY = false;
  26330. this.SHADOWFULLFLOAT = false;
  26331. this.CAMERACOLORGRADING = false;
  26332. this.CAMERACOLORCURVES = false;
  26333. this.rebuild();
  26334. }
  26335. return StandardMaterialDefines;
  26336. }(BABYLON.MaterialDefines));
  26337. var StandardMaterial = (function (_super) {
  26338. __extends(StandardMaterial, _super);
  26339. function StandardMaterial(name, scene) {
  26340. var _this = this;
  26341. _super.call(this, name, scene);
  26342. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26343. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26344. this.specularColor = new BABYLON.Color3(1, 1, 1);
  26345. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26346. this.specularPower = 64;
  26347. this.useAlphaFromDiffuseTexture = false;
  26348. this.useEmissiveAsIllumination = false;
  26349. this.linkEmissiveWithDiffuse = false;
  26350. this.useReflectionFresnelFromSpecular = false;
  26351. this.useSpecularOverAlpha = false;
  26352. this.useReflectionOverAlpha = false;
  26353. this.disableLighting = false;
  26354. this.useParallax = false;
  26355. this.useParallaxOcclusion = false;
  26356. this.parallaxScaleBias = 0.05;
  26357. this.roughness = 0;
  26358. this.indexOfRefraction = 0.98;
  26359. this.invertRefractionY = true;
  26360. this.useLightmapAsShadowmap = false;
  26361. this.useGlossinessFromSpecularMapAlpha = false;
  26362. this.maxSimultaneousLights = 4;
  26363. /**
  26364. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26365. */
  26366. this.invertNormalMapX = false;
  26367. /**
  26368. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26369. */
  26370. this.invertNormalMapY = false;
  26371. /**
  26372. * Color Grading 2D Lookup Texture.
  26373. * This allows special effects like sepia, black and white to sixties rendering style.
  26374. */
  26375. this.cameraColorGradingTexture = null;
  26376. /**
  26377. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26378. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26379. * 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;
  26380. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26381. */
  26382. this.cameraColorCurves = null;
  26383. this._renderTargets = new BABYLON.SmartArray(16);
  26384. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26385. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26386. this._defines = new StandardMaterialDefines();
  26387. this._cachedDefines = new StandardMaterialDefines();
  26388. this._cachedDefines.BonesPerMesh = -1;
  26389. this.getRenderTargetTextures = function () {
  26390. _this._renderTargets.reset();
  26391. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26392. _this._renderTargets.push(_this.reflectionTexture);
  26393. }
  26394. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26395. _this._renderTargets.push(_this.refractionTexture);
  26396. }
  26397. return _this._renderTargets;
  26398. };
  26399. }
  26400. StandardMaterial.prototype.getClassName = function () {
  26401. return "StandardMaterial";
  26402. };
  26403. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26404. get: function () {
  26405. return this._useLogarithmicDepth;
  26406. },
  26407. set: function (value) {
  26408. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. StandardMaterial.prototype.needAlphaBlending = function () {
  26414. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26415. };
  26416. StandardMaterial.prototype.needAlphaTesting = function () {
  26417. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26418. };
  26419. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26420. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26421. };
  26422. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26423. return this.diffuseTexture;
  26424. };
  26425. // Methods
  26426. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26427. if (!mesh) {
  26428. return true;
  26429. }
  26430. if (this._defines.INSTANCES !== useInstances) {
  26431. return false;
  26432. }
  26433. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26434. return true;
  26435. }
  26436. return false;
  26437. };
  26438. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26439. if (this.isFrozen) {
  26440. if (this._wasPreviouslyReady) {
  26441. return true;
  26442. }
  26443. }
  26444. var scene = this.getScene();
  26445. var engine = scene.getEngine();
  26446. var needUVs = false;
  26447. var needNormals = false;
  26448. this._defines.reset();
  26449. // Lights
  26450. if (scene.lightsEnabled && !this.disableLighting) {
  26451. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26452. }
  26453. if (!this.checkReadyOnEveryCall) {
  26454. if (this._renderId === scene.getRenderId()) {
  26455. if (this._checkCache(scene, mesh, useInstances)) {
  26456. return true;
  26457. }
  26458. }
  26459. }
  26460. // Textures
  26461. if (scene.texturesEnabled) {
  26462. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26463. if (!this.diffuseTexture.isReady()) {
  26464. return false;
  26465. }
  26466. else {
  26467. needUVs = true;
  26468. this._defines.DIFFUSE = true;
  26469. }
  26470. }
  26471. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26472. if (!this.ambientTexture.isReady()) {
  26473. return false;
  26474. }
  26475. else {
  26476. needUVs = true;
  26477. this._defines.AMBIENT = true;
  26478. }
  26479. }
  26480. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26481. if (!this.opacityTexture.isReady()) {
  26482. return false;
  26483. }
  26484. else {
  26485. needUVs = true;
  26486. this._defines.OPACITY = true;
  26487. if (this.opacityTexture.getAlphaFromRGB) {
  26488. this._defines.OPACITYRGB = true;
  26489. }
  26490. }
  26491. }
  26492. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26493. if (!this.reflectionTexture.isReady()) {
  26494. return false;
  26495. }
  26496. else {
  26497. needNormals = true;
  26498. this._defines.REFLECTION = true;
  26499. if (this.roughness > 0) {
  26500. this._defines.ROUGHNESS = true;
  26501. }
  26502. if (this.useReflectionOverAlpha) {
  26503. this._defines.REFLECTIONOVERALPHA = true;
  26504. }
  26505. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26506. this._defines.INVERTCUBICMAP = true;
  26507. }
  26508. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26509. switch (this.reflectionTexture.coordinatesMode) {
  26510. case BABYLON.Texture.CUBIC_MODE:
  26511. case BABYLON.Texture.INVCUBIC_MODE:
  26512. this._defines.REFLECTIONMAP_CUBIC = true;
  26513. break;
  26514. case BABYLON.Texture.EXPLICIT_MODE:
  26515. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26516. break;
  26517. case BABYLON.Texture.PLANAR_MODE:
  26518. this._defines.REFLECTIONMAP_PLANAR = true;
  26519. break;
  26520. case BABYLON.Texture.PROJECTION_MODE:
  26521. this._defines.REFLECTIONMAP_PROJECTION = true;
  26522. break;
  26523. case BABYLON.Texture.SKYBOX_MODE:
  26524. this._defines.REFLECTIONMAP_SKYBOX = true;
  26525. break;
  26526. case BABYLON.Texture.SPHERICAL_MODE:
  26527. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26528. break;
  26529. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26530. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26531. break;
  26532. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26533. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26534. break;
  26535. }
  26536. }
  26537. }
  26538. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26539. if (!this.emissiveTexture.isReady()) {
  26540. return false;
  26541. }
  26542. else {
  26543. needUVs = true;
  26544. this._defines.EMISSIVE = true;
  26545. }
  26546. }
  26547. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26548. if (!this.lightmapTexture.isReady()) {
  26549. return false;
  26550. }
  26551. else {
  26552. needUVs = true;
  26553. this._defines.LIGHTMAP = true;
  26554. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26555. }
  26556. }
  26557. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26558. if (!this.specularTexture.isReady()) {
  26559. return false;
  26560. }
  26561. else {
  26562. needUVs = true;
  26563. this._defines.SPECULAR = true;
  26564. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26565. }
  26566. }
  26567. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26568. if (!this.bumpTexture.isReady()) {
  26569. return false;
  26570. }
  26571. else {
  26572. needUVs = true;
  26573. this._defines.BUMP = true;
  26574. if (this.useParallax) {
  26575. this._defines.PARALLAX = true;
  26576. if (this.useParallaxOcclusion) {
  26577. this._defines.PARALLAXOCCLUSION = true;
  26578. }
  26579. }
  26580. if (this.invertNormalMapX) {
  26581. this._defines.INVERTNORMALMAPX = true;
  26582. }
  26583. if (this.invertNormalMapY) {
  26584. this._defines.INVERTNORMALMAPY = true;
  26585. }
  26586. }
  26587. }
  26588. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26589. if (!this.refractionTexture.isReady()) {
  26590. return false;
  26591. }
  26592. else {
  26593. needUVs = true;
  26594. this._defines.REFRACTION = true;
  26595. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26596. }
  26597. }
  26598. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26599. if (!this.cameraColorGradingTexture.isReady()) {
  26600. return false;
  26601. }
  26602. else {
  26603. this._defines.CAMERACOLORGRADING = true;
  26604. }
  26605. }
  26606. }
  26607. // Effect
  26608. if (scene.clipPlane) {
  26609. this._defines.CLIPPLANE = true;
  26610. }
  26611. if (engine.getAlphaTesting()) {
  26612. this._defines.ALPHATEST = true;
  26613. }
  26614. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26615. this._defines.ALPHAFROMDIFFUSE = true;
  26616. }
  26617. if (this.useEmissiveAsIllumination) {
  26618. this._defines.EMISSIVEASILLUMINATION = true;
  26619. }
  26620. if (this.linkEmissiveWithDiffuse) {
  26621. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26622. }
  26623. if (this.useLogarithmicDepth) {
  26624. this._defines.LOGARITHMICDEPTH = true;
  26625. }
  26626. if (this.cameraColorCurves) {
  26627. this._defines.CAMERACOLORCURVES = true;
  26628. }
  26629. // Point size
  26630. if (this.pointsCloud || scene.forcePointsCloud) {
  26631. this._defines.POINTSIZE = true;
  26632. }
  26633. // Fog
  26634. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26635. this._defines.FOG = true;
  26636. }
  26637. if (StandardMaterial.FresnelEnabled) {
  26638. // Fresnel
  26639. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26640. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26641. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26642. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26643. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26644. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26645. this._defines.DIFFUSEFRESNEL = true;
  26646. }
  26647. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26648. this._defines.OPACITYFRESNEL = true;
  26649. }
  26650. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26651. this._defines.REFLECTIONFRESNEL = true;
  26652. if (this.useReflectionFresnelFromSpecular) {
  26653. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26654. }
  26655. }
  26656. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26657. this._defines.REFRACTIONFRESNEL = true;
  26658. }
  26659. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26660. this._defines.EMISSIVEFRESNEL = true;
  26661. }
  26662. needNormals = true;
  26663. this._defines.FRESNEL = true;
  26664. }
  26665. }
  26666. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26667. this._defines.SPECULAROVERALPHA = true;
  26668. }
  26669. // Attribs
  26670. if (mesh) {
  26671. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26672. this._defines.NORMAL = true;
  26673. }
  26674. if (needUVs) {
  26675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26676. this._defines.UV1 = true;
  26677. }
  26678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26679. this._defines.UV2 = true;
  26680. }
  26681. }
  26682. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26683. this._defines.VERTEXCOLOR = true;
  26684. if (mesh.hasVertexAlpha) {
  26685. this._defines.VERTEXALPHA = true;
  26686. }
  26687. }
  26688. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26689. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26690. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26691. }
  26692. // Instances
  26693. if (useInstances) {
  26694. this._defines.INSTANCES = true;
  26695. }
  26696. }
  26697. // Get correct effect
  26698. if (!this._defines.isEqual(this._cachedDefines)) {
  26699. this._defines.cloneTo(this._cachedDefines);
  26700. scene.resetCachedMaterial();
  26701. // Fallbacks
  26702. var fallbacks = new BABYLON.EffectFallbacks();
  26703. if (this._defines.REFLECTION) {
  26704. fallbacks.addFallback(0, "REFLECTION");
  26705. }
  26706. if (this._defines.SPECULAR) {
  26707. fallbacks.addFallback(0, "SPECULAR");
  26708. }
  26709. if (this._defines.BUMP) {
  26710. fallbacks.addFallback(0, "BUMP");
  26711. }
  26712. if (this._defines.PARALLAX) {
  26713. fallbacks.addFallback(1, "PARALLAX");
  26714. }
  26715. if (this._defines.PARALLAXOCCLUSION) {
  26716. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26717. }
  26718. if (this._defines.SPECULAROVERALPHA) {
  26719. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26720. }
  26721. if (this._defines.FOG) {
  26722. fallbacks.addFallback(1, "FOG");
  26723. }
  26724. if (this._defines.POINTSIZE) {
  26725. fallbacks.addFallback(0, "POINTSIZE");
  26726. }
  26727. if (this._defines.LOGARITHMICDEPTH) {
  26728. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26729. }
  26730. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26731. if (this._defines.SPECULARTERM) {
  26732. fallbacks.addFallback(0, "SPECULARTERM");
  26733. }
  26734. if (this._defines.DIFFUSEFRESNEL) {
  26735. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26736. }
  26737. if (this._defines.OPACITYFRESNEL) {
  26738. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26739. }
  26740. if (this._defines.REFLECTIONFRESNEL) {
  26741. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26742. }
  26743. if (this._defines.EMISSIVEFRESNEL) {
  26744. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26745. }
  26746. if (this._defines.FRESNEL) {
  26747. fallbacks.addFallback(4, "FRESNEL");
  26748. }
  26749. //Attributes
  26750. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26751. if (this._defines.NORMAL) {
  26752. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26753. }
  26754. if (this._defines.UV1) {
  26755. attribs.push(BABYLON.VertexBuffer.UVKind);
  26756. }
  26757. if (this._defines.UV2) {
  26758. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26759. }
  26760. if (this._defines.VERTEXCOLOR) {
  26761. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26762. }
  26763. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26764. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26765. var shaderName = "default";
  26766. var join = this._defines.toString();
  26767. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26768. "vFogInfos", "vFogColor", "pointSize",
  26769. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26770. "mBones",
  26771. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26772. "depthValues",
  26773. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26774. "logarithmicDepthConstant"
  26775. ];
  26776. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26777. if (this._defines.CAMERACOLORCURVES) {
  26778. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26779. }
  26780. if (this._defines.CAMERACOLORGRADING) {
  26781. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26782. }
  26783. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26784. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26785. }
  26786. if (!this._effect.isReady()) {
  26787. return false;
  26788. }
  26789. this._renderId = scene.getRenderId();
  26790. this._wasPreviouslyReady = true;
  26791. if (mesh) {
  26792. if (!mesh._materialDefines) {
  26793. mesh._materialDefines = new StandardMaterialDefines();
  26794. }
  26795. this._defines.cloneTo(mesh._materialDefines);
  26796. }
  26797. return true;
  26798. };
  26799. StandardMaterial.prototype.unbind = function () {
  26800. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26801. this._effect.setTexture("reflection2DSampler", null);
  26802. }
  26803. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26804. this._effect.setTexture("refraction2DSampler", null);
  26805. }
  26806. _super.prototype.unbind.call(this);
  26807. };
  26808. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26809. this._effect.setMatrix("world", world);
  26810. };
  26811. StandardMaterial.prototype.bind = function (world, mesh) {
  26812. var scene = this.getScene();
  26813. // Matrices
  26814. this.bindOnlyWorldMatrix(world);
  26815. // Bones
  26816. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26817. if (scene.getCachedMaterial() !== this) {
  26818. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26819. if (StandardMaterial.FresnelEnabled) {
  26820. // Fresnel
  26821. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26822. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26823. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26824. }
  26825. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26826. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26827. }
  26828. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26829. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26830. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26831. }
  26832. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26833. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26834. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26835. }
  26836. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26837. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26838. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26839. }
  26840. }
  26841. // Textures
  26842. if (scene.texturesEnabled) {
  26843. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26844. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26845. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26846. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26847. }
  26848. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26849. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26850. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26851. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26852. }
  26853. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26854. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26855. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26856. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26857. }
  26858. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26859. if (this.reflectionTexture.isCube) {
  26860. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26861. }
  26862. else {
  26863. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26864. }
  26865. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26866. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26867. }
  26868. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26869. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26870. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26871. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26872. }
  26873. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26874. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26875. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26876. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26877. }
  26878. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26879. this._effect.setTexture("specularSampler", this.specularTexture);
  26880. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26881. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26882. }
  26883. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26884. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26885. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26886. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26887. }
  26888. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26889. var depth = 1.0;
  26890. if (this.refractionTexture.isCube) {
  26891. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26892. }
  26893. else {
  26894. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26895. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26896. if (this.refractionTexture.depth) {
  26897. depth = this.refractionTexture.depth;
  26898. }
  26899. }
  26900. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26901. }
  26902. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26903. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26904. }
  26905. }
  26906. // Clip plane
  26907. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26908. // Point size
  26909. if (this.pointsCloud) {
  26910. this._effect.setFloat("pointSize", this.pointSize);
  26911. }
  26912. // Colors
  26913. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26914. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26915. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26916. if (this._defines.SPECULARTERM) {
  26917. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26918. }
  26919. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26920. }
  26921. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26922. // Diffuse
  26923. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26924. // Lights
  26925. if (scene.lightsEnabled && !this.disableLighting) {
  26926. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26927. }
  26928. // View
  26929. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26930. this._effect.setMatrix("view", scene.getViewMatrix());
  26931. }
  26932. // Fog
  26933. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26934. // Log. depth
  26935. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26936. // Color Curves
  26937. if (this.cameraColorCurves) {
  26938. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26939. }
  26940. }
  26941. _super.prototype.bind.call(this, world, mesh);
  26942. };
  26943. StandardMaterial.prototype.getAnimatables = function () {
  26944. var results = [];
  26945. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26946. results.push(this.diffuseTexture);
  26947. }
  26948. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26949. results.push(this.ambientTexture);
  26950. }
  26951. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26952. results.push(this.opacityTexture);
  26953. }
  26954. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26955. results.push(this.reflectionTexture);
  26956. }
  26957. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26958. results.push(this.emissiveTexture);
  26959. }
  26960. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26961. results.push(this.specularTexture);
  26962. }
  26963. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26964. results.push(this.bumpTexture);
  26965. }
  26966. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26967. results.push(this.lightmapTexture);
  26968. }
  26969. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26970. results.push(this.refractionTexture);
  26971. }
  26972. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26973. results.push(this.cameraColorGradingTexture);
  26974. }
  26975. return results;
  26976. };
  26977. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26978. if (forceDisposeTextures) {
  26979. if (this.diffuseTexture) {
  26980. this.diffuseTexture.dispose();
  26981. }
  26982. if (this.ambientTexture) {
  26983. this.ambientTexture.dispose();
  26984. }
  26985. if (this.opacityTexture) {
  26986. this.opacityTexture.dispose();
  26987. }
  26988. if (this.reflectionTexture) {
  26989. this.reflectionTexture.dispose();
  26990. }
  26991. if (this.emissiveTexture) {
  26992. this.emissiveTexture.dispose();
  26993. }
  26994. if (this.specularTexture) {
  26995. this.specularTexture.dispose();
  26996. }
  26997. if (this.bumpTexture) {
  26998. this.bumpTexture.dispose();
  26999. }
  27000. if (this.lightmapTexture) {
  27001. this.lightmapTexture.dispose();
  27002. }
  27003. if (this.refractionTexture) {
  27004. this.refractionTexture.dispose();
  27005. }
  27006. if (this.cameraColorGradingTexture) {
  27007. this.cameraColorGradingTexture.dispose();
  27008. }
  27009. }
  27010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27011. };
  27012. StandardMaterial.prototype.clone = function (name) {
  27013. var _this = this;
  27014. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27015. };
  27016. StandardMaterial.prototype.serialize = function () {
  27017. return BABYLON.SerializationHelper.Serialize(this);
  27018. };
  27019. // Statics
  27020. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27021. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27022. };
  27023. // Flags used to enable or disable a type of texture for all Standard Materials
  27024. StandardMaterial.DiffuseTextureEnabled = true;
  27025. StandardMaterial.AmbientTextureEnabled = true;
  27026. StandardMaterial.OpacityTextureEnabled = true;
  27027. StandardMaterial.ReflectionTextureEnabled = true;
  27028. StandardMaterial.EmissiveTextureEnabled = true;
  27029. StandardMaterial.SpecularTextureEnabled = true;
  27030. StandardMaterial.BumpTextureEnabled = true;
  27031. StandardMaterial.FresnelEnabled = true;
  27032. StandardMaterial.LightmapTextureEnabled = true;
  27033. StandardMaterial.RefractionTextureEnabled = true;
  27034. StandardMaterial.ColorGradingTextureEnabled = true;
  27035. __decorate([
  27036. BABYLON.serializeAsTexture()
  27037. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27038. __decorate([
  27039. BABYLON.serializeAsTexture()
  27040. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27041. __decorate([
  27042. BABYLON.serializeAsTexture()
  27043. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27044. __decorate([
  27045. BABYLON.serializeAsTexture()
  27046. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27047. __decorate([
  27048. BABYLON.serializeAsTexture()
  27049. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27050. __decorate([
  27051. BABYLON.serializeAsTexture()
  27052. ], StandardMaterial.prototype, "specularTexture", void 0);
  27053. __decorate([
  27054. BABYLON.serializeAsTexture()
  27055. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27056. __decorate([
  27057. BABYLON.serializeAsTexture()
  27058. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27059. __decorate([
  27060. BABYLON.serializeAsTexture()
  27061. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27062. __decorate([
  27063. BABYLON.serializeAsColor3("ambient")
  27064. ], StandardMaterial.prototype, "ambientColor", void 0);
  27065. __decorate([
  27066. BABYLON.serializeAsColor3("diffuse")
  27067. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27068. __decorate([
  27069. BABYLON.serializeAsColor3("specular")
  27070. ], StandardMaterial.prototype, "specularColor", void 0);
  27071. __decorate([
  27072. BABYLON.serializeAsColor3("emissive")
  27073. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27074. __decorate([
  27075. BABYLON.serialize()
  27076. ], StandardMaterial.prototype, "specularPower", void 0);
  27077. __decorate([
  27078. BABYLON.serialize()
  27079. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27080. __decorate([
  27081. BABYLON.serialize()
  27082. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27083. __decorate([
  27084. BABYLON.serialize()
  27085. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27086. __decorate([
  27087. BABYLON.serialize()
  27088. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27089. __decorate([
  27090. BABYLON.serialize()
  27091. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27092. __decorate([
  27093. BABYLON.serialize()
  27094. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27095. __decorate([
  27096. BABYLON.serialize()
  27097. ], StandardMaterial.prototype, "disableLighting", void 0);
  27098. __decorate([
  27099. BABYLON.serialize()
  27100. ], StandardMaterial.prototype, "useParallax", void 0);
  27101. __decorate([
  27102. BABYLON.serialize()
  27103. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27104. __decorate([
  27105. BABYLON.serialize()
  27106. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27107. __decorate([
  27108. BABYLON.serialize()
  27109. ], StandardMaterial.prototype, "roughness", void 0);
  27110. __decorate([
  27111. BABYLON.serialize()
  27112. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27113. __decorate([
  27114. BABYLON.serialize()
  27115. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27116. __decorate([
  27117. BABYLON.serialize()
  27118. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27119. __decorate([
  27120. BABYLON.serializeAsFresnelParameters()
  27121. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27122. __decorate([
  27123. BABYLON.serializeAsFresnelParameters()
  27124. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27125. __decorate([
  27126. BABYLON.serializeAsFresnelParameters()
  27127. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27128. __decorate([
  27129. BABYLON.serializeAsFresnelParameters()
  27130. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27131. __decorate([
  27132. BABYLON.serializeAsFresnelParameters()
  27133. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27134. __decorate([
  27135. BABYLON.serialize()
  27136. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27137. __decorate([
  27138. BABYLON.serialize()
  27139. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27140. __decorate([
  27141. BABYLON.serialize()
  27142. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27143. __decorate([
  27144. BABYLON.serialize()
  27145. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27146. __decorate([
  27147. BABYLON.serializeAsTexture()
  27148. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27149. __decorate([
  27150. BABYLON.serializeAsColorCurves()
  27151. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27152. __decorate([
  27153. BABYLON.serialize()
  27154. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27155. return StandardMaterial;
  27156. }(BABYLON.Material));
  27157. BABYLON.StandardMaterial = StandardMaterial;
  27158. })(BABYLON || (BABYLON = {}));
  27159. //# sourceMappingURL=babylon.standardMaterial.js.map
  27160. var BABYLON;
  27161. (function (BABYLON) {
  27162. var MultiMaterial = (function (_super) {
  27163. __extends(MultiMaterial, _super);
  27164. function MultiMaterial(name, scene) {
  27165. _super.call(this, name, scene, true);
  27166. this.subMaterials = new Array();
  27167. scene.multiMaterials.push(this);
  27168. }
  27169. // Properties
  27170. MultiMaterial.prototype.getSubMaterial = function (index) {
  27171. if (index < 0 || index >= this.subMaterials.length) {
  27172. return this.getScene().defaultMaterial;
  27173. }
  27174. return this.subMaterials[index];
  27175. };
  27176. // Methods
  27177. MultiMaterial.prototype.getClassName = function () {
  27178. return "MultiMaterial";
  27179. };
  27180. MultiMaterial.prototype.isReady = function (mesh) {
  27181. for (var index = 0; index < this.subMaterials.length; index++) {
  27182. var subMaterial = this.subMaterials[index];
  27183. if (subMaterial) {
  27184. if (!this.subMaterials[index].isReady(mesh)) {
  27185. return false;
  27186. }
  27187. }
  27188. }
  27189. return true;
  27190. };
  27191. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27192. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27193. for (var index = 0; index < this.subMaterials.length; index++) {
  27194. var subMaterial = null;
  27195. if (cloneChildren) {
  27196. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27197. }
  27198. else {
  27199. subMaterial = this.subMaterials[index];
  27200. }
  27201. newMultiMaterial.subMaterials.push(subMaterial);
  27202. }
  27203. return newMultiMaterial;
  27204. };
  27205. MultiMaterial.prototype.serialize = function () {
  27206. var serializationObject = {};
  27207. serializationObject.name = this.name;
  27208. serializationObject.id = this.id;
  27209. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27210. serializationObject.materials = [];
  27211. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27212. var subMat = this.subMaterials[matIndex];
  27213. if (subMat) {
  27214. serializationObject.materials.push(subMat.id);
  27215. }
  27216. else {
  27217. serializationObject.materials.push(null);
  27218. }
  27219. }
  27220. return serializationObject;
  27221. };
  27222. return MultiMaterial;
  27223. }(BABYLON.Material));
  27224. BABYLON.MultiMaterial = MultiMaterial;
  27225. })(BABYLON || (BABYLON = {}));
  27226. //# sourceMappingURL=babylon.multiMaterial.js.map
  27227. var BABYLON;
  27228. (function (BABYLON) {
  27229. var SceneLoader = (function () {
  27230. function SceneLoader() {
  27231. }
  27232. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27233. get: function () {
  27234. return 0;
  27235. },
  27236. enumerable: true,
  27237. configurable: true
  27238. });
  27239. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27240. get: function () {
  27241. return 1;
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27247. get: function () {
  27248. return 2;
  27249. },
  27250. enumerable: true,
  27251. configurable: true
  27252. });
  27253. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27254. get: function () {
  27255. return 3;
  27256. },
  27257. enumerable: true,
  27258. configurable: true
  27259. });
  27260. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27261. get: function () {
  27262. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27263. },
  27264. set: function (value) {
  27265. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27266. },
  27267. enumerable: true,
  27268. configurable: true
  27269. });
  27270. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27271. get: function () {
  27272. return SceneLoader._ShowLoadingScreen;
  27273. },
  27274. set: function (value) {
  27275. SceneLoader._ShowLoadingScreen = value;
  27276. },
  27277. enumerable: true,
  27278. configurable: true
  27279. });
  27280. Object.defineProperty(SceneLoader, "loggingLevel", {
  27281. get: function () {
  27282. return SceneLoader._loggingLevel;
  27283. },
  27284. set: function (value) {
  27285. SceneLoader._loggingLevel = value;
  27286. },
  27287. enumerable: true,
  27288. configurable: true
  27289. });
  27290. SceneLoader._getDefaultPlugin = function () {
  27291. return SceneLoader._registeredPlugins[".babylon"];
  27292. };
  27293. SceneLoader._getPluginForExtension = function (extension) {
  27294. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27295. if (registeredPlugin) {
  27296. return registeredPlugin;
  27297. }
  27298. return SceneLoader._getDefaultPlugin();
  27299. };
  27300. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27301. if (sceneFilename.name) {
  27302. sceneFilename = sceneFilename.name;
  27303. }
  27304. var dotPosition = sceneFilename.lastIndexOf(".");
  27305. var queryStringPosition = sceneFilename.indexOf("?");
  27306. if (queryStringPosition === -1) {
  27307. queryStringPosition = sceneFilename.length;
  27308. }
  27309. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27310. return SceneLoader._getPluginForExtension(extension);
  27311. };
  27312. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27313. SceneLoader._getDirectLoad = function (sceneFilename) {
  27314. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27315. return sceneFilename.substr(5);
  27316. }
  27317. return null;
  27318. };
  27319. // Public functions
  27320. SceneLoader.GetPluginForExtension = function (extension) {
  27321. return SceneLoader._getPluginForExtension(extension).plugin;
  27322. };
  27323. SceneLoader.RegisterPlugin = function (plugin) {
  27324. if (typeof plugin.extensions === "string") {
  27325. var extension = plugin.extensions;
  27326. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27327. plugin: plugin,
  27328. isBinary: false
  27329. };
  27330. }
  27331. else {
  27332. var extensions = plugin.extensions;
  27333. Object.keys(extensions).forEach(function (extension) {
  27334. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27335. plugin: plugin,
  27336. isBinary: extensions[extension].isBinary
  27337. };
  27338. });
  27339. }
  27340. };
  27341. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27342. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27343. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27344. return;
  27345. }
  27346. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27347. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27348. return;
  27349. }
  27350. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27351. var loadingToken = {};
  27352. scene._addPendingData(loadingToken);
  27353. var manifestChecked = function (success) {
  27354. scene.database = database;
  27355. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27356. var plugin = registeredPlugin.plugin;
  27357. var useArrayBuffer = registeredPlugin.isBinary;
  27358. var importMeshFromData = function (data) {
  27359. var meshes = [];
  27360. var particleSystems = [];
  27361. var skeletons = [];
  27362. try {
  27363. if (plugin.importMesh) {
  27364. var syncedPlugin = plugin;
  27365. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27366. if (onerror) {
  27367. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27368. }
  27369. scene._removePendingData(loadingToken);
  27370. return;
  27371. }
  27372. if (onsuccess) {
  27373. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27374. onsuccess(meshes, particleSystems, skeletons);
  27375. scene._removePendingData(loadingToken);
  27376. }
  27377. }
  27378. else {
  27379. var asyncedPlugin = plugin;
  27380. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27381. if (onsuccess) {
  27382. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27383. onsuccess(meshes, particleSystems, skeletons);
  27384. scene._removePendingData(loadingToken);
  27385. }
  27386. }, function () {
  27387. if (onerror) {
  27388. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27389. }
  27390. scene._removePendingData(loadingToken);
  27391. });
  27392. }
  27393. }
  27394. catch (e) {
  27395. if (onerror) {
  27396. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27397. }
  27398. scene._removePendingData(loadingToken);
  27399. }
  27400. };
  27401. if (directLoad) {
  27402. importMeshFromData(directLoad);
  27403. return;
  27404. }
  27405. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27406. importMeshFromData(data);
  27407. }, progressCallBack, database, useArrayBuffer);
  27408. };
  27409. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27410. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27411. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27412. }
  27413. else {
  27414. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27415. manifestChecked(true);
  27416. }
  27417. };
  27418. /**
  27419. * Load a scene
  27420. * @param rootUrl a string that defines the root url for scene and resources
  27421. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27422. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27423. */
  27424. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27425. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27426. };
  27427. /**
  27428. * Append a scene
  27429. * @param rootUrl a string that defines the root url for scene and resources
  27430. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27431. * @param scene is the instance of BABYLON.Scene to append to
  27432. */
  27433. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27434. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27435. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27436. return;
  27437. }
  27438. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27439. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27440. var plugin = registeredPlugin.plugin;
  27441. var useArrayBuffer = registeredPlugin.isBinary;
  27442. var database;
  27443. var loadingToken = {};
  27444. scene._addPendingData(loadingToken);
  27445. if (SceneLoader.ShowLoadingScreen) {
  27446. scene.getEngine().displayLoadingUI();
  27447. }
  27448. var loadSceneFromData = function (data) {
  27449. scene.database = database;
  27450. if (plugin.load) {
  27451. var syncedPlugin = plugin;
  27452. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27453. if (onerror) {
  27454. onerror(scene);
  27455. }
  27456. scene._removePendingData(loadingToken);
  27457. scene.getEngine().hideLoadingUI();
  27458. return;
  27459. }
  27460. if (onsuccess) {
  27461. onsuccess(scene);
  27462. }
  27463. scene._removePendingData(loadingToken);
  27464. }
  27465. else {
  27466. var asyncedPlugin = plugin;
  27467. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27468. if (onsuccess) {
  27469. onsuccess(scene);
  27470. }
  27471. scene._removePendingData(loadingToken);
  27472. }, function () {
  27473. if (onerror) {
  27474. onerror(scene);
  27475. }
  27476. scene._removePendingData(loadingToken);
  27477. scene.getEngine().hideLoadingUI();
  27478. });
  27479. }
  27480. if (SceneLoader.ShowLoadingScreen) {
  27481. scene.executeWhenReady(function () {
  27482. scene.getEngine().hideLoadingUI();
  27483. });
  27484. }
  27485. };
  27486. var manifestChecked = function (success) {
  27487. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27488. };
  27489. if (directLoad) {
  27490. loadSceneFromData(directLoad);
  27491. return;
  27492. }
  27493. if (rootUrl.indexOf("file:") === -1) {
  27494. if (scene.getEngine().enableOfflineSupport) {
  27495. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27496. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27497. }
  27498. else {
  27499. manifestChecked(true);
  27500. }
  27501. }
  27502. else {
  27503. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27504. }
  27505. };
  27506. // Flags
  27507. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27508. SceneLoader._ShowLoadingScreen = true;
  27509. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27510. // Members
  27511. SceneLoader._registeredPlugins = {};
  27512. return SceneLoader;
  27513. }());
  27514. BABYLON.SceneLoader = SceneLoader;
  27515. ;
  27516. })(BABYLON || (BABYLON = {}));
  27517. //# sourceMappingURL=babylon.sceneLoader.js.map
  27518. var BABYLON;
  27519. (function (BABYLON) {
  27520. var Internals;
  27521. (function (Internals) {
  27522. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27523. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27524. var parsedMaterial = parsedData.materials[index];
  27525. if (parsedMaterial.id === id) {
  27526. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27527. }
  27528. }
  27529. return null;
  27530. };
  27531. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27532. names = (names instanceof Array) ? names : [names];
  27533. for (var i in names) {
  27534. if (mesh.name === names[i]) {
  27535. hierarchyIds.push(mesh.id);
  27536. return true;
  27537. }
  27538. }
  27539. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27540. hierarchyIds.push(mesh.id);
  27541. return true;
  27542. }
  27543. return false;
  27544. };
  27545. var logOperation = function (operation, producer) {
  27546. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27547. };
  27548. BABYLON.SceneLoader.RegisterPlugin({
  27549. extensions: ".babylon",
  27550. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27551. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27552. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27553. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27554. // and avoid problems with multiple concurrent .babylon loads.
  27555. var log = "importMesh has failed JSON parse";
  27556. try {
  27557. var parsedData = JSON.parse(data);
  27558. log = "";
  27559. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27560. var loadedSkeletonsIds = [];
  27561. var loadedMaterialsIds = [];
  27562. var hierarchyIds = [];
  27563. var index;
  27564. var cache;
  27565. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27566. var parsedMesh = parsedData.meshes[index];
  27567. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27568. if (meshesNames instanceof Array) {
  27569. // Remove found mesh name from list.
  27570. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27571. }
  27572. //Geometry?
  27573. if (parsedMesh.geometryId) {
  27574. //does the file contain geometries?
  27575. if (parsedData.geometries) {
  27576. //find the correct geometry and add it to the scene
  27577. var found = false;
  27578. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27579. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27580. return;
  27581. }
  27582. else {
  27583. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27584. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27585. switch (geometryType) {
  27586. case "boxes":
  27587. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27588. break;
  27589. case "spheres":
  27590. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27591. break;
  27592. case "cylinders":
  27593. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27594. break;
  27595. case "toruses":
  27596. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27597. break;
  27598. case "grounds":
  27599. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27600. break;
  27601. case "planes":
  27602. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27603. break;
  27604. case "torusKnots":
  27605. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27606. break;
  27607. case "vertexData":
  27608. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27609. break;
  27610. }
  27611. found = true;
  27612. }
  27613. });
  27614. }
  27615. });
  27616. if (!found) {
  27617. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27618. }
  27619. }
  27620. }
  27621. // Material ?
  27622. if (parsedMesh.materialId) {
  27623. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27624. if (!materialFound && parsedData.multiMaterials) {
  27625. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27626. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27627. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27628. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27629. var subMatId = parsedMultiMaterial.materials[matIndex];
  27630. loadedMaterialsIds.push(subMatId);
  27631. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27632. log += "\n\tMaterial " + mat.toString(fullDetails);
  27633. }
  27634. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27635. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27636. materialFound = true;
  27637. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27638. break;
  27639. }
  27640. }
  27641. }
  27642. if (!materialFound) {
  27643. loadedMaterialsIds.push(parsedMesh.materialId);
  27644. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27645. if (!mat) {
  27646. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27647. }
  27648. else {
  27649. log += "\n\tMaterial " + mat.toString(fullDetails);
  27650. }
  27651. }
  27652. }
  27653. // Skeleton ?
  27654. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27655. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27656. if (!skeletonAlreadyLoaded) {
  27657. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27658. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27659. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27660. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27661. skeletons.push(skeleton);
  27662. loadedSkeletonsIds.push(parsedSkeleton.id);
  27663. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27664. }
  27665. }
  27666. }
  27667. }
  27668. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27669. meshes.push(mesh);
  27670. log += "\n\tMesh " + mesh.toString(fullDetails);
  27671. }
  27672. }
  27673. // Connecting parents
  27674. var currentMesh;
  27675. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27676. currentMesh = scene.meshes[index];
  27677. if (currentMesh._waitingParentId) {
  27678. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27679. currentMesh._waitingParentId = undefined;
  27680. }
  27681. }
  27682. // freeze and compute world matrix application
  27683. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27684. currentMesh = scene.meshes[index];
  27685. if (currentMesh._waitingFreezeWorldMatrix) {
  27686. currentMesh.freezeWorldMatrix();
  27687. currentMesh._waitingFreezeWorldMatrix = undefined;
  27688. }
  27689. else {
  27690. currentMesh.computeWorldMatrix(true);
  27691. }
  27692. }
  27693. // Particles
  27694. if (parsedData.particleSystems) {
  27695. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27696. var parsedParticleSystem = parsedData.particleSystems[index];
  27697. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27698. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27699. }
  27700. }
  27701. }
  27702. return true;
  27703. }
  27704. catch (err) {
  27705. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27706. log = null;
  27707. throw err;
  27708. }
  27709. finally {
  27710. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27711. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27712. }
  27713. }
  27714. },
  27715. load: function (scene, data, rootUrl) {
  27716. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27717. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27718. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27719. // and avoid problems with multiple concurrent .babylon loads.
  27720. var log = "importScene has failed JSON parse";
  27721. try {
  27722. var parsedData = JSON.parse(data);
  27723. log = "";
  27724. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27725. // Scene
  27726. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27727. scene.autoClear = parsedData.autoClear;
  27728. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27729. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27730. if (parsedData.gravity) {
  27731. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27732. }
  27733. // Fog
  27734. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27735. scene.fogMode = parsedData.fogMode;
  27736. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27737. scene.fogStart = parsedData.fogStart;
  27738. scene.fogEnd = parsedData.fogEnd;
  27739. scene.fogDensity = parsedData.fogDensity;
  27740. log += "\tFog mode for scene: ";
  27741. switch (scene.fogMode) {
  27742. // getters not compiling, so using hardcoded
  27743. case 1:
  27744. log += "exp\n";
  27745. break;
  27746. case 2:
  27747. log += "exp2\n";
  27748. break;
  27749. case 3:
  27750. log += "linear\n";
  27751. break;
  27752. }
  27753. }
  27754. //Physics
  27755. if (parsedData.physicsEnabled) {
  27756. var physicsPlugin;
  27757. if (parsedData.physicsEngine === "cannon") {
  27758. physicsPlugin = new BABYLON.CannonJSPlugin();
  27759. }
  27760. else if (parsedData.physicsEngine === "oimo") {
  27761. physicsPlugin = new BABYLON.OimoJSPlugin();
  27762. }
  27763. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27764. //else - default engine, which is currently oimo
  27765. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27766. scene.enablePhysics(physicsGravity, physicsPlugin);
  27767. }
  27768. // Metadata
  27769. if (parsedData.metadata !== undefined) {
  27770. scene.metadata = parsedData.metadata;
  27771. }
  27772. //collisions, if defined. otherwise, default is true
  27773. if (parsedData.collisionsEnabled != undefined) {
  27774. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27775. }
  27776. scene.workerCollisions = !!parsedData.workerCollisions;
  27777. var index;
  27778. var cache;
  27779. // Lights
  27780. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27781. var parsedLight = parsedData.lights[index];
  27782. var light = BABYLON.Light.Parse(parsedLight, scene);
  27783. log += (index === 0 ? "\n\tLights:" : "");
  27784. log += "\n\t\t" + light.toString(fullDetails);
  27785. }
  27786. // Animations
  27787. if (parsedData.animations) {
  27788. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27789. var parsedAnimation = parsedData.animations[index];
  27790. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27791. scene.animations.push(animation);
  27792. log += (index === 0 ? "\n\tAnimations:" : "");
  27793. log += "\n\t\t" + animation.toString(fullDetails);
  27794. }
  27795. }
  27796. if (parsedData.autoAnimate) {
  27797. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27798. }
  27799. // Materials
  27800. if (parsedData.materials) {
  27801. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27802. var parsedMaterial = parsedData.materials[index];
  27803. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27804. log += (index === 0 ? "\n\tMaterials:" : "");
  27805. log += "\n\t\t" + mat.toString(fullDetails);
  27806. }
  27807. }
  27808. if (parsedData.multiMaterials) {
  27809. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27810. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27811. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27812. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27813. log += "\n\t\t" + mmat.toString(fullDetails);
  27814. }
  27815. }
  27816. // Skeletons
  27817. if (parsedData.skeletons) {
  27818. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27819. var parsedSkeleton = parsedData.skeletons[index];
  27820. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27821. log += (index === 0 ? "\n\tSkeletons:" : "");
  27822. log += "\n\t\t" + skeleton.toString(fullDetails);
  27823. }
  27824. }
  27825. // Geometries
  27826. var geometries = parsedData.geometries;
  27827. if (geometries) {
  27828. // Boxes
  27829. var boxes = geometries.boxes;
  27830. if (boxes) {
  27831. for (index = 0, cache = boxes.length; index < cache; index++) {
  27832. var parsedBox = boxes[index];
  27833. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27834. }
  27835. }
  27836. // Spheres
  27837. var spheres = geometries.spheres;
  27838. if (spheres) {
  27839. for (index = 0, cache = spheres.length; index < cache; index++) {
  27840. var parsedSphere = spheres[index];
  27841. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27842. }
  27843. }
  27844. // Cylinders
  27845. var cylinders = geometries.cylinders;
  27846. if (cylinders) {
  27847. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27848. var parsedCylinder = cylinders[index];
  27849. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27850. }
  27851. }
  27852. // Toruses
  27853. var toruses = geometries.toruses;
  27854. if (toruses) {
  27855. for (index = 0, cache = toruses.length; index < cache; index++) {
  27856. var parsedTorus = toruses[index];
  27857. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27858. }
  27859. }
  27860. // Grounds
  27861. var grounds = geometries.grounds;
  27862. if (grounds) {
  27863. for (index = 0, cache = grounds.length; index < cache; index++) {
  27864. var parsedGround = grounds[index];
  27865. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27866. }
  27867. }
  27868. // Planes
  27869. var planes = geometries.planes;
  27870. if (planes) {
  27871. for (index = 0, cache = planes.length; index < cache; index++) {
  27872. var parsedPlane = planes[index];
  27873. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27874. }
  27875. }
  27876. // TorusKnots
  27877. var torusKnots = geometries.torusKnots;
  27878. if (torusKnots) {
  27879. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27880. var parsedTorusKnot = torusKnots[index];
  27881. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27882. }
  27883. }
  27884. // VertexData
  27885. var vertexData = geometries.vertexData;
  27886. if (vertexData) {
  27887. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27888. var parsedVertexData = vertexData[index];
  27889. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27890. }
  27891. }
  27892. }
  27893. // Meshes
  27894. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27895. var parsedMesh = parsedData.meshes[index];
  27896. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27897. log += (index === 0 ? "\n\tMeshes:" : "");
  27898. log += "\n\t\t" + mesh.toString(fullDetails);
  27899. }
  27900. // Cameras
  27901. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27902. var parsedCamera = parsedData.cameras[index];
  27903. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27904. log += (index === 0 ? "\n\tCameras:" : "");
  27905. log += "\n\t\t" + camera.toString(fullDetails);
  27906. }
  27907. if (parsedData.activeCameraID) {
  27908. scene.setActiveCameraByID(parsedData.activeCameraID);
  27909. }
  27910. // Browsing all the graph to connect the dots
  27911. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27912. var camera = scene.cameras[index];
  27913. if (camera._waitingParentId) {
  27914. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27915. camera._waitingParentId = undefined;
  27916. }
  27917. }
  27918. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27919. var light = scene.lights[index];
  27920. if (light._waitingParentId) {
  27921. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27922. light._waitingParentId = undefined;
  27923. }
  27924. }
  27925. // Sounds
  27926. var loadedSounds = [];
  27927. var loadedSound;
  27928. if (BABYLON.AudioEngine && parsedData.sounds) {
  27929. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27930. var parsedSound = parsedData.sounds[index];
  27931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27932. if (!parsedSound.url)
  27933. parsedSound.url = parsedSound.name;
  27934. if (!loadedSounds[parsedSound.url]) {
  27935. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27936. loadedSounds[parsedSound.url] = loadedSound;
  27937. }
  27938. else {
  27939. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27940. }
  27941. }
  27942. else {
  27943. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27944. }
  27945. }
  27946. }
  27947. loadedSounds = [];
  27948. // Connect parents & children and parse actions
  27949. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27950. var mesh = scene.meshes[index];
  27951. if (mesh._waitingParentId) {
  27952. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27953. mesh._waitingParentId = undefined;
  27954. }
  27955. if (mesh._waitingActions) {
  27956. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27957. mesh._waitingActions = undefined;
  27958. }
  27959. }
  27960. // freeze world matrix application
  27961. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27962. var currentMesh = scene.meshes[index];
  27963. if (currentMesh._waitingFreezeWorldMatrix) {
  27964. currentMesh.freezeWorldMatrix();
  27965. currentMesh._waitingFreezeWorldMatrix = undefined;
  27966. }
  27967. else {
  27968. currentMesh.computeWorldMatrix(true);
  27969. }
  27970. }
  27971. // Particles Systems
  27972. if (parsedData.particleSystems) {
  27973. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27974. var parsedParticleSystem = parsedData.particleSystems[index];
  27975. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27976. }
  27977. }
  27978. // Lens flares
  27979. if (parsedData.lensFlareSystems) {
  27980. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27981. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27982. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27983. }
  27984. }
  27985. // Shadows
  27986. if (parsedData.shadowGenerators) {
  27987. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27988. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27989. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27990. }
  27991. }
  27992. // Actions (scene)
  27993. if (parsedData.actions) {
  27994. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27995. }
  27996. // Finish
  27997. return true;
  27998. }
  27999. catch (err) {
  28000. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28001. log = null;
  28002. throw err;
  28003. }
  28004. finally {
  28005. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28006. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28007. }
  28008. }
  28009. }
  28010. });
  28011. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28012. })(BABYLON || (BABYLON = {}));
  28013. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28014. var BABYLON;
  28015. (function (BABYLON) {
  28016. var SpriteManager = (function () {
  28017. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28018. if (epsilon === void 0) { epsilon = 0.01; }
  28019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28020. this.name = name;
  28021. this.sprites = new Array();
  28022. this.renderingGroupId = 0;
  28023. this.layerMask = 0x0FFFFFFF;
  28024. this.fogEnabled = true;
  28025. this.isPickable = false;
  28026. /**
  28027. * An event triggered when the manager is disposed.
  28028. * @type {BABYLON.Observable}
  28029. */
  28030. this.onDisposeObservable = new BABYLON.Observable();
  28031. this._vertexBuffers = {};
  28032. this._capacity = capacity;
  28033. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28034. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28035. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28036. if (cellSize.width && cellSize.height) {
  28037. this.cellWidth = cellSize.width;
  28038. this.cellHeight = cellSize.height;
  28039. }
  28040. else if (cellSize !== undefined) {
  28041. this.cellWidth = cellSize;
  28042. this.cellHeight = cellSize;
  28043. }
  28044. else {
  28045. return;
  28046. }
  28047. this._epsilon = epsilon;
  28048. this._scene = scene;
  28049. this._scene.spriteManagers.push(this);
  28050. var indices = [];
  28051. var index = 0;
  28052. for (var count = 0; count < capacity; count++) {
  28053. indices.push(index);
  28054. indices.push(index + 1);
  28055. indices.push(index + 2);
  28056. indices.push(index);
  28057. indices.push(index + 2);
  28058. indices.push(index + 3);
  28059. index += 4;
  28060. }
  28061. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28062. // VBO
  28063. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28064. this._vertexData = new Float32Array(capacity * 16 * 4);
  28065. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28066. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28067. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28068. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28069. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28071. this._vertexBuffers["options"] = options;
  28072. this._vertexBuffers["cellInfo"] = cellInfo;
  28073. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28074. // Effects
  28075. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28076. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28077. }
  28078. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28079. set: function (callback) {
  28080. if (this._onDisposeObserver) {
  28081. this.onDisposeObservable.remove(this._onDisposeObserver);
  28082. }
  28083. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28084. },
  28085. enumerable: true,
  28086. configurable: true
  28087. });
  28088. Object.defineProperty(SpriteManager.prototype, "texture", {
  28089. get: function () {
  28090. return this._spriteTexture;
  28091. },
  28092. set: function (value) {
  28093. this._spriteTexture = value;
  28094. },
  28095. enumerable: true,
  28096. configurable: true
  28097. });
  28098. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28099. var arrayOffset = index * 16;
  28100. if (offsetX === 0)
  28101. offsetX = this._epsilon;
  28102. else if (offsetX === 1)
  28103. offsetX = 1 - this._epsilon;
  28104. if (offsetY === 0)
  28105. offsetY = this._epsilon;
  28106. else if (offsetY === 1)
  28107. offsetY = 1 - this._epsilon;
  28108. this._vertexData[arrayOffset] = sprite.position.x;
  28109. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28110. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28111. this._vertexData[arrayOffset + 3] = sprite.angle;
  28112. this._vertexData[arrayOffset + 4] = sprite.width;
  28113. this._vertexData[arrayOffset + 5] = sprite.height;
  28114. this._vertexData[arrayOffset + 6] = offsetX;
  28115. this._vertexData[arrayOffset + 7] = offsetY;
  28116. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28117. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28118. var offset = (sprite.cellIndex / rowSize) >> 0;
  28119. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28120. this._vertexData[arrayOffset + 11] = offset;
  28121. // Color
  28122. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28123. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28124. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28125. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28126. };
  28127. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28128. var count = Math.min(this._capacity, this.sprites.length);
  28129. var min = BABYLON.Vector3.Zero();
  28130. var max = BABYLON.Vector3.Zero();
  28131. var distance = Number.MAX_VALUE;
  28132. var currentSprite;
  28133. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28134. var cameraView = camera.getViewMatrix();
  28135. for (var index = 0; index < count; index++) {
  28136. var sprite = this.sprites[index];
  28137. if (!sprite) {
  28138. continue;
  28139. }
  28140. if (predicate) {
  28141. if (!predicate(sprite)) {
  28142. continue;
  28143. }
  28144. }
  28145. else if (!sprite.isPickable) {
  28146. continue;
  28147. }
  28148. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28149. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28150. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28151. if (ray.intersectsBoxMinMax(min, max)) {
  28152. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28153. if (distance > currentDistance) {
  28154. distance = currentDistance;
  28155. currentSprite = sprite;
  28156. if (fastCheck) {
  28157. break;
  28158. }
  28159. }
  28160. }
  28161. }
  28162. if (currentSprite) {
  28163. var result = new BABYLON.PickingInfo();
  28164. result.hit = true;
  28165. result.pickedSprite = currentSprite;
  28166. result.distance = distance;
  28167. return result;
  28168. }
  28169. return null;
  28170. };
  28171. SpriteManager.prototype.render = function () {
  28172. // Check
  28173. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28174. return;
  28175. var engine = this._scene.getEngine();
  28176. var baseSize = this._spriteTexture.getBaseSize();
  28177. // Sprites
  28178. var deltaTime = engine.getDeltaTime();
  28179. var max = Math.min(this._capacity, this.sprites.length);
  28180. var rowSize = baseSize.width / this.cellWidth;
  28181. var offset = 0;
  28182. for (var index = 0; index < max; index++) {
  28183. var sprite = this.sprites[index];
  28184. if (!sprite) {
  28185. continue;
  28186. }
  28187. sprite._animate(deltaTime);
  28188. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28189. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28190. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28191. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28192. }
  28193. this._buffer.update(this._vertexData);
  28194. // Render
  28195. var effect = this._effectBase;
  28196. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28197. effect = this._effectFog;
  28198. }
  28199. engine.enableEffect(effect);
  28200. var viewMatrix = this._scene.getViewMatrix();
  28201. effect.setTexture("diffuseSampler", this._spriteTexture);
  28202. effect.setMatrix("view", viewMatrix);
  28203. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28204. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28205. // Fog
  28206. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28207. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28208. effect.setColor3("vFogColor", this._scene.fogColor);
  28209. }
  28210. // VBOs
  28211. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28212. // Draw order
  28213. engine.setDepthFunctionToLessOrEqual();
  28214. effect.setBool("alphaTest", true);
  28215. engine.setColorWrite(false);
  28216. engine.draw(true, 0, max * 6);
  28217. engine.setColorWrite(true);
  28218. effect.setBool("alphaTest", false);
  28219. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28220. engine.draw(true, 0, max * 6);
  28221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28222. };
  28223. SpriteManager.prototype.dispose = function () {
  28224. if (this._buffer) {
  28225. this._buffer.dispose();
  28226. this._buffer = null;
  28227. }
  28228. if (this._indexBuffer) {
  28229. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28230. this._indexBuffer = null;
  28231. }
  28232. if (this._spriteTexture) {
  28233. this._spriteTexture.dispose();
  28234. this._spriteTexture = null;
  28235. }
  28236. // Remove from scene
  28237. var index = this._scene.spriteManagers.indexOf(this);
  28238. this._scene.spriteManagers.splice(index, 1);
  28239. // Callback
  28240. this.onDisposeObservable.notifyObservers(this);
  28241. this.onDisposeObservable.clear();
  28242. };
  28243. return SpriteManager;
  28244. }());
  28245. BABYLON.SpriteManager = SpriteManager;
  28246. })(BABYLON || (BABYLON = {}));
  28247. //# sourceMappingURL=babylon.spriteManager.js.map
  28248. var BABYLON;
  28249. (function (BABYLON) {
  28250. var Sprite = (function () {
  28251. function Sprite(name, manager) {
  28252. this.name = name;
  28253. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28254. this.width = 1.0;
  28255. this.height = 1.0;
  28256. this.angle = 0;
  28257. this.cellIndex = 0;
  28258. this.invertU = 0;
  28259. this.invertV = 0;
  28260. this.animations = new Array();
  28261. this.isPickable = false;
  28262. this._animationStarted = false;
  28263. this._loopAnimation = false;
  28264. this._fromIndex = 0;
  28265. this._toIndex = 0;
  28266. this._delay = 0;
  28267. this._direction = 1;
  28268. this._frameCount = 0;
  28269. this._time = 0;
  28270. this._manager = manager;
  28271. this._manager.sprites.push(this);
  28272. this.position = BABYLON.Vector3.Zero();
  28273. }
  28274. Object.defineProperty(Sprite.prototype, "size", {
  28275. get: function () {
  28276. return this.width;
  28277. },
  28278. set: function (value) {
  28279. this.width = value;
  28280. this.height = value;
  28281. },
  28282. enumerable: true,
  28283. configurable: true
  28284. });
  28285. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28286. this._fromIndex = from;
  28287. this._toIndex = to;
  28288. this._loopAnimation = loop;
  28289. this._delay = delay;
  28290. this._animationStarted = true;
  28291. this._direction = from < to ? 1 : -1;
  28292. this.cellIndex = from;
  28293. this._time = 0;
  28294. this._onAnimationEnd = onAnimationEnd;
  28295. };
  28296. Sprite.prototype.stopAnimation = function () {
  28297. this._animationStarted = false;
  28298. };
  28299. Sprite.prototype._animate = function (deltaTime) {
  28300. if (!this._animationStarted)
  28301. return;
  28302. this._time += deltaTime;
  28303. if (this._time > this._delay) {
  28304. this._time = this._time % this._delay;
  28305. this.cellIndex += this._direction;
  28306. if (this.cellIndex === this._toIndex) {
  28307. if (this._loopAnimation) {
  28308. this.cellIndex = this._fromIndex;
  28309. }
  28310. else {
  28311. this._animationStarted = false;
  28312. if (this._onAnimationEnd) {
  28313. this._onAnimationEnd();
  28314. }
  28315. if (this.disposeWhenFinishedAnimating) {
  28316. this.dispose();
  28317. }
  28318. }
  28319. }
  28320. }
  28321. };
  28322. Sprite.prototype.dispose = function () {
  28323. for (var i = 0; i < this._manager.sprites.length; i++) {
  28324. if (this._manager.sprites[i] == this) {
  28325. this._manager.sprites.splice(i, 1);
  28326. }
  28327. }
  28328. };
  28329. return Sprite;
  28330. }());
  28331. BABYLON.Sprite = Sprite;
  28332. })(BABYLON || (BABYLON = {}));
  28333. //# sourceMappingURL=babylon.sprite.js.map
  28334. var BABYLON;
  28335. (function (BABYLON) {
  28336. var Layer = (function () {
  28337. function Layer(name, imgUrl, scene, isBackground, color) {
  28338. this.name = name;
  28339. this.scale = new BABYLON.Vector2(1, 1);
  28340. this.offset = new BABYLON.Vector2(0, 0);
  28341. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28342. this._vertexBuffers = {};
  28343. // Events
  28344. /**
  28345. * An event triggered when the layer is disposed.
  28346. * @type {BABYLON.Observable}
  28347. */
  28348. this.onDisposeObservable = new BABYLON.Observable();
  28349. /**
  28350. * An event triggered before rendering the scene
  28351. * @type {BABYLON.Observable}
  28352. */
  28353. this.onBeforeRenderObservable = new BABYLON.Observable();
  28354. /**
  28355. * An event triggered after rendering the scene
  28356. * @type {BABYLON.Observable}
  28357. */
  28358. this.onAfterRenderObservable = new BABYLON.Observable();
  28359. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28360. this.isBackground = isBackground === undefined ? true : isBackground;
  28361. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28362. this._scene = scene;
  28363. this._scene.layers.push(this);
  28364. var engine = scene.getEngine();
  28365. // VBO
  28366. var vertices = [];
  28367. vertices.push(1, 1);
  28368. vertices.push(-1, 1);
  28369. vertices.push(-1, -1);
  28370. vertices.push(1, -1);
  28371. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28373. // Indices
  28374. var indices = [];
  28375. indices.push(0);
  28376. indices.push(1);
  28377. indices.push(2);
  28378. indices.push(0);
  28379. indices.push(2);
  28380. indices.push(3);
  28381. this._indexBuffer = engine.createIndexBuffer(indices);
  28382. // Effects
  28383. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28384. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28385. }
  28386. Object.defineProperty(Layer.prototype, "onDispose", {
  28387. set: function (callback) {
  28388. if (this._onDisposeObserver) {
  28389. this.onDisposeObservable.remove(this._onDisposeObserver);
  28390. }
  28391. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28392. },
  28393. enumerable: true,
  28394. configurable: true
  28395. });
  28396. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28397. set: function (callback) {
  28398. if (this._onBeforeRenderObserver) {
  28399. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28400. }
  28401. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28407. set: function (callback) {
  28408. if (this._onAfterRenderObserver) {
  28409. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28410. }
  28411. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28412. },
  28413. enumerable: true,
  28414. configurable: true
  28415. });
  28416. Layer.prototype.render = function () {
  28417. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28418. // Check
  28419. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28420. return;
  28421. var engine = this._scene.getEngine();
  28422. this.onBeforeRenderObservable.notifyObservers(this);
  28423. // Render
  28424. engine.enableEffect(currentEffect);
  28425. engine.setState(false);
  28426. // Texture
  28427. currentEffect.setTexture("textureSampler", this.texture);
  28428. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28429. // Color
  28430. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28431. // Scale / offset
  28432. currentEffect.setVector2("offset", this.offset);
  28433. currentEffect.setVector2("scale", this.scale);
  28434. // VBOs
  28435. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28436. // Draw order
  28437. if (!this.alphaTest) {
  28438. engine.setAlphaMode(this.alphaBlendingMode);
  28439. engine.draw(true, 0, 6);
  28440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28441. }
  28442. else {
  28443. engine.draw(true, 0, 6);
  28444. }
  28445. this.onAfterRenderObservable.notifyObservers(this);
  28446. };
  28447. Layer.prototype.dispose = function () {
  28448. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28449. if (vertexBuffer) {
  28450. vertexBuffer.dispose();
  28451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28452. }
  28453. if (this._indexBuffer) {
  28454. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28455. this._indexBuffer = null;
  28456. }
  28457. if (this.texture) {
  28458. this.texture.dispose();
  28459. this.texture = null;
  28460. }
  28461. // Remove from scene
  28462. var index = this._scene.layers.indexOf(this);
  28463. this._scene.layers.splice(index, 1);
  28464. // Callback
  28465. this.onDisposeObservable.notifyObservers(this);
  28466. this.onDisposeObservable.clear();
  28467. this.onAfterRenderObservable.clear();
  28468. this.onBeforeRenderObservable.clear();
  28469. };
  28470. return Layer;
  28471. }());
  28472. BABYLON.Layer = Layer;
  28473. })(BABYLON || (BABYLON = {}));
  28474. //# sourceMappingURL=babylon.layer.js.map
  28475. var BABYLON;
  28476. (function (BABYLON) {
  28477. var Particle = (function () {
  28478. function Particle() {
  28479. this.position = BABYLON.Vector3.Zero();
  28480. this.direction = BABYLON.Vector3.Zero();
  28481. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28482. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28483. this.lifeTime = 1.0;
  28484. this.age = 0;
  28485. this.size = 0;
  28486. this.angle = 0;
  28487. this.angularSpeed = 0;
  28488. }
  28489. Particle.prototype.copyTo = function (other) {
  28490. other.position.copyFrom(this.position);
  28491. other.direction.copyFrom(this.direction);
  28492. other.color.copyFrom(this.color);
  28493. other.colorStep.copyFrom(this.colorStep);
  28494. other.lifeTime = this.lifeTime;
  28495. other.age = this.age;
  28496. other.size = this.size;
  28497. other.angle = this.angle;
  28498. other.angularSpeed = this.angularSpeed;
  28499. };
  28500. return Particle;
  28501. }());
  28502. BABYLON.Particle = Particle;
  28503. })(BABYLON || (BABYLON = {}));
  28504. //# sourceMappingURL=babylon.particle.js.map
  28505. var BABYLON;
  28506. (function (BABYLON) {
  28507. var randomNumber = function (min, max) {
  28508. if (min === max) {
  28509. return (min);
  28510. }
  28511. var random = Math.random();
  28512. return ((random * (max - min)) + min);
  28513. };
  28514. var ParticleSystem = (function () {
  28515. function ParticleSystem(name, capacity, scene, customEffect) {
  28516. var _this = this;
  28517. this.name = name;
  28518. // Members
  28519. this.animations = [];
  28520. this.renderingGroupId = 0;
  28521. this.emitter = null;
  28522. this.emitRate = 10;
  28523. this.manualEmitCount = -1;
  28524. this.updateSpeed = 0.01;
  28525. this.targetStopDuration = 0;
  28526. this.disposeOnStop = false;
  28527. this.minEmitPower = 1;
  28528. this.maxEmitPower = 1;
  28529. this.minLifeTime = 1;
  28530. this.maxLifeTime = 1;
  28531. this.minSize = 1;
  28532. this.maxSize = 1;
  28533. this.minAngularSpeed = 0;
  28534. this.maxAngularSpeed = 0;
  28535. this.layerMask = 0x0FFFFFFF;
  28536. /**
  28537. * An event triggered when the system is disposed.
  28538. * @type {BABYLON.Observable}
  28539. */
  28540. this.onDisposeObservable = new BABYLON.Observable();
  28541. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28542. this.forceDepthWrite = false;
  28543. this.gravity = BABYLON.Vector3.Zero();
  28544. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28545. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28546. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28547. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28548. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28549. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28550. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28551. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28552. this.particles = new Array();
  28553. this._stockParticles = new Array();
  28554. this._newPartsExcess = 0;
  28555. this._vertexBuffers = {};
  28556. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28557. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28558. this._scaledDirection = BABYLON.Vector3.Zero();
  28559. this._scaledGravity = BABYLON.Vector3.Zero();
  28560. this._currentRenderId = -1;
  28561. this._started = false;
  28562. this._stopped = false;
  28563. this._actualFrame = 0;
  28564. this.id = name;
  28565. this._capacity = capacity;
  28566. this._scene = scene;
  28567. this._customEffect = customEffect;
  28568. scene.particleSystems.push(this);
  28569. var indices = [];
  28570. var index = 0;
  28571. for (var count = 0; count < capacity; count++) {
  28572. indices.push(index);
  28573. indices.push(index + 1);
  28574. indices.push(index + 2);
  28575. indices.push(index);
  28576. indices.push(index + 2);
  28577. indices.push(index + 3);
  28578. index += 4;
  28579. }
  28580. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28581. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28582. this._vertexData = new Float32Array(capacity * 11 * 4);
  28583. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28584. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28585. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28586. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28588. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28589. this._vertexBuffers["options"] = options;
  28590. // Default behaviors
  28591. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28592. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28593. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28594. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28595. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28596. };
  28597. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28598. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28599. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28600. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28602. };
  28603. this.updateFunction = function (particles) {
  28604. for (var index = 0; index < particles.length; index++) {
  28605. var particle = particles[index];
  28606. particle.age += _this._scaledUpdateSpeed;
  28607. if (particle.age >= particle.lifeTime) {
  28608. _this.recycleParticle(particle);
  28609. index--;
  28610. continue;
  28611. }
  28612. else {
  28613. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28614. particle.color.addInPlace(_this._scaledColorStep);
  28615. if (particle.color.a < 0)
  28616. particle.color.a = 0;
  28617. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28618. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28619. particle.position.addInPlace(_this._scaledDirection);
  28620. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28621. particle.direction.addInPlace(_this._scaledGravity);
  28622. }
  28623. }
  28624. };
  28625. }
  28626. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28627. set: function (callback) {
  28628. if (this._onDisposeObserver) {
  28629. this.onDisposeObservable.remove(this._onDisposeObserver);
  28630. }
  28631. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28632. },
  28633. enumerable: true,
  28634. configurable: true
  28635. });
  28636. ParticleSystem.prototype.recycleParticle = function (particle) {
  28637. var lastParticle = this.particles.pop();
  28638. if (lastParticle !== particle) {
  28639. lastParticle.copyTo(particle);
  28640. this._stockParticles.push(lastParticle);
  28641. }
  28642. };
  28643. ParticleSystem.prototype.getCapacity = function () {
  28644. return this._capacity;
  28645. };
  28646. ParticleSystem.prototype.isAlive = function () {
  28647. return this._alive;
  28648. };
  28649. ParticleSystem.prototype.isStarted = function () {
  28650. return this._started;
  28651. };
  28652. ParticleSystem.prototype.start = function () {
  28653. this._started = true;
  28654. this._stopped = false;
  28655. this._actualFrame = 0;
  28656. };
  28657. ParticleSystem.prototype.stop = function () {
  28658. this._stopped = true;
  28659. };
  28660. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28661. var offset = index * 11;
  28662. this._vertexData[offset] = particle.position.x;
  28663. this._vertexData[offset + 1] = particle.position.y;
  28664. this._vertexData[offset + 2] = particle.position.z;
  28665. this._vertexData[offset + 3] = particle.color.r;
  28666. this._vertexData[offset + 4] = particle.color.g;
  28667. this._vertexData[offset + 5] = particle.color.b;
  28668. this._vertexData[offset + 6] = particle.color.a;
  28669. this._vertexData[offset + 7] = particle.angle;
  28670. this._vertexData[offset + 8] = particle.size;
  28671. this._vertexData[offset + 9] = offsetX;
  28672. this._vertexData[offset + 10] = offsetY;
  28673. };
  28674. ParticleSystem.prototype._update = function (newParticles) {
  28675. // Update current
  28676. this._alive = this.particles.length > 0;
  28677. this.updateFunction(this.particles);
  28678. // Add new ones
  28679. var worldMatrix;
  28680. if (this.emitter.position) {
  28681. worldMatrix = this.emitter.getWorldMatrix();
  28682. }
  28683. else {
  28684. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28685. }
  28686. var particle;
  28687. for (var index = 0; index < newParticles; index++) {
  28688. if (this.particles.length === this._capacity) {
  28689. break;
  28690. }
  28691. if (this._stockParticles.length !== 0) {
  28692. particle = this._stockParticles.pop();
  28693. particle.age = 0;
  28694. }
  28695. else {
  28696. particle = new BABYLON.Particle();
  28697. }
  28698. this.particles.push(particle);
  28699. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28700. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28701. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28702. particle.size = randomNumber(this.minSize, this.maxSize);
  28703. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28704. this.startPositionFunction(worldMatrix, particle.position, particle);
  28705. var step = randomNumber(0, 1.0);
  28706. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28707. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28708. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28709. }
  28710. };
  28711. ParticleSystem.prototype._getEffect = function () {
  28712. if (this._customEffect) {
  28713. return this._customEffect;
  28714. }
  28715. ;
  28716. var defines = [];
  28717. if (this._scene.clipPlane) {
  28718. defines.push("#define CLIPPLANE");
  28719. }
  28720. // Effect
  28721. var join = defines.join("\n");
  28722. if (this._cachedDefines !== join) {
  28723. this._cachedDefines = join;
  28724. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28725. }
  28726. return this._effect;
  28727. };
  28728. ParticleSystem.prototype.animate = function () {
  28729. if (!this._started)
  28730. return;
  28731. var effect = this._getEffect();
  28732. // Check
  28733. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28734. return;
  28735. if (this._currentRenderId === this._scene.getRenderId()) {
  28736. return;
  28737. }
  28738. this._currentRenderId = this._scene.getRenderId();
  28739. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28740. // determine the number of particles we need to create
  28741. var newParticles;
  28742. if (this.manualEmitCount > -1) {
  28743. newParticles = this.manualEmitCount;
  28744. this._newPartsExcess = 0;
  28745. this.manualEmitCount = 0;
  28746. }
  28747. else {
  28748. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28749. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28750. }
  28751. if (this._newPartsExcess > 1.0) {
  28752. newParticles += this._newPartsExcess >> 0;
  28753. this._newPartsExcess -= this._newPartsExcess >> 0;
  28754. }
  28755. this._alive = false;
  28756. if (!this._stopped) {
  28757. this._actualFrame += this._scaledUpdateSpeed;
  28758. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28759. this.stop();
  28760. }
  28761. else {
  28762. newParticles = 0;
  28763. }
  28764. this._update(newParticles);
  28765. // Stopped?
  28766. if (this._stopped) {
  28767. if (!this._alive) {
  28768. this._started = false;
  28769. if (this.disposeOnStop) {
  28770. this._scene._toBeDisposed.push(this);
  28771. }
  28772. }
  28773. }
  28774. // Update VBO
  28775. var offset = 0;
  28776. for (var index = 0; index < this.particles.length; index++) {
  28777. var particle = this.particles[index];
  28778. this._appendParticleVertex(offset++, particle, 0, 0);
  28779. this._appendParticleVertex(offset++, particle, 1, 0);
  28780. this._appendParticleVertex(offset++, particle, 1, 1);
  28781. this._appendParticleVertex(offset++, particle, 0, 1);
  28782. }
  28783. this._vertexBuffer.update(this._vertexData);
  28784. };
  28785. ParticleSystem.prototype.render = function () {
  28786. var effect = this._getEffect();
  28787. // Check
  28788. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28789. return 0;
  28790. var engine = this._scene.getEngine();
  28791. // Render
  28792. engine.enableEffect(effect);
  28793. engine.setState(false);
  28794. var viewMatrix = this._scene.getViewMatrix();
  28795. effect.setTexture("diffuseSampler", this.particleTexture);
  28796. effect.setMatrix("view", viewMatrix);
  28797. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28798. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28799. if (this._scene.clipPlane) {
  28800. var clipPlane = this._scene.clipPlane;
  28801. var invView = viewMatrix.clone();
  28802. invView.invert();
  28803. effect.setMatrix("invView", invView);
  28804. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28805. }
  28806. // VBOs
  28807. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28808. // Draw order
  28809. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28810. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28811. }
  28812. else {
  28813. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28814. }
  28815. if (this.forceDepthWrite) {
  28816. engine.setDepthWrite(true);
  28817. }
  28818. engine.draw(true, 0, this.particles.length * 6);
  28819. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28820. return this.particles.length;
  28821. };
  28822. ParticleSystem.prototype.dispose = function () {
  28823. if (this._vertexBuffer) {
  28824. this._vertexBuffer.dispose();
  28825. this._vertexBuffer = null;
  28826. }
  28827. if (this._indexBuffer) {
  28828. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28829. this._indexBuffer = null;
  28830. }
  28831. if (this.particleTexture) {
  28832. this.particleTexture.dispose();
  28833. this.particleTexture = null;
  28834. }
  28835. // Remove from scene
  28836. var index = this._scene.particleSystems.indexOf(this);
  28837. this._scene.particleSystems.splice(index, 1);
  28838. // Callback
  28839. this.onDisposeObservable.notifyObservers(this);
  28840. this.onDisposeObservable.clear();
  28841. };
  28842. // Clone
  28843. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28844. var result = new ParticleSystem(name, this._capacity, this._scene);
  28845. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28846. if (newEmitter === undefined) {
  28847. newEmitter = this.emitter;
  28848. }
  28849. result.emitter = newEmitter;
  28850. if (this.particleTexture) {
  28851. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28852. }
  28853. result.start();
  28854. return result;
  28855. };
  28856. ParticleSystem.prototype.serialize = function () {
  28857. var serializationObject = {};
  28858. serializationObject.name = this.name;
  28859. serializationObject.id = this.id;
  28860. // Emitter
  28861. if (this.emitter.position) {
  28862. serializationObject.emitterId = this.emitter.id;
  28863. }
  28864. else {
  28865. serializationObject.emitter = this.emitter.asArray();
  28866. }
  28867. serializationObject.capacity = this.getCapacity();
  28868. if (this.particleTexture) {
  28869. serializationObject.textureName = this.particleTexture.name;
  28870. }
  28871. // Animations
  28872. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28873. // Particle system
  28874. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28875. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28876. serializationObject.minSize = this.minSize;
  28877. serializationObject.maxSize = this.maxSize;
  28878. serializationObject.minEmitPower = this.minEmitPower;
  28879. serializationObject.maxEmitPower = this.maxEmitPower;
  28880. serializationObject.minLifeTime = this.minLifeTime;
  28881. serializationObject.maxLifeTime = this.maxLifeTime;
  28882. serializationObject.emitRate = this.emitRate;
  28883. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28884. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28885. serializationObject.gravity = this.gravity.asArray();
  28886. serializationObject.direction1 = this.direction1.asArray();
  28887. serializationObject.direction2 = this.direction2.asArray();
  28888. serializationObject.color1 = this.color1.asArray();
  28889. serializationObject.color2 = this.color2.asArray();
  28890. serializationObject.colorDead = this.colorDead.asArray();
  28891. serializationObject.updateSpeed = this.updateSpeed;
  28892. serializationObject.targetStopDuration = this.targetStopDuration;
  28893. serializationObject.textureMask = this.textureMask.asArray();
  28894. serializationObject.blendMode = this.blendMode;
  28895. return serializationObject;
  28896. };
  28897. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28898. var name = parsedParticleSystem.name;
  28899. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28900. if (parsedParticleSystem.id) {
  28901. particleSystem.id = parsedParticleSystem.id;
  28902. }
  28903. // Texture
  28904. if (parsedParticleSystem.textureName) {
  28905. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28906. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28907. }
  28908. // Emitter
  28909. if (parsedParticleSystem.emitterId) {
  28910. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28911. }
  28912. else {
  28913. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28914. }
  28915. // Animations
  28916. if (parsedParticleSystem.animations) {
  28917. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28918. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28919. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28920. }
  28921. }
  28922. if (parsedParticleSystem.autoAnimate) {
  28923. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28924. }
  28925. // Particle system
  28926. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28927. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28928. particleSystem.minSize = parsedParticleSystem.minSize;
  28929. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28930. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28931. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28932. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28933. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28934. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28935. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28936. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28937. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28938. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28939. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28940. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28941. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28942. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28943. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28944. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28945. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28946. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28947. if (!parsedParticleSystem.preventAutoStart) {
  28948. particleSystem.start();
  28949. }
  28950. return particleSystem;
  28951. };
  28952. // Statics
  28953. ParticleSystem.BLENDMODE_ONEONE = 0;
  28954. ParticleSystem.BLENDMODE_STANDARD = 1;
  28955. return ParticleSystem;
  28956. }());
  28957. BABYLON.ParticleSystem = ParticleSystem;
  28958. })(BABYLON || (BABYLON = {}));
  28959. //# sourceMappingURL=babylon.particleSystem.js.map
  28960. var BABYLON;
  28961. (function (BABYLON) {
  28962. var AnimationRange = (function () {
  28963. function AnimationRange(name, from, to) {
  28964. this.name = name;
  28965. this.from = from;
  28966. this.to = to;
  28967. }
  28968. AnimationRange.prototype.clone = function () {
  28969. return new AnimationRange(this.name, this.from, this.to);
  28970. };
  28971. return AnimationRange;
  28972. }());
  28973. BABYLON.AnimationRange = AnimationRange;
  28974. /**
  28975. * Composed of a frame, and an action function
  28976. */
  28977. var AnimationEvent = (function () {
  28978. function AnimationEvent(frame, action, onlyOnce) {
  28979. this.frame = frame;
  28980. this.action = action;
  28981. this.onlyOnce = onlyOnce;
  28982. this.isDone = false;
  28983. }
  28984. return AnimationEvent;
  28985. }());
  28986. BABYLON.AnimationEvent = AnimationEvent;
  28987. var PathCursor = (function () {
  28988. function PathCursor(path) {
  28989. this.path = path;
  28990. this._onchange = new Array();
  28991. this.value = 0;
  28992. this.animations = new Array();
  28993. }
  28994. PathCursor.prototype.getPoint = function () {
  28995. var point = this.path.getPointAtLengthPosition(this.value);
  28996. return new BABYLON.Vector3(point.x, 0, point.y);
  28997. };
  28998. PathCursor.prototype.moveAhead = function (step) {
  28999. if (step === void 0) { step = 0.002; }
  29000. this.move(step);
  29001. return this;
  29002. };
  29003. PathCursor.prototype.moveBack = function (step) {
  29004. if (step === void 0) { step = 0.002; }
  29005. this.move(-step);
  29006. return this;
  29007. };
  29008. PathCursor.prototype.move = function (step) {
  29009. if (Math.abs(step) > 1) {
  29010. throw "step size should be less than 1.";
  29011. }
  29012. this.value += step;
  29013. this.ensureLimits();
  29014. this.raiseOnChange();
  29015. return this;
  29016. };
  29017. PathCursor.prototype.ensureLimits = function () {
  29018. while (this.value > 1) {
  29019. this.value -= 1;
  29020. }
  29021. while (this.value < 0) {
  29022. this.value += 1;
  29023. }
  29024. return this;
  29025. };
  29026. // used by animation engine
  29027. PathCursor.prototype.markAsDirty = function (propertyName) {
  29028. this.ensureLimits();
  29029. this.raiseOnChange();
  29030. return this;
  29031. };
  29032. PathCursor.prototype.raiseOnChange = function () {
  29033. var _this = this;
  29034. this._onchange.forEach(function (f) { return f(_this); });
  29035. return this;
  29036. };
  29037. PathCursor.prototype.onchange = function (f) {
  29038. this._onchange.push(f);
  29039. return this;
  29040. };
  29041. return PathCursor;
  29042. }());
  29043. BABYLON.PathCursor = PathCursor;
  29044. var Animation = (function () {
  29045. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29046. this.name = name;
  29047. this.targetProperty = targetProperty;
  29048. this.framePerSecond = framePerSecond;
  29049. this.dataType = dataType;
  29050. this.loopMode = loopMode;
  29051. this.enableBlending = enableBlending;
  29052. this._offsetsCache = {};
  29053. this._highLimitsCache = {};
  29054. this._stopped = false;
  29055. this._blendingFactor = 0;
  29056. // The set of event that will be linked to this animation
  29057. this._events = new Array();
  29058. this.allowMatricesInterpolation = false;
  29059. this.blendingSpeed = 0.01;
  29060. this._ranges = {};
  29061. this.targetPropertyPath = targetProperty.split(".");
  29062. this.dataType = dataType;
  29063. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29064. }
  29065. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29066. var dataType = undefined;
  29067. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29068. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29069. }
  29070. else if (from instanceof BABYLON.Quaternion) {
  29071. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29072. }
  29073. else if (from instanceof BABYLON.Vector3) {
  29074. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29075. }
  29076. else if (from instanceof BABYLON.Vector2) {
  29077. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29078. }
  29079. else if (from instanceof BABYLON.Color3) {
  29080. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29081. }
  29082. else if (from instanceof BABYLON.Size) {
  29083. dataType = Animation.ANIMATIONTYPE_SIZE;
  29084. }
  29085. if (dataType == undefined) {
  29086. return null;
  29087. }
  29088. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29089. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29090. animation.setKeys(keys);
  29091. if (easingFunction !== undefined) {
  29092. animation.setEasingFunction(easingFunction);
  29093. }
  29094. return animation;
  29095. };
  29096. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29097. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29098. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29099. };
  29100. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29101. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29102. node.animations.push(animation);
  29103. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29104. };
  29105. // Methods
  29106. /**
  29107. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29108. */
  29109. Animation.prototype.toString = function (fullDetails) {
  29110. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29111. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29112. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29113. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29114. if (fullDetails) {
  29115. ret += ", Ranges: {";
  29116. var first = true;
  29117. for (var name in this._ranges) {
  29118. if (first) {
  29119. ret += ", ";
  29120. first = false;
  29121. }
  29122. ret += name;
  29123. }
  29124. ret += "}";
  29125. }
  29126. return ret;
  29127. };
  29128. /**
  29129. * Add an event to this animation.
  29130. */
  29131. Animation.prototype.addEvent = function (event) {
  29132. this._events.push(event);
  29133. };
  29134. /**
  29135. * Remove all events found at the given frame
  29136. * @param frame
  29137. */
  29138. Animation.prototype.removeEvents = function (frame) {
  29139. for (var index = 0; index < this._events.length; index++) {
  29140. if (this._events[index].frame === frame) {
  29141. this._events.splice(index, 1);
  29142. index--;
  29143. }
  29144. }
  29145. };
  29146. Animation.prototype.createRange = function (name, from, to) {
  29147. // check name not already in use; could happen for bones after serialized
  29148. if (!this._ranges[name]) {
  29149. this._ranges[name] = new AnimationRange(name, from, to);
  29150. }
  29151. };
  29152. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29153. if (deleteFrames === void 0) { deleteFrames = true; }
  29154. if (this._ranges[name]) {
  29155. if (deleteFrames) {
  29156. var from = this._ranges[name].from;
  29157. var to = this._ranges[name].to;
  29158. // this loop MUST go high to low for multiple splices to work
  29159. for (var key = this._keys.length - 1; key >= 0; key--) {
  29160. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29161. this._keys.splice(key, 1);
  29162. }
  29163. }
  29164. }
  29165. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29166. }
  29167. };
  29168. Animation.prototype.getRange = function (name) {
  29169. return this._ranges[name];
  29170. };
  29171. Animation.prototype.reset = function () {
  29172. this._offsetsCache = {};
  29173. this._highLimitsCache = {};
  29174. this.currentFrame = 0;
  29175. this._blendingFactor = 0;
  29176. this._originalBlendValue = null;
  29177. };
  29178. Animation.prototype.isStopped = function () {
  29179. return this._stopped;
  29180. };
  29181. Animation.prototype.getKeys = function () {
  29182. return this._keys;
  29183. };
  29184. Animation.prototype.getHighestFrame = function () {
  29185. var ret = 0;
  29186. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29187. if (ret < this._keys[key].frame) {
  29188. ret = this._keys[key].frame;
  29189. }
  29190. }
  29191. return ret;
  29192. };
  29193. Animation.prototype.getEasingFunction = function () {
  29194. return this._easingFunction;
  29195. };
  29196. Animation.prototype.setEasingFunction = function (easingFunction) {
  29197. this._easingFunction = easingFunction;
  29198. };
  29199. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29200. return startValue + (endValue - startValue) * gradient;
  29201. };
  29202. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29203. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29204. };
  29205. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29206. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29207. };
  29208. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29209. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29210. };
  29211. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29212. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29213. };
  29214. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29215. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29216. };
  29217. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29218. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29219. };
  29220. Animation.prototype.clone = function () {
  29221. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29222. if (this._keys) {
  29223. clone.setKeys(this._keys);
  29224. }
  29225. if (this._ranges) {
  29226. clone._ranges = {};
  29227. for (var name in this._ranges) {
  29228. clone._ranges[name] = this._ranges[name].clone();
  29229. }
  29230. }
  29231. return clone;
  29232. };
  29233. Animation.prototype.setKeys = function (values) {
  29234. this._keys = values.slice(0);
  29235. this._offsetsCache = {};
  29236. this._highLimitsCache = {};
  29237. };
  29238. Animation.prototype._getKeyValue = function (value) {
  29239. if (typeof value === "function") {
  29240. return value();
  29241. }
  29242. return value;
  29243. };
  29244. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29245. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29246. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29247. }
  29248. this.currentFrame = currentFrame;
  29249. // Try to get a hash to find the right key
  29250. 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));
  29251. if (this._keys[startKey].frame >= currentFrame) {
  29252. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29253. startKey--;
  29254. }
  29255. }
  29256. for (var key = startKey; key < this._keys.length; key++) {
  29257. if (this._keys[key + 1].frame >= currentFrame) {
  29258. var startValue = this._getKeyValue(this._keys[key].value);
  29259. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29260. // gradient : percent of currentFrame between the frame inf and the frame sup
  29261. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29262. // check for easingFunction and correction of gradient
  29263. if (this._easingFunction != null) {
  29264. gradient = this._easingFunction.ease(gradient);
  29265. }
  29266. switch (this.dataType) {
  29267. // Float
  29268. case Animation.ANIMATIONTYPE_FLOAT:
  29269. switch (loopMode) {
  29270. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29271. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29272. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29273. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29274. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29275. }
  29276. break;
  29277. // Quaternion
  29278. case Animation.ANIMATIONTYPE_QUATERNION:
  29279. var quaternion = null;
  29280. switch (loopMode) {
  29281. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29282. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29283. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29284. break;
  29285. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29286. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29287. break;
  29288. }
  29289. return quaternion;
  29290. // Vector3
  29291. case Animation.ANIMATIONTYPE_VECTOR3:
  29292. switch (loopMode) {
  29293. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29294. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29295. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29296. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29297. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29298. }
  29299. // Vector2
  29300. case Animation.ANIMATIONTYPE_VECTOR2:
  29301. switch (loopMode) {
  29302. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29303. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29304. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29305. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29306. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29307. }
  29308. // Size
  29309. case Animation.ANIMATIONTYPE_SIZE:
  29310. switch (loopMode) {
  29311. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29312. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29313. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29314. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29315. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29316. }
  29317. // Color3
  29318. case Animation.ANIMATIONTYPE_COLOR3:
  29319. switch (loopMode) {
  29320. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29321. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29322. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29323. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29324. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29325. }
  29326. // Matrix
  29327. case Animation.ANIMATIONTYPE_MATRIX:
  29328. switch (loopMode) {
  29329. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29330. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29331. if (this.allowMatricesInterpolation) {
  29332. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29333. }
  29334. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29335. return startValue;
  29336. }
  29337. default:
  29338. break;
  29339. }
  29340. break;
  29341. }
  29342. }
  29343. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29344. };
  29345. Animation.prototype.setValue = function (currentValue, blend) {
  29346. if (blend === void 0) { blend = false; }
  29347. // Set value
  29348. var path;
  29349. var destination;
  29350. if (this.targetPropertyPath.length > 1) {
  29351. var property = this._target[this.targetPropertyPath[0]];
  29352. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29353. property = property[this.targetPropertyPath[index]];
  29354. }
  29355. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29356. destination = property;
  29357. }
  29358. else {
  29359. path = this.targetPropertyPath[0];
  29360. destination = this._target;
  29361. }
  29362. // Blending
  29363. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29364. if (!this._originalBlendValue) {
  29365. if (destination[path].clone) {
  29366. this._originalBlendValue = destination[path].clone();
  29367. }
  29368. else {
  29369. this._originalBlendValue = destination[path];
  29370. }
  29371. }
  29372. if (this._originalBlendValue.prototype) {
  29373. if (this._originalBlendValue.prototype.Lerp) {
  29374. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29375. }
  29376. else {
  29377. destination[path] = currentValue;
  29378. }
  29379. }
  29380. else if (this._originalBlendValue.m) {
  29381. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29382. }
  29383. else {
  29384. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29385. }
  29386. this._blendingFactor += this.blendingSpeed;
  29387. }
  29388. else {
  29389. destination[path] = currentValue;
  29390. }
  29391. if (this._target.markAsDirty) {
  29392. this._target.markAsDirty(this.targetProperty);
  29393. }
  29394. };
  29395. Animation.prototype.goToFrame = function (frame) {
  29396. if (frame < this._keys[0].frame) {
  29397. frame = this._keys[0].frame;
  29398. }
  29399. else if (frame > this._keys[this._keys.length - 1].frame) {
  29400. frame = this._keys[this._keys.length - 1].frame;
  29401. }
  29402. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29403. this.setValue(currentValue);
  29404. };
  29405. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29406. if (blend === void 0) { blend = false; }
  29407. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29408. this._stopped = true;
  29409. return false;
  29410. }
  29411. var returnValue = true;
  29412. // Adding a start key at frame 0 if missing
  29413. if (this._keys[0].frame !== 0) {
  29414. var newKey = { frame: 0, value: this._keys[0].value };
  29415. this._keys.splice(0, 0, newKey);
  29416. }
  29417. // Check limits
  29418. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29419. from = this._keys[0].frame;
  29420. }
  29421. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29422. to = this._keys[this._keys.length - 1].frame;
  29423. }
  29424. //to and from cannot be the same key
  29425. if (from === to) {
  29426. from++;
  29427. }
  29428. // Compute ratio
  29429. var range = to - from;
  29430. var offsetValue;
  29431. // ratio represents the frame delta between from and to
  29432. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29433. var highLimitValue = 0;
  29434. if (ratio > range && !loop) {
  29435. returnValue = false;
  29436. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29437. }
  29438. else {
  29439. // Get max value if required
  29440. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29441. var keyOffset = to.toString() + from.toString();
  29442. if (!this._offsetsCache[keyOffset]) {
  29443. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29444. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29445. switch (this.dataType) {
  29446. // Float
  29447. case Animation.ANIMATIONTYPE_FLOAT:
  29448. this._offsetsCache[keyOffset] = toValue - fromValue;
  29449. break;
  29450. // Quaternion
  29451. case Animation.ANIMATIONTYPE_QUATERNION:
  29452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29453. break;
  29454. // Vector3
  29455. case Animation.ANIMATIONTYPE_VECTOR3:
  29456. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29457. // Vector2
  29458. case Animation.ANIMATIONTYPE_VECTOR2:
  29459. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29460. // Size
  29461. case Animation.ANIMATIONTYPE_SIZE:
  29462. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29463. // Color3
  29464. case Animation.ANIMATIONTYPE_COLOR3:
  29465. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29466. default:
  29467. break;
  29468. }
  29469. this._highLimitsCache[keyOffset] = toValue;
  29470. }
  29471. highLimitValue = this._highLimitsCache[keyOffset];
  29472. offsetValue = this._offsetsCache[keyOffset];
  29473. }
  29474. }
  29475. if (offsetValue === undefined) {
  29476. switch (this.dataType) {
  29477. // Float
  29478. case Animation.ANIMATIONTYPE_FLOAT:
  29479. offsetValue = 0;
  29480. break;
  29481. // Quaternion
  29482. case Animation.ANIMATIONTYPE_QUATERNION:
  29483. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29484. break;
  29485. // Vector3
  29486. case Animation.ANIMATIONTYPE_VECTOR3:
  29487. offsetValue = BABYLON.Vector3.Zero();
  29488. break;
  29489. // Vector2
  29490. case Animation.ANIMATIONTYPE_VECTOR2:
  29491. offsetValue = BABYLON.Vector2.Zero();
  29492. break;
  29493. // Size
  29494. case Animation.ANIMATIONTYPE_SIZE:
  29495. offsetValue = BABYLON.Size.Zero();
  29496. break;
  29497. // Color3
  29498. case Animation.ANIMATIONTYPE_COLOR3:
  29499. offsetValue = BABYLON.Color3.Black();
  29500. }
  29501. }
  29502. // Compute value
  29503. var repeatCount = (ratio / range) >> 0;
  29504. var currentFrame = returnValue ? from + ratio % range : to;
  29505. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29506. // Set value
  29507. this.setValue(currentValue);
  29508. // Check events
  29509. for (var index = 0; index < this._events.length; index++) {
  29510. if (currentFrame >= this._events[index].frame) {
  29511. var event = this._events[index];
  29512. if (!event.isDone) {
  29513. // If event should be done only once, remove it.
  29514. if (event.onlyOnce) {
  29515. this._events.splice(index, 1);
  29516. index--;
  29517. }
  29518. event.isDone = true;
  29519. event.action();
  29520. } // Don't do anything if the event has already be done.
  29521. }
  29522. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29523. // reset event, the animation is looping
  29524. this._events[index].isDone = false;
  29525. }
  29526. }
  29527. if (!returnValue) {
  29528. this._stopped = true;
  29529. }
  29530. return returnValue;
  29531. };
  29532. Animation.prototype.serialize = function () {
  29533. var serializationObject = {};
  29534. serializationObject.name = this.name;
  29535. serializationObject.property = this.targetProperty;
  29536. serializationObject.framePerSecond = this.framePerSecond;
  29537. serializationObject.dataType = this.dataType;
  29538. serializationObject.loopBehavior = this.loopMode;
  29539. var dataType = this.dataType;
  29540. serializationObject.keys = [];
  29541. var keys = this.getKeys();
  29542. for (var index = 0; index < keys.length; index++) {
  29543. var animationKey = keys[index];
  29544. var key = {};
  29545. key.frame = animationKey.frame;
  29546. switch (dataType) {
  29547. case Animation.ANIMATIONTYPE_FLOAT:
  29548. key.values = [animationKey.value];
  29549. break;
  29550. case Animation.ANIMATIONTYPE_QUATERNION:
  29551. case Animation.ANIMATIONTYPE_MATRIX:
  29552. case Animation.ANIMATIONTYPE_VECTOR3:
  29553. case Animation.ANIMATIONTYPE_COLOR3:
  29554. key.values = animationKey.value.asArray();
  29555. break;
  29556. }
  29557. serializationObject.keys.push(key);
  29558. }
  29559. serializationObject.ranges = [];
  29560. for (var name in this._ranges) {
  29561. var range = {};
  29562. range.name = name;
  29563. range.from = this._ranges[name].from;
  29564. range.to = this._ranges[name].to;
  29565. serializationObject.ranges.push(range);
  29566. }
  29567. return serializationObject;
  29568. };
  29569. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29570. get: function () {
  29571. return Animation._ANIMATIONTYPE_FLOAT;
  29572. },
  29573. enumerable: true,
  29574. configurable: true
  29575. });
  29576. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29577. get: function () {
  29578. return Animation._ANIMATIONTYPE_VECTOR3;
  29579. },
  29580. enumerable: true,
  29581. configurable: true
  29582. });
  29583. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29584. get: function () {
  29585. return Animation._ANIMATIONTYPE_VECTOR2;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29591. get: function () {
  29592. return Animation._ANIMATIONTYPE_SIZE;
  29593. },
  29594. enumerable: true,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29598. get: function () {
  29599. return Animation._ANIMATIONTYPE_QUATERNION;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29605. get: function () {
  29606. return Animation._ANIMATIONTYPE_MATRIX;
  29607. },
  29608. enumerable: true,
  29609. configurable: true
  29610. });
  29611. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29612. get: function () {
  29613. return Animation._ANIMATIONTYPE_COLOR3;
  29614. },
  29615. enumerable: true,
  29616. configurable: true
  29617. });
  29618. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29619. get: function () {
  29620. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29621. },
  29622. enumerable: true,
  29623. configurable: true
  29624. });
  29625. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29626. get: function () {
  29627. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29628. },
  29629. enumerable: true,
  29630. configurable: true
  29631. });
  29632. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29633. get: function () {
  29634. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29635. },
  29636. enumerable: true,
  29637. configurable: true
  29638. });
  29639. Animation.Parse = function (parsedAnimation) {
  29640. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29641. var dataType = parsedAnimation.dataType;
  29642. var keys = [];
  29643. var data;
  29644. var index;
  29645. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29646. var key = parsedAnimation.keys[index];
  29647. switch (dataType) {
  29648. case Animation.ANIMATIONTYPE_FLOAT:
  29649. data = key.values[0];
  29650. break;
  29651. case Animation.ANIMATIONTYPE_QUATERNION:
  29652. data = BABYLON.Quaternion.FromArray(key.values);
  29653. break;
  29654. case Animation.ANIMATIONTYPE_MATRIX:
  29655. data = BABYLON.Matrix.FromArray(key.values);
  29656. break;
  29657. case Animation.ANIMATIONTYPE_COLOR3:
  29658. data = BABYLON.Color3.FromArray(key.values);
  29659. break;
  29660. case Animation.ANIMATIONTYPE_VECTOR3:
  29661. default:
  29662. data = BABYLON.Vector3.FromArray(key.values);
  29663. break;
  29664. }
  29665. keys.push({
  29666. frame: key.frame,
  29667. value: data
  29668. });
  29669. }
  29670. animation.setKeys(keys);
  29671. if (parsedAnimation.ranges) {
  29672. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29673. data = parsedAnimation.ranges[index];
  29674. animation.createRange(data.name, data.from, data.to);
  29675. }
  29676. }
  29677. return animation;
  29678. };
  29679. Animation.AppendSerializedAnimations = function (source, destination) {
  29680. if (source.animations) {
  29681. destination.animations = [];
  29682. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29683. var animation = source.animations[animationIndex];
  29684. destination.animations.push(animation.serialize());
  29685. }
  29686. }
  29687. };
  29688. // Statics
  29689. Animation._ANIMATIONTYPE_FLOAT = 0;
  29690. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29691. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29692. Animation._ANIMATIONTYPE_MATRIX = 3;
  29693. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29694. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29695. Animation._ANIMATIONTYPE_SIZE = 6;
  29696. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29697. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29698. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29699. return Animation;
  29700. }());
  29701. BABYLON.Animation = Animation;
  29702. })(BABYLON || (BABYLON = {}));
  29703. //# sourceMappingURL=babylon.animation.js.map
  29704. var BABYLON;
  29705. (function (BABYLON) {
  29706. var Animatable = (function () {
  29707. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29708. if (fromFrame === void 0) { fromFrame = 0; }
  29709. if (toFrame === void 0) { toFrame = 100; }
  29710. if (loopAnimation === void 0) { loopAnimation = false; }
  29711. if (speedRatio === void 0) { speedRatio = 1.0; }
  29712. this.target = target;
  29713. this.fromFrame = fromFrame;
  29714. this.toFrame = toFrame;
  29715. this.loopAnimation = loopAnimation;
  29716. this.speedRatio = speedRatio;
  29717. this.onAnimationEnd = onAnimationEnd;
  29718. this._animations = new Array();
  29719. this._paused = false;
  29720. this.animationStarted = false;
  29721. if (animations) {
  29722. this.appendAnimations(target, animations);
  29723. }
  29724. this._scene = scene;
  29725. scene._activeAnimatables.push(this);
  29726. }
  29727. // Methods
  29728. Animatable.prototype.getAnimations = function () {
  29729. return this._animations;
  29730. };
  29731. Animatable.prototype.appendAnimations = function (target, animations) {
  29732. for (var index = 0; index < animations.length; index++) {
  29733. var animation = animations[index];
  29734. animation._target = target;
  29735. this._animations.push(animation);
  29736. }
  29737. };
  29738. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29739. var animations = this._animations;
  29740. for (var index = 0; index < animations.length; index++) {
  29741. if (animations[index].targetProperty === property) {
  29742. return animations[index];
  29743. }
  29744. }
  29745. return null;
  29746. };
  29747. Animatable.prototype.reset = function () {
  29748. var animations = this._animations;
  29749. for (var index = 0; index < animations.length; index++) {
  29750. animations[index].reset();
  29751. }
  29752. this._localDelayOffset = null;
  29753. this._pausedDelay = null;
  29754. };
  29755. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29756. var animations = this._animations;
  29757. for (var index = 0; index < animations.length; index++) {
  29758. animations[index].enableBlending = true;
  29759. animations[index].blendingSpeed = blendingSpeed;
  29760. }
  29761. };
  29762. Animatable.prototype.disableBlending = function () {
  29763. var animations = this._animations;
  29764. for (var index = 0; index < animations.length; index++) {
  29765. animations[index].enableBlending = false;
  29766. }
  29767. };
  29768. Animatable.prototype.goToFrame = function (frame) {
  29769. var animations = this._animations;
  29770. if (animations[0]) {
  29771. var fps = animations[0].framePerSecond;
  29772. var currentFrame = animations[0].currentFrame;
  29773. var adjustTime = frame - currentFrame;
  29774. var delay = adjustTime * 1000 / fps;
  29775. this._localDelayOffset -= delay;
  29776. }
  29777. for (var index = 0; index < animations.length; index++) {
  29778. animations[index].goToFrame(frame);
  29779. }
  29780. };
  29781. Animatable.prototype.pause = function () {
  29782. if (this._paused) {
  29783. return;
  29784. }
  29785. this._paused = true;
  29786. };
  29787. Animatable.prototype.restart = function () {
  29788. this._paused = false;
  29789. };
  29790. Animatable.prototype.stop = function (animationName) {
  29791. var index = this._scene._activeAnimatables.indexOf(this);
  29792. if (index > -1) {
  29793. var animations = this._animations;
  29794. var numberOfAnimationsStopped = 0;
  29795. for (var index = animations.length - 1; index >= 0; index--) {
  29796. if (typeof animationName === "string" && animations[index].name != animationName) {
  29797. continue;
  29798. }
  29799. animations[index].reset();
  29800. animations.splice(index, 1);
  29801. numberOfAnimationsStopped++;
  29802. }
  29803. if (animations.length == numberOfAnimationsStopped) {
  29804. this._scene._activeAnimatables.splice(index, 1);
  29805. if (this.onAnimationEnd) {
  29806. this.onAnimationEnd();
  29807. }
  29808. }
  29809. }
  29810. };
  29811. Animatable.prototype._animate = function (delay) {
  29812. if (this._paused) {
  29813. this.animationStarted = false;
  29814. if (!this._pausedDelay) {
  29815. this._pausedDelay = delay;
  29816. }
  29817. return true;
  29818. }
  29819. if (!this._localDelayOffset) {
  29820. this._localDelayOffset = delay;
  29821. }
  29822. else if (this._pausedDelay) {
  29823. this._localDelayOffset += delay - this._pausedDelay;
  29824. this._pausedDelay = null;
  29825. }
  29826. // Animating
  29827. var running = false;
  29828. var animations = this._animations;
  29829. var index;
  29830. for (index = 0; index < animations.length; index++) {
  29831. var animation = animations[index];
  29832. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29833. running = running || isRunning;
  29834. }
  29835. this.animationStarted = running;
  29836. if (!running) {
  29837. // Remove from active animatables
  29838. index = this._scene._activeAnimatables.indexOf(this);
  29839. this._scene._activeAnimatables.splice(index, 1);
  29840. }
  29841. if (!running && this.onAnimationEnd) {
  29842. this.onAnimationEnd();
  29843. this.onAnimationEnd = null;
  29844. }
  29845. return running;
  29846. };
  29847. return Animatable;
  29848. }());
  29849. BABYLON.Animatable = Animatable;
  29850. })(BABYLON || (BABYLON = {}));
  29851. //# sourceMappingURL=babylon.animatable.js.map
  29852. var BABYLON;
  29853. (function (BABYLON) {
  29854. var EasingFunction = (function () {
  29855. function EasingFunction() {
  29856. // Properties
  29857. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29858. }
  29859. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29860. get: function () {
  29861. return EasingFunction._EASINGMODE_EASEIN;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29867. get: function () {
  29868. return EasingFunction._EASINGMODE_EASEOUT;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29874. get: function () {
  29875. return EasingFunction._EASINGMODE_EASEINOUT;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29881. var n = Math.min(Math.max(easingMode, 0), 2);
  29882. this._easingMode = n;
  29883. };
  29884. EasingFunction.prototype.getEasingMode = function () {
  29885. return this._easingMode;
  29886. };
  29887. EasingFunction.prototype.easeInCore = function (gradient) {
  29888. throw new Error('You must implement this method');
  29889. };
  29890. EasingFunction.prototype.ease = function (gradient) {
  29891. switch (this._easingMode) {
  29892. case EasingFunction.EASINGMODE_EASEIN:
  29893. return this.easeInCore(gradient);
  29894. case EasingFunction.EASINGMODE_EASEOUT:
  29895. return (1 - this.easeInCore(1 - gradient));
  29896. }
  29897. if (gradient >= 0.5) {
  29898. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29899. }
  29900. return (this.easeInCore(gradient * 2) * 0.5);
  29901. };
  29902. //Statics
  29903. EasingFunction._EASINGMODE_EASEIN = 0;
  29904. EasingFunction._EASINGMODE_EASEOUT = 1;
  29905. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29906. return EasingFunction;
  29907. }());
  29908. BABYLON.EasingFunction = EasingFunction;
  29909. var CircleEase = (function (_super) {
  29910. __extends(CircleEase, _super);
  29911. function CircleEase() {
  29912. _super.apply(this, arguments);
  29913. }
  29914. CircleEase.prototype.easeInCore = function (gradient) {
  29915. gradient = Math.max(0, Math.min(1, gradient));
  29916. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29917. };
  29918. return CircleEase;
  29919. }(EasingFunction));
  29920. BABYLON.CircleEase = CircleEase;
  29921. var BackEase = (function (_super) {
  29922. __extends(BackEase, _super);
  29923. function BackEase(amplitude) {
  29924. if (amplitude === void 0) { amplitude = 1; }
  29925. _super.call(this);
  29926. this.amplitude = amplitude;
  29927. }
  29928. BackEase.prototype.easeInCore = function (gradient) {
  29929. var num = Math.max(0, this.amplitude);
  29930. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29931. };
  29932. return BackEase;
  29933. }(EasingFunction));
  29934. BABYLON.BackEase = BackEase;
  29935. var BounceEase = (function (_super) {
  29936. __extends(BounceEase, _super);
  29937. function BounceEase(bounces, bounciness) {
  29938. if (bounces === void 0) { bounces = 3; }
  29939. if (bounciness === void 0) { bounciness = 2; }
  29940. _super.call(this);
  29941. this.bounces = bounces;
  29942. this.bounciness = bounciness;
  29943. }
  29944. BounceEase.prototype.easeInCore = function (gradient) {
  29945. var y = Math.max(0.0, this.bounces);
  29946. var bounciness = this.bounciness;
  29947. if (bounciness <= 1.0) {
  29948. bounciness = 1.001;
  29949. }
  29950. var num9 = Math.pow(bounciness, y);
  29951. var num5 = 1.0 - bounciness;
  29952. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29953. var num15 = gradient * num4;
  29954. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29955. var num3 = Math.floor(num65);
  29956. var num13 = num3 + 1.0;
  29957. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29958. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29959. var num7 = (num8 + num12) * 0.5;
  29960. var num6 = gradient - num7;
  29961. var num2 = num7 - num8;
  29962. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29963. };
  29964. return BounceEase;
  29965. }(EasingFunction));
  29966. BABYLON.BounceEase = BounceEase;
  29967. var CubicEase = (function (_super) {
  29968. __extends(CubicEase, _super);
  29969. function CubicEase() {
  29970. _super.apply(this, arguments);
  29971. }
  29972. CubicEase.prototype.easeInCore = function (gradient) {
  29973. return (gradient * gradient * gradient);
  29974. };
  29975. return CubicEase;
  29976. }(EasingFunction));
  29977. BABYLON.CubicEase = CubicEase;
  29978. var ElasticEase = (function (_super) {
  29979. __extends(ElasticEase, _super);
  29980. function ElasticEase(oscillations, springiness) {
  29981. if (oscillations === void 0) { oscillations = 3; }
  29982. if (springiness === void 0) { springiness = 3; }
  29983. _super.call(this);
  29984. this.oscillations = oscillations;
  29985. this.springiness = springiness;
  29986. }
  29987. ElasticEase.prototype.easeInCore = function (gradient) {
  29988. var num2;
  29989. var num3 = Math.max(0.0, this.oscillations);
  29990. var num = Math.max(0.0, this.springiness);
  29991. if (num == 0) {
  29992. num2 = gradient;
  29993. }
  29994. else {
  29995. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29996. }
  29997. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29998. };
  29999. return ElasticEase;
  30000. }(EasingFunction));
  30001. BABYLON.ElasticEase = ElasticEase;
  30002. var ExponentialEase = (function (_super) {
  30003. __extends(ExponentialEase, _super);
  30004. function ExponentialEase(exponent) {
  30005. if (exponent === void 0) { exponent = 2; }
  30006. _super.call(this);
  30007. this.exponent = exponent;
  30008. }
  30009. ExponentialEase.prototype.easeInCore = function (gradient) {
  30010. if (this.exponent <= 0) {
  30011. return gradient;
  30012. }
  30013. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30014. };
  30015. return ExponentialEase;
  30016. }(EasingFunction));
  30017. BABYLON.ExponentialEase = ExponentialEase;
  30018. var PowerEase = (function (_super) {
  30019. __extends(PowerEase, _super);
  30020. function PowerEase(power) {
  30021. if (power === void 0) { power = 2; }
  30022. _super.call(this);
  30023. this.power = power;
  30024. }
  30025. PowerEase.prototype.easeInCore = function (gradient) {
  30026. var y = Math.max(0.0, this.power);
  30027. return Math.pow(gradient, y);
  30028. };
  30029. return PowerEase;
  30030. }(EasingFunction));
  30031. BABYLON.PowerEase = PowerEase;
  30032. var QuadraticEase = (function (_super) {
  30033. __extends(QuadraticEase, _super);
  30034. function QuadraticEase() {
  30035. _super.apply(this, arguments);
  30036. }
  30037. QuadraticEase.prototype.easeInCore = function (gradient) {
  30038. return (gradient * gradient);
  30039. };
  30040. return QuadraticEase;
  30041. }(EasingFunction));
  30042. BABYLON.QuadraticEase = QuadraticEase;
  30043. var QuarticEase = (function (_super) {
  30044. __extends(QuarticEase, _super);
  30045. function QuarticEase() {
  30046. _super.apply(this, arguments);
  30047. }
  30048. QuarticEase.prototype.easeInCore = function (gradient) {
  30049. return (gradient * gradient * gradient * gradient);
  30050. };
  30051. return QuarticEase;
  30052. }(EasingFunction));
  30053. BABYLON.QuarticEase = QuarticEase;
  30054. var QuinticEase = (function (_super) {
  30055. __extends(QuinticEase, _super);
  30056. function QuinticEase() {
  30057. _super.apply(this, arguments);
  30058. }
  30059. QuinticEase.prototype.easeInCore = function (gradient) {
  30060. return (gradient * gradient * gradient * gradient * gradient);
  30061. };
  30062. return QuinticEase;
  30063. }(EasingFunction));
  30064. BABYLON.QuinticEase = QuinticEase;
  30065. var SineEase = (function (_super) {
  30066. __extends(SineEase, _super);
  30067. function SineEase() {
  30068. _super.apply(this, arguments);
  30069. }
  30070. SineEase.prototype.easeInCore = function (gradient) {
  30071. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30072. };
  30073. return SineEase;
  30074. }(EasingFunction));
  30075. BABYLON.SineEase = SineEase;
  30076. var BezierCurveEase = (function (_super) {
  30077. __extends(BezierCurveEase, _super);
  30078. function BezierCurveEase(x1, y1, x2, y2) {
  30079. if (x1 === void 0) { x1 = 0; }
  30080. if (y1 === void 0) { y1 = 0; }
  30081. if (x2 === void 0) { x2 = 1; }
  30082. if (y2 === void 0) { y2 = 1; }
  30083. _super.call(this);
  30084. this.x1 = x1;
  30085. this.y1 = y1;
  30086. this.x2 = x2;
  30087. this.y2 = y2;
  30088. }
  30089. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30090. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30091. };
  30092. return BezierCurveEase;
  30093. }(EasingFunction));
  30094. BABYLON.BezierCurveEase = BezierCurveEase;
  30095. })(BABYLON || (BABYLON = {}));
  30096. //# sourceMappingURL=babylon.easing.js.map
  30097. var BABYLON;
  30098. (function (BABYLON) {
  30099. var Bone = (function (_super) {
  30100. __extends(Bone, _super);
  30101. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30102. _super.call(this, name, skeleton.getScene());
  30103. this.name = name;
  30104. this.children = new Array();
  30105. this.animations = new Array();
  30106. this._worldTransform = new BABYLON.Matrix();
  30107. this._absoluteTransform = new BABYLON.Matrix();
  30108. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30109. this._scaleMatrix = BABYLON.Matrix.Identity();
  30110. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30111. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30112. this._scalingDeterminant = 1;
  30113. this._syncScaleVector = function () {
  30114. var lm = this.getLocalMatrix();
  30115. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30116. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30117. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30118. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30119. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30120. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30121. this._scaleVector.x = xs * Math.sqrt(xsq);
  30122. this._scaleVector.y = ys * Math.sqrt(ysq);
  30123. this._scaleVector.z = zs * Math.sqrt(zsq);
  30124. if (this._parent) {
  30125. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30126. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30127. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30128. }
  30129. 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);
  30130. };
  30131. this._skeleton = skeleton;
  30132. this._matrix = matrix;
  30133. this._baseMatrix = matrix;
  30134. this._restPose = restPose ? restPose : matrix.clone();
  30135. skeleton.bones.push(this);
  30136. if (parentBone) {
  30137. this._parent = parentBone;
  30138. parentBone.children.push(this);
  30139. }
  30140. else {
  30141. this._parent = null;
  30142. }
  30143. this._updateDifferenceMatrix();
  30144. if (this.getAbsoluteTransform().determinant() < 0) {
  30145. this._scalingDeterminant *= -1;
  30146. }
  30147. }
  30148. // Members
  30149. Bone.prototype.getParent = function () {
  30150. return this._parent;
  30151. };
  30152. Bone.prototype.getLocalMatrix = function () {
  30153. return this._matrix;
  30154. };
  30155. Bone.prototype.getBaseMatrix = function () {
  30156. return this._baseMatrix;
  30157. };
  30158. Bone.prototype.getRestPose = function () {
  30159. return this._restPose;
  30160. };
  30161. Bone.prototype.returnToRest = function () {
  30162. this.updateMatrix(this._restPose.clone());
  30163. };
  30164. Bone.prototype.getWorldMatrix = function () {
  30165. return this._worldTransform;
  30166. };
  30167. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30168. return this._invertedAbsoluteTransform;
  30169. };
  30170. Bone.prototype.getAbsoluteTransform = function () {
  30171. return this._absoluteTransform;
  30172. };
  30173. // Methods
  30174. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30175. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30176. this._baseMatrix = matrix.clone();
  30177. this._matrix = matrix.clone();
  30178. this._skeleton._markAsDirty();
  30179. if (updateDifferenceMatrix) {
  30180. this._updateDifferenceMatrix();
  30181. }
  30182. };
  30183. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30184. if (!rootMatrix) {
  30185. rootMatrix = this._baseMatrix;
  30186. }
  30187. if (this._parent) {
  30188. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30189. }
  30190. else {
  30191. this._absoluteTransform.copyFrom(rootMatrix);
  30192. }
  30193. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30194. for (var index = 0; index < this.children.length; index++) {
  30195. this.children[index]._updateDifferenceMatrix();
  30196. }
  30197. };
  30198. Bone.prototype.markAsDirty = function () {
  30199. this._currentRenderId++;
  30200. this._skeleton._markAsDirty();
  30201. };
  30202. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30203. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30204. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30205. // all animation may be coming from a library skeleton, so may need to create animation
  30206. if (this.animations.length === 0) {
  30207. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30208. this.animations[0].setKeys([]);
  30209. }
  30210. // get animation info / verify there is such a range from the source bone
  30211. var sourceRange = source.animations[0].getRange(rangeName);
  30212. if (!sourceRange) {
  30213. return false;
  30214. }
  30215. var from = sourceRange.from;
  30216. var to = sourceRange.to;
  30217. var sourceKeys = source.animations[0].getKeys();
  30218. // rescaling prep
  30219. var sourceBoneLength = source.length;
  30220. var sourceParent = source.getParent();
  30221. var parent = this.getParent();
  30222. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30223. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30224. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30225. var destKeys = this.animations[0].getKeys();
  30226. // loop vars declaration
  30227. var orig;
  30228. var origTranslation;
  30229. var mat;
  30230. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30231. orig = sourceKeys[key];
  30232. if (orig.frame >= from && orig.frame <= to) {
  30233. if (rescaleAsRequired) {
  30234. mat = orig.value.clone();
  30235. // scale based on parent ratio, when bone has parent
  30236. if (parentScalingReqd) {
  30237. origTranslation = mat.getTranslation();
  30238. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30239. }
  30240. else if (dimensionsScalingReqd) {
  30241. origTranslation = mat.getTranslation();
  30242. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30243. }
  30244. else {
  30245. mat = orig.value;
  30246. }
  30247. }
  30248. else {
  30249. mat = orig.value;
  30250. }
  30251. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30252. }
  30253. }
  30254. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30255. return true;
  30256. };
  30257. Bone.prototype.translate = function (vec, space, mesh) {
  30258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30259. var lm = this.getLocalMatrix();
  30260. if (space == BABYLON.Space.LOCAL) {
  30261. lm.m[12] += vec.x;
  30262. lm.m[13] += vec.y;
  30263. lm.m[14] += vec.z;
  30264. }
  30265. else {
  30266. this._skeleton.computeAbsoluteTransforms();
  30267. var tmat = BABYLON.Tmp.Matrix[0];
  30268. var tvec = BABYLON.Tmp.Vector3[0];
  30269. if (mesh) {
  30270. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30271. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30272. }
  30273. else {
  30274. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30275. }
  30276. tmat.m[12] = 0;
  30277. tmat.m[13] = 0;
  30278. tmat.m[14] = 0;
  30279. tmat.invert();
  30280. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30281. lm.m[12] += tvec.x;
  30282. lm.m[13] += tvec.y;
  30283. lm.m[14] += tvec.z;
  30284. }
  30285. this.markAsDirty();
  30286. };
  30287. Bone.prototype.setPosition = function (position, space, mesh) {
  30288. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30289. var lm = this.getLocalMatrix();
  30290. if (space == BABYLON.Space.LOCAL) {
  30291. lm.m[12] = position.x;
  30292. lm.m[13] = position.y;
  30293. lm.m[14] = position.z;
  30294. }
  30295. else {
  30296. this._skeleton.computeAbsoluteTransforms();
  30297. var tmat = BABYLON.Tmp.Matrix[0];
  30298. var vec = BABYLON.Tmp.Vector3[0];
  30299. if (mesh) {
  30300. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30301. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30302. }
  30303. else {
  30304. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30305. }
  30306. tmat.invert();
  30307. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30308. lm.m[12] = vec.x;
  30309. lm.m[13] = vec.y;
  30310. lm.m[14] = vec.z;
  30311. }
  30312. this.markAsDirty();
  30313. };
  30314. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30315. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30316. };
  30317. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30318. if (scaleChildren === void 0) { scaleChildren = false; }
  30319. if (this.animations[0] && !this.animations[0].isStopped()) {
  30320. if (!scaleChildren) {
  30321. this._negateScaleChildren.x = 1 / x;
  30322. this._negateScaleChildren.y = 1 / y;
  30323. this._negateScaleChildren.z = 1 / z;
  30324. }
  30325. this._syncScaleVector();
  30326. }
  30327. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30328. };
  30329. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30330. if (scaleChildren === void 0) { scaleChildren = false; }
  30331. var locMat = this.getLocalMatrix();
  30332. var origLocMat = BABYLON.Tmp.Matrix[0];
  30333. origLocMat.copyFrom(locMat);
  30334. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30335. origLocMatInv.copyFrom(origLocMat);
  30336. origLocMatInv.invert();
  30337. var scaleMat = BABYLON.Tmp.Matrix[2];
  30338. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30339. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30340. this._scaleVector.x *= x;
  30341. this._scaleVector.y *= y;
  30342. this._scaleVector.z *= z;
  30343. locMat.multiplyToRef(origLocMatInv, locMat);
  30344. locMat.multiplyToRef(scaleMat, locMat);
  30345. locMat.multiplyToRef(origLocMat, locMat);
  30346. var parent = this.getParent();
  30347. if (parent) {
  30348. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30349. }
  30350. else {
  30351. this.getAbsoluteTransform().copyFrom(locMat);
  30352. }
  30353. var len = this.children.length;
  30354. scaleMat.invert();
  30355. for (var i = 0; i < len; i++) {
  30356. var child = this.children[i];
  30357. var cm = child.getLocalMatrix();
  30358. cm.multiplyToRef(scaleMat, cm);
  30359. var lm = child.getLocalMatrix();
  30360. lm.m[12] *= x;
  30361. lm.m[13] *= y;
  30362. lm.m[14] *= z;
  30363. }
  30364. this.computeAbsoluteTransforms();
  30365. if (scaleChildren) {
  30366. for (var i = 0; i < len; i++) {
  30367. this.children[i].scale(x, y, z, scaleChildren);
  30368. }
  30369. }
  30370. this.markAsDirty();
  30371. };
  30372. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30374. var rotMat = BABYLON.Tmp.Matrix[0];
  30375. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30376. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30377. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30378. rotMatInv.multiplyToRef(rotMat, rotMat);
  30379. this._rotateWithMatrix(rotMat, space, mesh);
  30380. };
  30381. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30383. var rmat = BABYLON.Tmp.Matrix[0];
  30384. rmat.m[12] = 0;
  30385. rmat.m[13] = 0;
  30386. rmat.m[14] = 0;
  30387. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30388. this._rotateWithMatrix(rmat, space, mesh);
  30389. };
  30390. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30392. var rotMat = BABYLON.Tmp.Matrix[0];
  30393. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30394. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30395. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30396. rotMatInv.multiplyToRef(rotMat, rotMat);
  30397. this._rotateWithMatrix(rotMat, space, mesh);
  30398. };
  30399. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30401. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30402. };
  30403. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30405. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30406. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30407. var rotMat = BABYLON.Tmp.Matrix[1];
  30408. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30409. rotMatInv.multiplyToRef(rotMat, rotMat);
  30410. this._rotateWithMatrix(rotMat, space, mesh);
  30411. };
  30412. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30414. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30415. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30416. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30417. rotMat2.copyFrom(rotMat);
  30418. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30419. this._rotateWithMatrix(rotMat2, space, mesh);
  30420. };
  30421. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30423. var lmat = this.getLocalMatrix();
  30424. var lx = lmat.m[12];
  30425. var ly = lmat.m[13];
  30426. var lz = lmat.m[14];
  30427. var parent = this.getParent();
  30428. var parentScale = BABYLON.Tmp.Matrix[3];
  30429. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30430. if (parent) {
  30431. if (space == BABYLON.Space.WORLD) {
  30432. if (mesh) {
  30433. parentScale.copyFrom(mesh.getWorldMatrix());
  30434. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30435. }
  30436. else {
  30437. parentScale.copyFrom(parent.getAbsoluteTransform());
  30438. }
  30439. }
  30440. else {
  30441. parentScale = parent._scaleMatrix;
  30442. }
  30443. parentScaleInv.copyFrom(parentScale);
  30444. parentScaleInv.invert();
  30445. lmat.multiplyToRef(parentScale, lmat);
  30446. lmat.multiplyToRef(rmat, lmat);
  30447. lmat.multiplyToRef(parentScaleInv, lmat);
  30448. }
  30449. else {
  30450. if (space == BABYLON.Space.WORLD && mesh) {
  30451. parentScale.copyFrom(mesh.getWorldMatrix());
  30452. parentScaleInv.copyFrom(parentScale);
  30453. parentScaleInv.invert();
  30454. lmat.multiplyToRef(parentScale, lmat);
  30455. lmat.multiplyToRef(rmat, lmat);
  30456. lmat.multiplyToRef(parentScaleInv, lmat);
  30457. }
  30458. else {
  30459. lmat.multiplyToRef(rmat, lmat);
  30460. }
  30461. }
  30462. lmat.m[12] = lx;
  30463. lmat.m[13] = ly;
  30464. lmat.m[14] = lz;
  30465. this.computeAbsoluteTransforms();
  30466. this.markAsDirty();
  30467. };
  30468. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30470. if (space == BABYLON.Space.WORLD) {
  30471. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30472. scaleMatrix.copyFrom(this._scaleMatrix);
  30473. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30474. if (mesh) {
  30475. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30476. var meshScale = BABYLON.Tmp.Matrix[3];
  30477. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30478. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30479. }
  30480. rotMatInv.invert();
  30481. scaleMatrix.m[0] *= this._scalingDeterminant;
  30482. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30483. }
  30484. else {
  30485. rotMatInv.copyFrom(this.getLocalMatrix());
  30486. rotMatInv.invert();
  30487. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30488. scaleMatrix.copyFrom(this._scaleMatrix);
  30489. if (this._parent) {
  30490. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30491. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30492. pscaleMatrix.invert();
  30493. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30494. }
  30495. else {
  30496. scaleMatrix.m[0] *= this._scalingDeterminant;
  30497. }
  30498. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30499. }
  30500. };
  30501. Bone.prototype.getScale = function () {
  30502. return this._scaleVector.clone();
  30503. };
  30504. Bone.prototype.getScaleToRef = function (result) {
  30505. result.copyFrom(this._scaleVector);
  30506. };
  30507. Bone.prototype.getPosition = function (space, mesh) {
  30508. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30509. var pos = BABYLON.Vector3.Zero();
  30510. this.getPositionToRef(space, mesh, pos);
  30511. return pos;
  30512. };
  30513. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30514. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30515. if (space == BABYLON.Space.LOCAL) {
  30516. var lm = this.getLocalMatrix();
  30517. result.x = lm.m[12];
  30518. result.y = lm.m[13];
  30519. result.z = lm.m[14];
  30520. }
  30521. else {
  30522. this._skeleton.computeAbsoluteTransforms();
  30523. var tmat = BABYLON.Tmp.Matrix[0];
  30524. if (mesh) {
  30525. tmat.copyFrom(this.getAbsoluteTransform());
  30526. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30527. }
  30528. else {
  30529. tmat = this.getAbsoluteTransform();
  30530. }
  30531. result.x = tmat.m[12];
  30532. result.y = tmat.m[13];
  30533. result.z = tmat.m[14];
  30534. }
  30535. };
  30536. Bone.prototype.getAbsolutePosition = function (mesh) {
  30537. var pos = BABYLON.Vector3.Zero();
  30538. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30539. return pos;
  30540. };
  30541. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30542. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30543. };
  30544. Bone.prototype.computeAbsoluteTransforms = function () {
  30545. if (this._parent) {
  30546. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30547. }
  30548. else {
  30549. this._absoluteTransform.copyFrom(this._matrix);
  30550. var poseMatrix = this._skeleton.getPoseMatrix();
  30551. if (poseMatrix) {
  30552. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30553. }
  30554. }
  30555. var children = this.children;
  30556. var len = children.length;
  30557. for (var i = 0; i < len; i++) {
  30558. children[i].computeAbsoluteTransforms();
  30559. }
  30560. };
  30561. Bone.prototype.getDirection = function (localAxis, mesh) {
  30562. var result = BABYLON.Vector3.Zero();
  30563. this.getDirectionToRef(localAxis, mesh, result);
  30564. return result;
  30565. };
  30566. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30567. this._skeleton.computeAbsoluteTransforms();
  30568. var mat = BABYLON.Tmp.Matrix[0];
  30569. mat.copyFrom(this.getAbsoluteTransform());
  30570. if (mesh) {
  30571. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30572. }
  30573. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30574. result.normalize();
  30575. };
  30576. Bone.prototype.getRotation = function (space, mesh) {
  30577. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30578. var result = BABYLON.Vector3.Zero();
  30579. this.getRotationToRef(space, mesh, result);
  30580. return result;
  30581. };
  30582. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30584. var quat = BABYLON.Tmp.Quaternion[0];
  30585. this.getRotationQuaternionToRef(space, mesh, quat);
  30586. quat.toEulerAnglesToRef(result);
  30587. };
  30588. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30590. var result = BABYLON.Quaternion.Identity();
  30591. this.getRotationQuaternionToRef(space, mesh, result);
  30592. return result;
  30593. };
  30594. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30596. if (space == BABYLON.Space.LOCAL) {
  30597. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30598. }
  30599. else {
  30600. var mat = BABYLON.Tmp.Matrix[0];
  30601. var amat = this.getAbsoluteTransform();
  30602. if (mesh) {
  30603. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30604. }
  30605. else {
  30606. mat.copyFrom(amat);
  30607. }
  30608. mat.m[0] *= this._scalingDeterminant;
  30609. mat.m[1] *= this._scalingDeterminant;
  30610. mat.m[2] *= this._scalingDeterminant;
  30611. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30612. }
  30613. };
  30614. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30616. var result = BABYLON.Matrix.Identity();
  30617. this.getRotationMatrixToRef(space, mesh, result);
  30618. return result;
  30619. };
  30620. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30622. if (space == BABYLON.Space.LOCAL) {
  30623. this.getLocalMatrix().getRotationMatrixToRef(result);
  30624. }
  30625. else {
  30626. var mat = BABYLON.Tmp.Matrix[0];
  30627. var amat = this.getAbsoluteTransform();
  30628. if (mesh) {
  30629. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30630. }
  30631. else {
  30632. mat.copyFrom(amat);
  30633. }
  30634. mat.m[0] *= this._scalingDeterminant;
  30635. mat.m[1] *= this._scalingDeterminant;
  30636. mat.m[2] *= this._scalingDeterminant;
  30637. mat.getRotationMatrixToRef(result);
  30638. }
  30639. };
  30640. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30641. var result = BABYLON.Vector3.Zero();
  30642. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30643. return result;
  30644. };
  30645. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30646. this._skeleton.computeAbsoluteTransforms();
  30647. var tmat = BABYLON.Tmp.Matrix[0];
  30648. if (mesh) {
  30649. tmat.copyFrom(this.getAbsoluteTransform());
  30650. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30651. }
  30652. else {
  30653. tmat = this.getAbsoluteTransform();
  30654. }
  30655. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30656. };
  30657. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30658. var result = BABYLON.Vector3.Zero();
  30659. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30660. return result;
  30661. };
  30662. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30663. this._skeleton.computeAbsoluteTransforms();
  30664. var tmat = BABYLON.Tmp.Matrix[0];
  30665. tmat.copyFrom(this.getAbsoluteTransform());
  30666. if (mesh) {
  30667. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30668. }
  30669. tmat.invert();
  30670. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30671. };
  30672. return Bone;
  30673. }(BABYLON.Node));
  30674. BABYLON.Bone = Bone;
  30675. })(BABYLON || (BABYLON = {}));
  30676. //# sourceMappingURL=babylon.bone.js.map
  30677. var BABYLON;
  30678. (function (BABYLON) {
  30679. var BoneIKController = (function () {
  30680. function BoneIKController(mesh, bone, options) {
  30681. this.targetPosition = BABYLON.Vector3.Zero();
  30682. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30683. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30684. this.poleAngle = 0;
  30685. this.slerpAmount = 1;
  30686. this._bone1Quat = BABYLON.Quaternion.Identity();
  30687. this._bone1Mat = BABYLON.Matrix.Identity();
  30688. this._bone2Ang = Math.PI;
  30689. this._maxAngle = Math.PI;
  30690. this._tmpVec1 = BABYLON.Vector3.Zero();
  30691. this._tmpVec2 = BABYLON.Vector3.Zero();
  30692. this._tmpVec3 = BABYLON.Vector3.Zero();
  30693. this._tmpVec4 = BABYLON.Vector3.Zero();
  30694. this._tmpVec5 = BABYLON.Vector3.Zero();
  30695. this._tmpMat1 = BABYLON.Matrix.Identity();
  30696. this._tmpMat2 = BABYLON.Matrix.Identity();
  30697. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30698. this._rightHandedSystem = false;
  30699. this._bendAxis = BABYLON.Vector3.Right();
  30700. this._slerping = false;
  30701. this._bone2 = bone;
  30702. this._bone1 = bone.getParent();
  30703. this.mesh = mesh;
  30704. if (bone.getAbsoluteTransform().determinant() > 0) {
  30705. this._rightHandedSystem = true;
  30706. this._bendAxis.x = 0;
  30707. this._bendAxis.y = 0;
  30708. this._bendAxis.z = 1;
  30709. }
  30710. if (this._bone1.length) {
  30711. var boneScale1 = this._bone1.getScale();
  30712. var boneScale2 = this._bone2.getScale();
  30713. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30714. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30715. }
  30716. else if (this._bone1.children[0]) {
  30717. mesh.computeWorldMatrix(true);
  30718. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30719. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30720. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30721. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30722. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30723. }
  30724. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30725. this.maxAngle = Math.PI;
  30726. if (options) {
  30727. if (options.targetMesh) {
  30728. this.targetMesh = options.targetMesh;
  30729. this.targetMesh.computeWorldMatrix(true);
  30730. }
  30731. if (options.poleTargetMesh) {
  30732. this.poleTargetMesh = options.poleTargetMesh;
  30733. this.poleTargetMesh.computeWorldMatrix(true);
  30734. }
  30735. else if (options.poleTargetBone) {
  30736. this.poleTargetBone = options.poleTargetBone;
  30737. }
  30738. else if (this._bone1.getParent()) {
  30739. this.poleTargetBone = this._bone1.getParent();
  30740. }
  30741. if (options.poleTargetLocalOffset) {
  30742. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30743. }
  30744. if (options.poleAngle) {
  30745. this.poleAngle = options.poleAngle;
  30746. }
  30747. if (options.bendAxis) {
  30748. this._bendAxis.copyFrom(options.bendAxis);
  30749. }
  30750. if (options.maxAngle) {
  30751. this.maxAngle = options.maxAngle;
  30752. }
  30753. if (options.slerpAmount) {
  30754. this.slerpAmount = options.slerpAmount;
  30755. }
  30756. }
  30757. }
  30758. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30759. get: function () {
  30760. return this._maxAngle;
  30761. },
  30762. set: function (value) {
  30763. this._setMaxAngle(value);
  30764. },
  30765. enumerable: true,
  30766. configurable: true
  30767. });
  30768. BoneIKController.prototype._setMaxAngle = function (ang) {
  30769. if (ang < 0) {
  30770. ang = 0;
  30771. }
  30772. if (ang > Math.PI || ang == undefined) {
  30773. ang = Math.PI;
  30774. }
  30775. this._maxAngle = ang;
  30776. var a = this._bone1Length;
  30777. var b = this._bone2Length;
  30778. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30779. };
  30780. BoneIKController.prototype.update = function () {
  30781. var bone1 = this._bone1;
  30782. var target = this.targetPosition;
  30783. var poleTarget = this.poleTargetPosition;
  30784. var mat1 = this._tmpMat1;
  30785. var mat2 = this._tmpMat2;
  30786. if (this.targetMesh) {
  30787. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30788. }
  30789. if (this.poleTargetBone) {
  30790. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30791. }
  30792. else if (this.poleTargetMesh) {
  30793. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30794. }
  30795. var bonePos = this._tmpVec1;
  30796. var zaxis = this._tmpVec2;
  30797. var xaxis = this._tmpVec3;
  30798. var yaxis = this._tmpVec4;
  30799. var upAxis = this._tmpVec5;
  30800. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30801. poleTarget.subtractToRef(bonePos, upAxis);
  30802. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30803. upAxis.y = 1;
  30804. }
  30805. else {
  30806. upAxis.normalize();
  30807. }
  30808. target.subtractToRef(bonePos, yaxis);
  30809. yaxis.normalize();
  30810. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30811. zaxis.normalize();
  30812. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30813. xaxis.normalize();
  30814. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30815. var a = this._bone1Length;
  30816. var b = this._bone2Length;
  30817. var c = BABYLON.Vector3.Distance(bonePos, target);
  30818. if (this._maxReach > 0) {
  30819. c = Math.min(this._maxReach, c);
  30820. }
  30821. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30822. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30823. if (acosa > 1) {
  30824. acosa = 1;
  30825. }
  30826. if (acosb > 1) {
  30827. acosb = 1;
  30828. }
  30829. if (acosa < -1) {
  30830. acosa = -1;
  30831. }
  30832. if (acosb < -1) {
  30833. acosb = -1;
  30834. }
  30835. var angA = Math.acos(acosa);
  30836. var angB = Math.acos(acosb);
  30837. var angC = -angA - angB;
  30838. if (this._rightHandedSystem) {
  30839. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30840. mat2.multiplyToRef(mat1, mat1);
  30841. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30842. mat2.multiplyToRef(mat1, mat1);
  30843. }
  30844. else {
  30845. this._tmpVec1.copyFrom(this._bendAxis);
  30846. this._tmpVec1.x *= -1;
  30847. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30848. mat2.multiplyToRef(mat1, mat1);
  30849. }
  30850. if (this.poleAngle) {
  30851. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30852. mat1.multiplyToRef(mat2, mat1);
  30853. }
  30854. if (this.slerpAmount < 1) {
  30855. if (!this._slerping) {
  30856. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30857. }
  30858. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30859. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30860. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30861. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30862. this._slerping = true;
  30863. }
  30864. else {
  30865. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30866. this._bone1Mat.copyFrom(mat1);
  30867. this._slerping = false;
  30868. }
  30869. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30870. this._bone2Ang = angC;
  30871. };
  30872. return BoneIKController;
  30873. }());
  30874. BABYLON.BoneIKController = BoneIKController;
  30875. })(BABYLON || (BABYLON = {}));
  30876. //# sourceMappingURL=babylon.boneIKController.js.map
  30877. var BABYLON;
  30878. (function (BABYLON) {
  30879. var BoneLookController = (function () {
  30880. function BoneLookController(mesh, bone, target, options) {
  30881. this.upAxis = BABYLON.Vector3.Up();
  30882. this.adjustYaw = 0;
  30883. this.adjustPitch = 0;
  30884. this.adjustRoll = 0;
  30885. this._tmpVec1 = BABYLON.Vector3.Zero();
  30886. this._tmpVec2 = BABYLON.Vector3.Zero();
  30887. this._tmpVec3 = BABYLON.Vector3.Zero();
  30888. this._tmpVec4 = BABYLON.Vector3.Zero();
  30889. this._tmpMat1 = BABYLON.Matrix.Identity();
  30890. this._tmpMat2 = BABYLON.Matrix.Identity();
  30891. this.mesh = mesh;
  30892. this.bone = bone;
  30893. this.target = target;
  30894. if (options) {
  30895. if (options.adjustYaw) {
  30896. this.adjustYaw = options.adjustYaw;
  30897. }
  30898. if (options.adjustPitch) {
  30899. this.adjustPitch = options.adjustPitch;
  30900. }
  30901. if (options.adjustRoll) {
  30902. this.adjustRoll = options.adjustRoll;
  30903. }
  30904. }
  30905. }
  30906. BoneLookController.prototype.update = function () {
  30907. var bone = this.bone;
  30908. var target = this.target;
  30909. var bonePos = this._tmpVec1;
  30910. var zaxis = this._tmpVec2;
  30911. var xaxis = this._tmpVec3;
  30912. var yaxis = this._tmpVec4;
  30913. var mat1 = this._tmpMat1;
  30914. var mat2 = this._tmpMat2;
  30915. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30916. target.subtractToRef(bonePos, zaxis);
  30917. zaxis.normalize();
  30918. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30919. xaxis.normalize();
  30920. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30921. yaxis.normalize();
  30922. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30923. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30924. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30925. mat2.multiplyToRef(mat1, mat1);
  30926. }
  30927. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30928. };
  30929. return BoneLookController;
  30930. }());
  30931. BABYLON.BoneLookController = BoneLookController;
  30932. })(BABYLON || (BABYLON = {}));
  30933. //# sourceMappingURL=babylon.boneLookController.js.map
  30934. var BABYLON;
  30935. (function (BABYLON) {
  30936. var Skeleton = (function () {
  30937. function Skeleton(name, id, scene) {
  30938. this.name = name;
  30939. this.id = id;
  30940. this.bones = new Array();
  30941. this.needInitialSkinMatrix = false;
  30942. this._isDirty = true;
  30943. this._meshesWithPoseMatrix = new Array();
  30944. this._identity = BABYLON.Matrix.Identity();
  30945. this._ranges = {};
  30946. this._lastAbsoluteTransformsUpdateId = -1;
  30947. this.bones = [];
  30948. this._scene = scene;
  30949. scene.skeletons.push(this);
  30950. //make sure it will recalculate the matrix next time prepare is called.
  30951. this._isDirty = true;
  30952. }
  30953. // Members
  30954. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30955. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30956. return mesh._bonesTransformMatrices;
  30957. }
  30958. if (!this._transformMatrices) {
  30959. this.prepare();
  30960. }
  30961. return this._transformMatrices;
  30962. };
  30963. Skeleton.prototype.getScene = function () {
  30964. return this._scene;
  30965. };
  30966. // Methods
  30967. /**
  30968. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30969. */
  30970. Skeleton.prototype.toString = function (fullDetails) {
  30971. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  30972. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30973. if (fullDetails) {
  30974. ret += ", Ranges: {";
  30975. var first = true;
  30976. for (var name_1 in this._ranges) {
  30977. if (first) {
  30978. ret += ", ";
  30979. first = false;
  30980. }
  30981. ret += name_1;
  30982. }
  30983. ret += "}";
  30984. }
  30985. return ret;
  30986. };
  30987. /**
  30988. * Get bone's index searching by name
  30989. * @param {string} name is bone's name to search for
  30990. * @return {number} Indice of the bone. Returns -1 if not found
  30991. */
  30992. Skeleton.prototype.getBoneIndexByName = function (name) {
  30993. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  30994. if (this.bones[boneIndex].name === name) {
  30995. return boneIndex;
  30996. }
  30997. }
  30998. return -1;
  30999. };
  31000. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31001. // check name not already in use
  31002. if (!this._ranges[name]) {
  31003. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31004. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31005. if (this.bones[i].animations[0]) {
  31006. this.bones[i].animations[0].createRange(name, from, to);
  31007. }
  31008. }
  31009. }
  31010. };
  31011. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31012. if (deleteFrames === void 0) { deleteFrames = true; }
  31013. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31014. if (this.bones[i].animations[0]) {
  31015. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31016. }
  31017. }
  31018. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31019. };
  31020. Skeleton.prototype.getAnimationRange = function (name) {
  31021. return this._ranges[name];
  31022. };
  31023. /**
  31024. * Returns as an Array, all AnimationRanges defined on this skeleton
  31025. */
  31026. Skeleton.prototype.getAnimationRanges = function () {
  31027. var animationRanges = [];
  31028. var name;
  31029. var i = 0;
  31030. for (name in this._ranges) {
  31031. animationRanges[i] = this._ranges[name];
  31032. i++;
  31033. }
  31034. return animationRanges;
  31035. };
  31036. /**
  31037. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31038. */
  31039. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31040. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31041. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31042. return false;
  31043. }
  31044. var ret = true;
  31045. var frameOffset = this._getHighestAnimationFrame() + 1;
  31046. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31047. var boneDict = {};
  31048. var sourceBones = source.bones;
  31049. var nBones;
  31050. var i;
  31051. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31052. boneDict[sourceBones[i].name] = sourceBones[i];
  31053. }
  31054. if (this.bones.length !== sourceBones.length) {
  31055. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31056. ret = false;
  31057. }
  31058. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31059. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31060. var boneName = this.bones[i].name;
  31061. var sourceBone = boneDict[boneName];
  31062. if (sourceBone) {
  31063. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31064. }
  31065. else {
  31066. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31067. ret = false;
  31068. }
  31069. }
  31070. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31071. var range = source.getAnimationRange(name);
  31072. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31073. return ret;
  31074. };
  31075. Skeleton.prototype.returnToRest = function () {
  31076. for (var index = 0; index < this.bones.length; index++) {
  31077. this.bones[index].returnToRest();
  31078. }
  31079. };
  31080. Skeleton.prototype._getHighestAnimationFrame = function () {
  31081. var ret = 0;
  31082. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31083. if (this.bones[i].animations[0]) {
  31084. var highest = this.bones[i].animations[0].getHighestFrame();
  31085. if (ret < highest) {
  31086. ret = highest;
  31087. }
  31088. }
  31089. }
  31090. return ret;
  31091. };
  31092. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31093. var range = this.getAnimationRange(name);
  31094. if (!range) {
  31095. return null;
  31096. }
  31097. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31098. };
  31099. Skeleton.prototype._markAsDirty = function () {
  31100. this._isDirty = true;
  31101. };
  31102. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31103. this._meshesWithPoseMatrix.push(mesh);
  31104. };
  31105. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31106. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31107. if (index > -1) {
  31108. this._meshesWithPoseMatrix.splice(index, 1);
  31109. }
  31110. };
  31111. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31112. for (var index = 0; index < this.bones.length; index++) {
  31113. var bone = this.bones[index];
  31114. var parentBone = bone.getParent();
  31115. if (parentBone) {
  31116. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31117. }
  31118. else {
  31119. if (initialSkinMatrix) {
  31120. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31121. }
  31122. else {
  31123. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31124. }
  31125. }
  31126. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31127. }
  31128. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31129. };
  31130. Skeleton.prototype.prepare = function () {
  31131. if (!this._isDirty) {
  31132. return;
  31133. }
  31134. if (this.needInitialSkinMatrix) {
  31135. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31136. var mesh = this._meshesWithPoseMatrix[index];
  31137. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31138. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31139. }
  31140. var poseMatrix = mesh.getPoseMatrix();
  31141. // Prepare bones
  31142. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31143. var bone = this.bones[boneIndex];
  31144. if (!bone.getParent()) {
  31145. var matrix = bone.getBaseMatrix();
  31146. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31147. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31148. }
  31149. }
  31150. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31151. }
  31152. }
  31153. else {
  31154. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31155. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31156. }
  31157. this._computeTransformMatrices(this._transformMatrices, null);
  31158. }
  31159. this._isDirty = false;
  31160. this._scene._activeBones.addCount(this.bones.length, false);
  31161. };
  31162. Skeleton.prototype.getAnimatables = function () {
  31163. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31164. this._animatables = [];
  31165. for (var index = 0; index < this.bones.length; index++) {
  31166. this._animatables.push(this.bones[index]);
  31167. }
  31168. }
  31169. return this._animatables;
  31170. };
  31171. Skeleton.prototype.clone = function (name, id) {
  31172. var result = new Skeleton(name, id || name, this._scene);
  31173. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31174. for (var index = 0; index < this.bones.length; index++) {
  31175. var source = this.bones[index];
  31176. var parentBone = null;
  31177. if (source.getParent()) {
  31178. var parentIndex = this.bones.indexOf(source.getParent());
  31179. parentBone = result.bones[parentIndex];
  31180. }
  31181. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31182. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31183. }
  31184. if (this._ranges) {
  31185. result._ranges = {};
  31186. for (var rangeName in this._ranges) {
  31187. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31188. }
  31189. }
  31190. this._isDirty = true;
  31191. return result;
  31192. };
  31193. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31194. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31195. this.bones.forEach(function (bone) {
  31196. bone.animations.forEach(function (animation) {
  31197. animation.enableBlending = true;
  31198. animation.blendingSpeed = blendingSpeed;
  31199. });
  31200. });
  31201. };
  31202. Skeleton.prototype.dispose = function () {
  31203. this._meshesWithPoseMatrix = [];
  31204. // Animations
  31205. this.getScene().stopAnimation(this);
  31206. // Remove from scene
  31207. this.getScene().removeSkeleton(this);
  31208. };
  31209. Skeleton.prototype.serialize = function () {
  31210. var serializationObject = {};
  31211. serializationObject.name = this.name;
  31212. serializationObject.id = this.id;
  31213. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31214. serializationObject.bones = [];
  31215. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31216. for (var index = 0; index < this.bones.length; index++) {
  31217. var bone = this.bones[index];
  31218. var serializedBone = {
  31219. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31220. name: bone.name,
  31221. matrix: bone.getLocalMatrix().toArray(),
  31222. rest: bone.getRestPose().toArray()
  31223. };
  31224. serializationObject.bones.push(serializedBone);
  31225. if (bone.length) {
  31226. serializedBone.length = bone.length;
  31227. }
  31228. if (bone.animations && bone.animations.length > 0) {
  31229. serializedBone.animation = bone.animations[0].serialize();
  31230. }
  31231. serializationObject.ranges = [];
  31232. for (var name in this._ranges) {
  31233. var range = {};
  31234. range.name = name;
  31235. range.from = this._ranges[name].from;
  31236. range.to = this._ranges[name].to;
  31237. serializationObject.ranges.push(range);
  31238. }
  31239. }
  31240. return serializationObject;
  31241. };
  31242. Skeleton.Parse = function (parsedSkeleton, scene) {
  31243. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31244. if (parsedSkeleton.dimensionsAtRest) {
  31245. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31246. }
  31247. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31248. var index;
  31249. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31250. var parsedBone = parsedSkeleton.bones[index];
  31251. var parentBone = null;
  31252. if (parsedBone.parentBoneIndex > -1) {
  31253. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31254. }
  31255. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31256. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31257. if (parsedBone.length) {
  31258. bone.length = parsedBone.length;
  31259. }
  31260. if (parsedBone.animation) {
  31261. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31262. }
  31263. }
  31264. // placed after bones, so createAnimationRange can cascade down
  31265. if (parsedSkeleton.ranges) {
  31266. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31267. var data = parsedSkeleton.ranges[index];
  31268. skeleton.createAnimationRange(data.name, data.from, data.to);
  31269. }
  31270. }
  31271. return skeleton;
  31272. };
  31273. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31274. if (forceUpdate === void 0) { forceUpdate = false; }
  31275. var renderId = this._scene.getRenderId();
  31276. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31277. this.bones[0].computeAbsoluteTransforms();
  31278. this._lastAbsoluteTransformsUpdateId = renderId;
  31279. }
  31280. };
  31281. Skeleton.prototype.getPoseMatrix = function () {
  31282. var poseMatrix;
  31283. if (this._meshesWithPoseMatrix.length > 0) {
  31284. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31285. }
  31286. return poseMatrix;
  31287. };
  31288. return Skeleton;
  31289. }());
  31290. BABYLON.Skeleton = Skeleton;
  31291. })(BABYLON || (BABYLON = {}));
  31292. //# sourceMappingURL=babylon.skeleton.js.map
  31293. var BABYLON;
  31294. (function (BABYLON) {
  31295. var PostProcess = (function () {
  31296. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31298. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31299. this.name = name;
  31300. this.width = -1;
  31301. this.height = -1;
  31302. /*
  31303. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31304. Can only be used on a single postprocess or on the last one of a chain.
  31305. */
  31306. this.enablePixelPerfectMode = false;
  31307. this._reusable = false;
  31308. this._textures = new BABYLON.SmartArray(2);
  31309. this._currentRenderTextureInd = 0;
  31310. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31311. // Events
  31312. /**
  31313. * An event triggered when the postprocess is activated.
  31314. * @type {BABYLON.Observable}
  31315. */
  31316. this.onActivateObservable = new BABYLON.Observable();
  31317. /**
  31318. * An event triggered when the postprocess changes its size.
  31319. * @type {BABYLON.Observable}
  31320. */
  31321. this.onSizeChangedObservable = new BABYLON.Observable();
  31322. /**
  31323. * An event triggered when the postprocess applies its effect.
  31324. * @type {BABYLON.Observable}
  31325. */
  31326. this.onApplyObservable = new BABYLON.Observable();
  31327. /**
  31328. * An event triggered before rendering the postprocess
  31329. * @type {BABYLON.Observable}
  31330. */
  31331. this.onBeforeRenderObservable = new BABYLON.Observable();
  31332. /**
  31333. * An event triggered after rendering the postprocess
  31334. * @type {BABYLON.Observable}
  31335. */
  31336. this.onAfterRenderObservable = new BABYLON.Observable();
  31337. if (camera != null) {
  31338. this._camera = camera;
  31339. this._scene = camera.getScene();
  31340. camera.attachPostProcess(this);
  31341. this._engine = this._scene.getEngine();
  31342. }
  31343. else {
  31344. this._engine = engine;
  31345. }
  31346. this._options = options;
  31347. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31348. this._reusable = reusable || false;
  31349. this._textureType = textureType;
  31350. this._samplers = samplers || [];
  31351. this._samplers.push("textureSampler");
  31352. this._fragmentUrl = fragmentUrl;
  31353. this._parameters = parameters || [];
  31354. this._parameters.push("scale");
  31355. this.updateEffect(defines);
  31356. }
  31357. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31358. set: function (callback) {
  31359. if (this._onActivateObserver) {
  31360. this.onActivateObservable.remove(this._onActivateObserver);
  31361. }
  31362. this._onActivateObserver = this.onActivateObservable.add(callback);
  31363. },
  31364. enumerable: true,
  31365. configurable: true
  31366. });
  31367. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31368. set: function (callback) {
  31369. if (this._onSizeChangedObserver) {
  31370. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31371. }
  31372. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31373. },
  31374. enumerable: true,
  31375. configurable: true
  31376. });
  31377. Object.defineProperty(PostProcess.prototype, "onApply", {
  31378. set: function (callback) {
  31379. if (this._onApplyObserver) {
  31380. this.onApplyObservable.remove(this._onApplyObserver);
  31381. }
  31382. this._onApplyObserver = this.onApplyObservable.add(callback);
  31383. },
  31384. enumerable: true,
  31385. configurable: true
  31386. });
  31387. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31388. set: function (callback) {
  31389. if (this._onBeforeRenderObserver) {
  31390. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31391. }
  31392. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31393. },
  31394. enumerable: true,
  31395. configurable: true
  31396. });
  31397. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31398. set: function (callback) {
  31399. if (this._onAfterRenderObserver) {
  31400. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31401. }
  31402. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31403. },
  31404. enumerable: true,
  31405. configurable: true
  31406. });
  31407. PostProcess.prototype.updateEffect = function (defines) {
  31408. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31409. };
  31410. PostProcess.prototype.isReusable = function () {
  31411. return this._reusable;
  31412. };
  31413. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31414. PostProcess.prototype.markTextureDirty = function () {
  31415. this.width = -1;
  31416. };
  31417. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31418. camera = camera || this._camera;
  31419. var scene = camera.getScene();
  31420. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31421. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31422. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31423. var desiredWidth = this._options.width || requiredWidth;
  31424. var desiredHeight = this._options.height || requiredHeight;
  31425. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31426. if (!this._options.width) {
  31427. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31428. }
  31429. if (!this._options.height) {
  31430. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31431. }
  31432. }
  31433. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31434. if (this._textures.length > 0) {
  31435. for (var i = 0; i < this._textures.length; i++) {
  31436. this._engine._releaseTexture(this._textures.data[i]);
  31437. }
  31438. this._textures.reset();
  31439. }
  31440. this.width = desiredWidth;
  31441. this.height = desiredHeight;
  31442. var textureSize = { width: this.width, height: this.height };
  31443. var textureOptions = {
  31444. generateMipMaps: false,
  31445. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31446. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31447. samplingMode: this.renderTargetSamplingMode,
  31448. type: this._textureType
  31449. };
  31450. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31451. if (this._reusable) {
  31452. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31453. }
  31454. this.onSizeChangedObservable.notifyObservers(this);
  31455. }
  31456. if (this.enablePixelPerfectMode) {
  31457. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31458. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31459. }
  31460. else {
  31461. this._scaleRatio.copyFromFloats(1, 1);
  31462. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31463. }
  31464. this.onActivateObservable.notifyObservers(camera);
  31465. // Clear
  31466. if (this.clearColor) {
  31467. this._engine.clear(this.clearColor, true, true, true);
  31468. }
  31469. else {
  31470. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31471. }
  31472. if (this._reusable) {
  31473. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31474. }
  31475. };
  31476. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31477. get: function () {
  31478. return this._effect.isSupported;
  31479. },
  31480. enumerable: true,
  31481. configurable: true
  31482. });
  31483. PostProcess.prototype.apply = function () {
  31484. // Check
  31485. if (!this._effect.isReady())
  31486. return null;
  31487. // States
  31488. this._engine.enableEffect(this._effect);
  31489. this._engine.setState(false);
  31490. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31491. this._engine.setDepthBuffer(false);
  31492. this._engine.setDepthWrite(false);
  31493. // Texture
  31494. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31495. // Parameters
  31496. this._effect.setVector2("scale", this._scaleRatio);
  31497. this.onApplyObservable.notifyObservers(this._effect);
  31498. return this._effect;
  31499. };
  31500. PostProcess.prototype.dispose = function (camera) {
  31501. camera = camera || this._camera;
  31502. if (this._textures.length > 0) {
  31503. for (var i = 0; i < this._textures.length; i++) {
  31504. this._engine._releaseTexture(this._textures.data[i]);
  31505. }
  31506. this._textures.reset();
  31507. }
  31508. if (!camera) {
  31509. return;
  31510. }
  31511. camera.detachPostProcess(this);
  31512. var index = camera._postProcesses.indexOf(this);
  31513. if (index === 0 && camera._postProcesses.length > 0) {
  31514. this._camera._postProcesses[0].markTextureDirty();
  31515. }
  31516. this.onActivateObservable.clear();
  31517. this.onAfterRenderObservable.clear();
  31518. this.onApplyObservable.clear();
  31519. this.onBeforeRenderObservable.clear();
  31520. this.onSizeChangedObservable.clear();
  31521. };
  31522. return PostProcess;
  31523. }());
  31524. BABYLON.PostProcess = PostProcess;
  31525. })(BABYLON || (BABYLON = {}));
  31526. //# sourceMappingURL=babylon.postProcess.js.map
  31527. var BABYLON;
  31528. (function (BABYLON) {
  31529. var PostProcessManager = (function () {
  31530. function PostProcessManager(scene) {
  31531. this._vertexBuffers = {};
  31532. this._scene = scene;
  31533. }
  31534. PostProcessManager.prototype._prepareBuffers = function () {
  31535. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31536. return;
  31537. }
  31538. // VBO
  31539. var vertices = [];
  31540. vertices.push(1, 1);
  31541. vertices.push(-1, 1);
  31542. vertices.push(-1, -1);
  31543. vertices.push(1, -1);
  31544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31545. // Indices
  31546. var indices = [];
  31547. indices.push(0);
  31548. indices.push(1);
  31549. indices.push(2);
  31550. indices.push(0);
  31551. indices.push(2);
  31552. indices.push(3);
  31553. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31554. };
  31555. // Methods
  31556. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31557. var postProcesses = this._scene.activeCamera._postProcesses;
  31558. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31559. return false;
  31560. }
  31561. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31562. return true;
  31563. };
  31564. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31565. var engine = this._scene.getEngine();
  31566. for (var index = 0; index < postProcesses.length; index++) {
  31567. if (index < postProcesses.length - 1) {
  31568. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31569. }
  31570. else {
  31571. if (targetTexture) {
  31572. engine.bindFramebuffer(targetTexture);
  31573. }
  31574. else {
  31575. engine.restoreDefaultFramebuffer();
  31576. }
  31577. }
  31578. var pp = postProcesses[index];
  31579. var effect = pp.apply();
  31580. if (effect) {
  31581. pp.onBeforeRenderObservable.notifyObservers(effect);
  31582. // VBOs
  31583. this._prepareBuffers();
  31584. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31585. // Draw order
  31586. engine.draw(true, 0, 6);
  31587. pp.onAfterRenderObservable.notifyObservers(effect);
  31588. }
  31589. }
  31590. // Restore depth buffer
  31591. engine.setDepthBuffer(true);
  31592. engine.setDepthWrite(true);
  31593. };
  31594. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31595. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31596. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31597. return;
  31598. }
  31599. var engine = this._scene.getEngine();
  31600. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31601. if (index < len - 1) {
  31602. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31603. }
  31604. else {
  31605. if (targetTexture) {
  31606. engine.bindFramebuffer(targetTexture, faceIndex);
  31607. }
  31608. else {
  31609. engine.restoreDefaultFramebuffer();
  31610. }
  31611. }
  31612. if (doNotPresent) {
  31613. break;
  31614. }
  31615. var pp = postProcesses[index];
  31616. var effect = pp.apply();
  31617. if (effect) {
  31618. pp.onBeforeRenderObservable.notifyObservers(effect);
  31619. // VBOs
  31620. this._prepareBuffers();
  31621. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31622. // Draw order
  31623. engine.draw(true, 0, 6);
  31624. pp.onAfterRenderObservable.notifyObservers(effect);
  31625. }
  31626. }
  31627. // Restore depth buffer
  31628. engine.setDepthBuffer(true);
  31629. engine.setDepthWrite(true);
  31630. };
  31631. PostProcessManager.prototype.dispose = function () {
  31632. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31633. if (buffer) {
  31634. buffer.dispose();
  31635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31636. }
  31637. if (this._indexBuffer) {
  31638. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31639. this._indexBuffer = null;
  31640. }
  31641. };
  31642. return PostProcessManager;
  31643. }());
  31644. BABYLON.PostProcessManager = PostProcessManager;
  31645. })(BABYLON || (BABYLON = {}));
  31646. //# sourceMappingURL=babylon.postProcessManager.js.map
  31647. var BABYLON;
  31648. (function (BABYLON) {
  31649. var PassPostProcess = (function (_super) {
  31650. __extends(PassPostProcess, _super);
  31651. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31652. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  31653. }
  31654. return PassPostProcess;
  31655. }(BABYLON.PostProcess));
  31656. BABYLON.PassPostProcess = PassPostProcess;
  31657. })(BABYLON || (BABYLON = {}));
  31658. //# sourceMappingURL=babylon.passPostProcess.js.map
  31659. var BABYLON;
  31660. (function (BABYLON) {
  31661. /**
  31662. * This is a holder class for the physics joint created by the physics plugin.
  31663. * It holds a set of functions to control the underlying joint.
  31664. */
  31665. var PhysicsJoint = (function () {
  31666. function PhysicsJoint(type, jointData) {
  31667. this.type = type;
  31668. this.jointData = jointData;
  31669. jointData.nativeParams = jointData.nativeParams || {};
  31670. }
  31671. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31672. get: function () {
  31673. return this._physicsJoint;
  31674. },
  31675. set: function (newJoint) {
  31676. if (this._physicsJoint) {
  31677. }
  31678. this._physicsJoint = newJoint;
  31679. },
  31680. enumerable: true,
  31681. configurable: true
  31682. });
  31683. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31684. set: function (physicsPlugin) {
  31685. this._physicsPlugin = physicsPlugin;
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. /**
  31691. * Execute a function that is physics-plugin specific.
  31692. * @param {Function} func the function that will be executed.
  31693. * It accepts two parameters: the physics world and the physics joint.
  31694. */
  31695. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31696. func(this._physicsPlugin.world, this._physicsJoint);
  31697. };
  31698. //TODO check if the native joints are the same
  31699. //Joint Types
  31700. PhysicsJoint.DistanceJoint = 0;
  31701. PhysicsJoint.HingeJoint = 1;
  31702. PhysicsJoint.BallAndSocketJoint = 2;
  31703. PhysicsJoint.WheelJoint = 3;
  31704. PhysicsJoint.SliderJoint = 4;
  31705. //OIMO
  31706. PhysicsJoint.PrismaticJoint = 5;
  31707. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31708. PhysicsJoint.UniversalJoint = 6;
  31709. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31710. //Cannon
  31711. //Similar to a Ball-Joint. Different in params
  31712. PhysicsJoint.PointToPointJoint = 8;
  31713. //Cannon only at the moment
  31714. PhysicsJoint.SpringJoint = 9;
  31715. PhysicsJoint.LockJoint = 10;
  31716. return PhysicsJoint;
  31717. }());
  31718. BABYLON.PhysicsJoint = PhysicsJoint;
  31719. /**
  31720. * A class representing a physics distance joint.
  31721. */
  31722. var DistanceJoint = (function (_super) {
  31723. __extends(DistanceJoint, _super);
  31724. function DistanceJoint(jointData) {
  31725. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  31726. }
  31727. /**
  31728. * Update the predefined distance.
  31729. */
  31730. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31731. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31732. };
  31733. return DistanceJoint;
  31734. }(PhysicsJoint));
  31735. BABYLON.DistanceJoint = DistanceJoint;
  31736. var MotorEnabledJoint = (function (_super) {
  31737. __extends(MotorEnabledJoint, _super);
  31738. function MotorEnabledJoint(type, jointData) {
  31739. _super.call(this, type, jointData);
  31740. }
  31741. /**
  31742. * Set the motor values.
  31743. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31744. * @param {number} force the force to apply
  31745. * @param {number} maxForce max force for this motor.
  31746. */
  31747. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31748. this._physicsPlugin.setMotor(this, force, maxForce);
  31749. };
  31750. /**
  31751. * Set the motor's limits.
  31752. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31753. */
  31754. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31755. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31756. };
  31757. return MotorEnabledJoint;
  31758. }(PhysicsJoint));
  31759. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31760. /**
  31761. * This class represents a single hinge physics joint
  31762. */
  31763. var HingeJoint = (function (_super) {
  31764. __extends(HingeJoint, _super);
  31765. function HingeJoint(jointData) {
  31766. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  31767. }
  31768. /**
  31769. * Set the motor values.
  31770. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31771. * @param {number} force the force to apply
  31772. * @param {number} maxForce max force for this motor.
  31773. */
  31774. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31775. this._physicsPlugin.setMotor(this, force, maxForce);
  31776. };
  31777. /**
  31778. * Set the motor's limits.
  31779. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31780. */
  31781. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31782. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31783. };
  31784. return HingeJoint;
  31785. }(MotorEnabledJoint));
  31786. BABYLON.HingeJoint = HingeJoint;
  31787. /**
  31788. * This class represents a dual hinge physics joint (same as wheel joint)
  31789. */
  31790. var Hinge2Joint = (function (_super) {
  31791. __extends(Hinge2Joint, _super);
  31792. function Hinge2Joint(jointData) {
  31793. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31794. }
  31795. /**
  31796. * Set the motor values.
  31797. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31798. * @param {number} force the force to apply
  31799. * @param {number} maxForce max force for this motor.
  31800. * @param {motorIndex} the motor's index, 0 or 1.
  31801. */
  31802. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31803. if (motorIndex === void 0) { motorIndex = 0; }
  31804. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31805. };
  31806. /**
  31807. * Set the motor limits.
  31808. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31809. * @param {number} upperLimit the upper limit
  31810. * @param {number} lowerLimit lower limit
  31811. * @param {motorIndex} the motor's index, 0 or 1.
  31812. */
  31813. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31814. if (motorIndex === void 0) { motorIndex = 0; }
  31815. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31816. };
  31817. return Hinge2Joint;
  31818. }(MotorEnabledJoint));
  31819. BABYLON.Hinge2Joint = Hinge2Joint;
  31820. })(BABYLON || (BABYLON = {}));
  31821. //# sourceMappingURL=babylon.physicsJoint.js.map
  31822. var BABYLON;
  31823. (function (BABYLON) {
  31824. var PhysicsImpostor = (function () {
  31825. function PhysicsImpostor(object, type, _options, _scene) {
  31826. var _this = this;
  31827. if (_options === void 0) { _options = { mass: 0 }; }
  31828. this.object = object;
  31829. this.type = type;
  31830. this._options = _options;
  31831. this._scene = _scene;
  31832. this._bodyUpdateRequired = false;
  31833. this._onBeforePhysicsStepCallbacks = new Array();
  31834. this._onAfterPhysicsStepCallbacks = new Array();
  31835. this._onPhysicsCollideCallbacks = [];
  31836. this._deltaPosition = BABYLON.Vector3.Zero();
  31837. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31838. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31839. /**
  31840. * this function is executed by the physics engine.
  31841. */
  31842. this.beforeStep = function () {
  31843. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31844. //conjugate deltaRotation
  31845. if (_this._deltaRotationConjugated) {
  31846. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31847. }
  31848. else {
  31849. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31850. }
  31851. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31852. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31853. func(_this);
  31854. });
  31855. };
  31856. /**
  31857. * this function is executed by the physics engine.
  31858. */
  31859. this.afterStep = function () {
  31860. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31861. func(_this);
  31862. });
  31863. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31864. _this.object.position.addInPlace(_this._deltaPosition);
  31865. if (_this._deltaRotation) {
  31866. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31867. }
  31868. };
  31869. //event and body object due to cannon's event-based architecture.
  31870. this.onCollide = function (e) {
  31871. if (!_this._onPhysicsCollideCallbacks.length)
  31872. return;
  31873. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31874. if (otherImpostor) {
  31875. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31876. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31877. }).forEach(function (obj) {
  31878. obj.callback(_this, otherImpostor);
  31879. });
  31880. }
  31881. };
  31882. //sanity check!
  31883. if (!this.object) {
  31884. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31885. return;
  31886. }
  31887. //legacy support for old syntax.
  31888. if (!this._scene && object.getScene) {
  31889. this._scene = object.getScene();
  31890. }
  31891. this._physicsEngine = this._scene.getPhysicsEngine();
  31892. if (!this._physicsEngine) {
  31893. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31894. }
  31895. else {
  31896. //set the object's quaternion, if not set
  31897. if (!this.object.rotationQuaternion) {
  31898. if (this.object.rotation) {
  31899. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31900. }
  31901. else {
  31902. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31903. }
  31904. }
  31905. //default options params
  31906. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31907. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31908. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31909. this._joints = [];
  31910. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31911. if (!this.object.parent) {
  31912. this._init();
  31913. }
  31914. }
  31915. }
  31916. /**
  31917. * This function will completly initialize this impostor.
  31918. * It will create a new body - but only if this mesh has no parent.
  31919. * If it has, this impostor will not be used other than to define the impostor
  31920. * of the child mesh.
  31921. */
  31922. PhysicsImpostor.prototype._init = function () {
  31923. this._physicsEngine.removeImpostor(this);
  31924. this.physicsBody = null;
  31925. this._parent = this._parent || this._getPhysicsParent();
  31926. if (!this.parent) {
  31927. this._physicsEngine.addImpostor(this);
  31928. }
  31929. };
  31930. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31931. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31932. var parentMesh = this.object.parent;
  31933. return parentMesh.physicsImpostor;
  31934. }
  31935. return;
  31936. };
  31937. /**
  31938. * Should a new body be generated.
  31939. */
  31940. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31941. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31942. };
  31943. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31944. this.forceUpdate();
  31945. };
  31946. /**
  31947. * Force a regeneration of this or the parent's impostor's body.
  31948. * Use under cautious - This will remove all joints already implemented.
  31949. */
  31950. PhysicsImpostor.prototype.forceUpdate = function () {
  31951. this._init();
  31952. if (this.parent) {
  31953. this.parent.forceUpdate();
  31954. }
  31955. };
  31956. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31957. /*public get mesh(): AbstractMesh {
  31958. return this._mesh;
  31959. }*/
  31960. /**
  31961. * Gets the body that holds this impostor. Either its own, or its parent.
  31962. */
  31963. get: function () {
  31964. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31965. },
  31966. /**
  31967. * Set the physics body. Used mainly by the physics engine/plugin
  31968. */
  31969. set: function (physicsBody) {
  31970. if (this._physicsBody) {
  31971. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  31972. }
  31973. this._physicsBody = physicsBody;
  31974. this.resetUpdateFlags();
  31975. },
  31976. enumerable: true,
  31977. configurable: true
  31978. });
  31979. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  31980. get: function () {
  31981. return this._parent;
  31982. },
  31983. set: function (value) {
  31984. this._parent = value;
  31985. },
  31986. enumerable: true,
  31987. configurable: true
  31988. });
  31989. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  31990. this._bodyUpdateRequired = false;
  31991. };
  31992. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  31993. if (this.object.getBoundingInfo) {
  31994. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  31995. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  31996. }
  31997. else {
  31998. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  31999. }
  32000. };
  32001. PhysicsImpostor.prototype.getObjectCenter = function () {
  32002. if (this.object.getBoundingInfo) {
  32003. return this.object.getBoundingInfo().boundingBox.center;
  32004. }
  32005. else {
  32006. return this.object.position;
  32007. }
  32008. };
  32009. /**
  32010. * Get a specific parametes from the options parameter.
  32011. */
  32012. PhysicsImpostor.prototype.getParam = function (paramName) {
  32013. return this._options[paramName];
  32014. };
  32015. /**
  32016. * Sets a specific parameter in the options given to the physics plugin
  32017. */
  32018. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32019. this._options[paramName] = value;
  32020. this._bodyUpdateRequired = true;
  32021. };
  32022. /**
  32023. * Specifically change the body's mass option. Won't recreate the physics body object
  32024. */
  32025. PhysicsImpostor.prototype.setMass = function (mass) {
  32026. if (this.getParam("mass") !== mass) {
  32027. this.setParam("mass", mass);
  32028. }
  32029. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32030. };
  32031. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32032. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32033. };
  32034. /**
  32035. * Set the body's linear velocity.
  32036. */
  32037. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32038. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32039. };
  32040. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32041. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32042. };
  32043. /**
  32044. * Set the body's linear velocity.
  32045. */
  32046. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32047. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32048. };
  32049. /**
  32050. * Execute a function with the physics plugin native code.
  32051. * Provide a function the will have two variables - the world object and the physics body object.
  32052. */
  32053. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32054. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32055. };
  32056. /**
  32057. * Register a function that will be executed before the physics world is stepping forward.
  32058. */
  32059. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32060. this._onBeforePhysicsStepCallbacks.push(func);
  32061. };
  32062. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32063. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32064. if (index > -1) {
  32065. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32066. }
  32067. else {
  32068. BABYLON.Tools.Warn("Function to remove was not found");
  32069. }
  32070. };
  32071. /**
  32072. * Register a function that will be executed after the physics step
  32073. */
  32074. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32075. this._onAfterPhysicsStepCallbacks.push(func);
  32076. };
  32077. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32078. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32079. if (index > -1) {
  32080. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32081. }
  32082. else {
  32083. BABYLON.Tools.Warn("Function to remove was not found");
  32084. }
  32085. };
  32086. /**
  32087. * register a function that will be executed when this impostor collides against a different body.
  32088. */
  32089. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32090. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32091. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32092. };
  32093. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32094. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32095. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32096. if (index > -1) {
  32097. this._onPhysicsCollideCallbacks.splice(index, 1);
  32098. }
  32099. else {
  32100. BABYLON.Tools.Warn("Function to remove was not found");
  32101. }
  32102. };
  32103. /**
  32104. * Apply a force
  32105. */
  32106. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32107. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32108. };
  32109. /**
  32110. * Apply an impulse
  32111. */
  32112. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32113. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32114. };
  32115. /**
  32116. * A help function to create a joint.
  32117. */
  32118. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32119. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32120. this.addJoint(otherImpostor, joint);
  32121. };
  32122. /**
  32123. * Add a joint to this impostor with a different impostor.
  32124. */
  32125. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32126. this._joints.push({
  32127. otherImpostor: otherImpostor,
  32128. joint: joint
  32129. });
  32130. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32131. };
  32132. /**
  32133. * Will keep this body still, in a sleep mode.
  32134. */
  32135. PhysicsImpostor.prototype.sleep = function () {
  32136. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32137. };
  32138. /**
  32139. * Wake the body up.
  32140. */
  32141. PhysicsImpostor.prototype.wakeUp = function () {
  32142. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32143. };
  32144. PhysicsImpostor.prototype.clone = function (newObject) {
  32145. if (!newObject)
  32146. return null;
  32147. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32148. };
  32149. PhysicsImpostor.prototype.dispose = function () {
  32150. var _this = this;
  32151. //no dispose if no physics engine is available.
  32152. if (!this._physicsEngine) {
  32153. return;
  32154. }
  32155. this._joints.forEach(function (j) {
  32156. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32157. });
  32158. //dispose the physics body
  32159. this._physicsEngine.removeImpostor(this);
  32160. if (this.parent) {
  32161. this.parent.forceUpdate();
  32162. }
  32163. else {
  32164. }
  32165. };
  32166. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32167. this._deltaPosition.copyFrom(position);
  32168. };
  32169. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32170. if (!this._deltaRotation) {
  32171. this._deltaRotation = new BABYLON.Quaternion();
  32172. }
  32173. this._deltaRotation.copyFrom(rotation);
  32174. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32175. };
  32176. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32177. //Impostor types
  32178. PhysicsImpostor.NoImpostor = 0;
  32179. PhysicsImpostor.SphereImpostor = 1;
  32180. PhysicsImpostor.BoxImpostor = 2;
  32181. PhysicsImpostor.PlaneImpostor = 3;
  32182. PhysicsImpostor.MeshImpostor = 4;
  32183. PhysicsImpostor.CylinderImpostor = 7;
  32184. PhysicsImpostor.ParticleImpostor = 8;
  32185. PhysicsImpostor.HeightmapImpostor = 9;
  32186. return PhysicsImpostor;
  32187. }());
  32188. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32189. })(BABYLON || (BABYLON = {}));
  32190. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32191. var BABYLON;
  32192. (function (BABYLON) {
  32193. var PhysicsEngine = (function () {
  32194. function PhysicsEngine(gravity, _physicsPlugin) {
  32195. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32196. this._physicsPlugin = _physicsPlugin;
  32197. //new methods and parameters
  32198. this._impostors = [];
  32199. this._joints = [];
  32200. if (!this._physicsPlugin.isSupported()) {
  32201. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32202. + "Please make sure it is included.");
  32203. }
  32204. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32205. this.setGravity(gravity);
  32206. this.setTimeStep();
  32207. }
  32208. PhysicsEngine.prototype.setGravity = function (gravity) {
  32209. this.gravity = gravity;
  32210. this._physicsPlugin.setGravity(this.gravity);
  32211. };
  32212. /**
  32213. * Set the time step of the physics engine.
  32214. * default is 1/60.
  32215. * To slow it down, enter 1/600 for example.
  32216. * To speed it up, 1/30
  32217. * @param {number} newTimeStep the new timestep to apply to this world.
  32218. */
  32219. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32220. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32221. this._physicsPlugin.setTimeStep(newTimeStep);
  32222. };
  32223. PhysicsEngine.prototype.dispose = function () {
  32224. this._impostors.forEach(function (impostor) {
  32225. impostor.dispose();
  32226. });
  32227. this._physicsPlugin.dispose();
  32228. };
  32229. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32230. return this._physicsPlugin.name;
  32231. };
  32232. /**
  32233. * Adding a new impostor for the impostor tracking.
  32234. * This will be done by the impostor itself.
  32235. * @param {PhysicsImpostor} impostor the impostor to add
  32236. */
  32237. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32238. impostor.uniqueId = this._impostors.push(impostor);
  32239. //if no parent, generate the body
  32240. if (!impostor.parent) {
  32241. this._physicsPlugin.generatePhysicsBody(impostor);
  32242. }
  32243. };
  32244. /**
  32245. * Remove an impostor from the engine.
  32246. * This impostor and its mesh will not longer be updated by the physics engine.
  32247. * @param {PhysicsImpostor} impostor the impostor to remove
  32248. */
  32249. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32250. var index = this._impostors.indexOf(impostor);
  32251. if (index > -1) {
  32252. var removed = this._impostors.splice(index, 1);
  32253. //Is it needed?
  32254. if (removed.length) {
  32255. //this will also remove it from the world.
  32256. removed[0].physicsBody = null;
  32257. }
  32258. }
  32259. };
  32260. /**
  32261. * Add a joint to the physics engine
  32262. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32263. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32264. * @param {PhysicsJoint} the joint that will connect both impostors.
  32265. */
  32266. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32267. var impostorJoint = {
  32268. mainImpostor: mainImpostor,
  32269. connectedImpostor: connectedImpostor,
  32270. joint: joint
  32271. };
  32272. joint.physicsPlugin = this._physicsPlugin;
  32273. this._joints.push(impostorJoint);
  32274. this._physicsPlugin.generateJoint(impostorJoint);
  32275. };
  32276. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32277. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32278. return (impostorJoint.connectedImpostor === connectedImpostor
  32279. && impostorJoint.joint === joint
  32280. && impostorJoint.mainImpostor === mainImpostor);
  32281. });
  32282. if (matchingJoints.length) {
  32283. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32284. }
  32285. };
  32286. /**
  32287. * Called by the scene. no need to call it.
  32288. */
  32289. PhysicsEngine.prototype._step = function (delta) {
  32290. var _this = this;
  32291. //check if any mesh has no body / requires an update
  32292. this._impostors.forEach(function (impostor) {
  32293. if (impostor.isBodyInitRequired()) {
  32294. _this._physicsPlugin.generatePhysicsBody(impostor);
  32295. }
  32296. });
  32297. if (delta > 0.1) {
  32298. delta = 0.1;
  32299. }
  32300. else if (delta <= 0) {
  32301. delta = 1.0 / 60.0;
  32302. }
  32303. this._physicsPlugin.executeStep(delta, this._impostors);
  32304. };
  32305. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32306. return this._physicsPlugin;
  32307. };
  32308. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32309. for (var i = 0; i < this._impostors.length; ++i) {
  32310. if (this._impostors[i].object === object) {
  32311. return this._impostors[i];
  32312. }
  32313. }
  32314. };
  32315. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32316. for (var i = 0; i < this._impostors.length; ++i) {
  32317. if (this._impostors[i].physicsBody === body) {
  32318. return this._impostors[i];
  32319. }
  32320. }
  32321. };
  32322. // Statics, Legacy support.
  32323. /**
  32324. * @Deprecated
  32325. *
  32326. */
  32327. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32328. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32329. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32330. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32331. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32332. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32333. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32334. PhysicsEngine.CapsuleImpostor = -1;
  32335. PhysicsEngine.ConeImpostor = -1;
  32336. PhysicsEngine.ConvexHullImpostor = -1;
  32337. PhysicsEngine.Epsilon = 0.001;
  32338. return PhysicsEngine;
  32339. }());
  32340. BABYLON.PhysicsEngine = PhysicsEngine;
  32341. })(BABYLON || (BABYLON = {}));
  32342. //# sourceMappingURL=babylon.physicsEngine.js.map
  32343. var BABYLON;
  32344. (function (BABYLON) {
  32345. var VertexData = (function () {
  32346. function VertexData() {
  32347. }
  32348. VertexData.prototype.set = function (data, kind) {
  32349. switch (kind) {
  32350. case BABYLON.VertexBuffer.PositionKind:
  32351. this.positions = data;
  32352. break;
  32353. case BABYLON.VertexBuffer.NormalKind:
  32354. this.normals = data;
  32355. break;
  32356. case BABYLON.VertexBuffer.UVKind:
  32357. this.uvs = data;
  32358. break;
  32359. case BABYLON.VertexBuffer.UV2Kind:
  32360. this.uvs2 = data;
  32361. break;
  32362. case BABYLON.VertexBuffer.UV3Kind:
  32363. this.uvs3 = data;
  32364. break;
  32365. case BABYLON.VertexBuffer.UV4Kind:
  32366. this.uvs4 = data;
  32367. break;
  32368. case BABYLON.VertexBuffer.UV5Kind:
  32369. this.uvs5 = data;
  32370. break;
  32371. case BABYLON.VertexBuffer.UV6Kind:
  32372. this.uvs6 = data;
  32373. break;
  32374. case BABYLON.VertexBuffer.ColorKind:
  32375. this.colors = data;
  32376. break;
  32377. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32378. this.matricesIndices = data;
  32379. break;
  32380. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32381. this.matricesWeights = data;
  32382. break;
  32383. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32384. this.matricesIndicesExtra = data;
  32385. break;
  32386. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32387. this.matricesWeightsExtra = data;
  32388. break;
  32389. }
  32390. };
  32391. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32392. this._applyTo(mesh, updatable);
  32393. };
  32394. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32395. this._applyTo(geometry, updatable);
  32396. };
  32397. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32398. this._update(mesh);
  32399. };
  32400. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32401. this._update(geometry);
  32402. };
  32403. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32404. if (this.positions) {
  32405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32406. }
  32407. if (this.normals) {
  32408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32409. }
  32410. if (this.uvs) {
  32411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32412. }
  32413. if (this.uvs2) {
  32414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32415. }
  32416. if (this.uvs3) {
  32417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32418. }
  32419. if (this.uvs4) {
  32420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32421. }
  32422. if (this.uvs5) {
  32423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32424. }
  32425. if (this.uvs6) {
  32426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32427. }
  32428. if (this.colors) {
  32429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32430. }
  32431. if (this.matricesIndices) {
  32432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32433. }
  32434. if (this.matricesWeights) {
  32435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32436. }
  32437. if (this.matricesIndicesExtra) {
  32438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32439. }
  32440. if (this.matricesWeightsExtra) {
  32441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32442. }
  32443. if (this.indices) {
  32444. meshOrGeometry.setIndices(this.indices);
  32445. }
  32446. };
  32447. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32448. if (this.positions) {
  32449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32450. }
  32451. if (this.normals) {
  32452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32453. }
  32454. if (this.uvs) {
  32455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32456. }
  32457. if (this.uvs2) {
  32458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32459. }
  32460. if (this.uvs3) {
  32461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32462. }
  32463. if (this.uvs4) {
  32464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32465. }
  32466. if (this.uvs5) {
  32467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32468. }
  32469. if (this.uvs6) {
  32470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32471. }
  32472. if (this.colors) {
  32473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32474. }
  32475. if (this.matricesIndices) {
  32476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32477. }
  32478. if (this.matricesWeights) {
  32479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32480. }
  32481. if (this.matricesIndicesExtra) {
  32482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32483. }
  32484. if (this.matricesWeightsExtra) {
  32485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32486. }
  32487. if (this.indices) {
  32488. meshOrGeometry.setIndices(this.indices);
  32489. }
  32490. };
  32491. VertexData.prototype.transform = function (matrix) {
  32492. var transformed = BABYLON.Vector3.Zero();
  32493. var index;
  32494. if (this.positions) {
  32495. var position = BABYLON.Vector3.Zero();
  32496. for (index = 0; index < this.positions.length; index += 3) {
  32497. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32498. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32499. this.positions[index] = transformed.x;
  32500. this.positions[index + 1] = transformed.y;
  32501. this.positions[index + 2] = transformed.z;
  32502. }
  32503. }
  32504. if (this.normals) {
  32505. var normal = BABYLON.Vector3.Zero();
  32506. for (index = 0; index < this.normals.length; index += 3) {
  32507. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32508. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32509. this.normals[index] = transformed.x;
  32510. this.normals[index + 1] = transformed.y;
  32511. this.normals[index + 2] = transformed.z;
  32512. }
  32513. }
  32514. };
  32515. VertexData.prototype.merge = function (other) {
  32516. if (other.indices) {
  32517. if (!this.indices) {
  32518. this.indices = [];
  32519. }
  32520. var offset = this.positions ? this.positions.length / 3 : 0;
  32521. for (var index = 0; index < other.indices.length; index++) {
  32522. //TODO check type - if Int32Array!
  32523. this.indices.push(other.indices[index] + offset);
  32524. }
  32525. }
  32526. this.positions = this._mergeElement(this.positions, other.positions);
  32527. this.normals = this._mergeElement(this.normals, other.normals);
  32528. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32529. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32530. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32531. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32532. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32533. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32534. this.colors = this._mergeElement(this.colors, other.colors);
  32535. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32536. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32537. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32538. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32539. };
  32540. VertexData.prototype._mergeElement = function (source, other) {
  32541. if (!other)
  32542. return source;
  32543. if (!source)
  32544. return other;
  32545. var len = other.length + source.length;
  32546. var isSrcTypedArray = source instanceof Float32Array;
  32547. var isOthTypedArray = other instanceof Float32Array;
  32548. // use non-loop method when the source is Float32Array
  32549. if (isSrcTypedArray) {
  32550. var ret32 = new Float32Array(len);
  32551. ret32.set(source);
  32552. ret32.set(other, source.length);
  32553. return ret32;
  32554. }
  32555. else if (!isOthTypedArray) {
  32556. return source.concat(other);
  32557. }
  32558. else {
  32559. var ret = source.slice(0); // copy source to a separate array
  32560. for (var i = 0, len = other.length; i < len; i++) {
  32561. ret.push(other[i]);
  32562. }
  32563. return ret;
  32564. }
  32565. };
  32566. VertexData.prototype.serialize = function () {
  32567. var serializationObject = this.serialize();
  32568. if (this.positions) {
  32569. serializationObject.positions = this.positions;
  32570. }
  32571. if (this.normals) {
  32572. serializationObject.normals = this.normals;
  32573. }
  32574. if (this.uvs) {
  32575. serializationObject.uvs = this.uvs;
  32576. }
  32577. if (this.uvs2) {
  32578. serializationObject.uvs2 = this.uvs2;
  32579. }
  32580. if (this.uvs3) {
  32581. serializationObject.uvs3 = this.uvs3;
  32582. }
  32583. if (this.uvs4) {
  32584. serializationObject.uvs4 = this.uvs4;
  32585. }
  32586. if (this.uvs5) {
  32587. serializationObject.uvs5 = this.uvs5;
  32588. }
  32589. if (this.uvs6) {
  32590. serializationObject.uvs6 = this.uvs6;
  32591. }
  32592. if (this.colors) {
  32593. serializationObject.colors = this.colors;
  32594. }
  32595. if (this.matricesIndices) {
  32596. serializationObject.matricesIndices = this.matricesIndices;
  32597. serializationObject.matricesIndices._isExpanded = true;
  32598. }
  32599. if (this.matricesWeights) {
  32600. serializationObject.matricesWeights = this.matricesWeights;
  32601. }
  32602. if (this.matricesIndicesExtra) {
  32603. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32604. serializationObject.matricesIndicesExtra._isExpanded = true;
  32605. }
  32606. if (this.matricesWeightsExtra) {
  32607. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32608. }
  32609. serializationObject.indices = this.indices;
  32610. return serializationObject;
  32611. };
  32612. // Statics
  32613. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32614. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32615. };
  32616. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32617. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32618. };
  32619. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32620. var result = new VertexData();
  32621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32622. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32623. }
  32624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32625. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32626. }
  32627. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32628. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32629. }
  32630. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32631. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32632. }
  32633. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32634. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32635. }
  32636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32637. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32638. }
  32639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32640. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32641. }
  32642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32643. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32644. }
  32645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32646. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32647. }
  32648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32649. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32650. }
  32651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32652. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32653. }
  32654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32655. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32656. }
  32657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32658. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32659. }
  32660. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32661. return result;
  32662. };
  32663. VertexData.CreateRibbon = function (options) {
  32664. var pathArray = options.pathArray;
  32665. var closeArray = options.closeArray || false;
  32666. var closePath = options.closePath || false;
  32667. var invertUV = options.invertUV || false;
  32668. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32669. var offset = options.offset || defaultOffset;
  32670. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32671. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32672. var positions = [];
  32673. var indices = [];
  32674. var normals = [];
  32675. var uvs = [];
  32676. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32677. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32678. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32679. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32680. var minlg; // minimal length among all paths from pathArray
  32681. var lg = []; // array of path lengths : nb of vertex per path
  32682. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32683. var p; // path iterator
  32684. var i; // point iterator
  32685. var j; // point iterator
  32686. // if single path in pathArray
  32687. if (pathArray.length < 2) {
  32688. var ar1 = [];
  32689. var ar2 = [];
  32690. for (i = 0; i < pathArray[0].length - offset; i++) {
  32691. ar1.push(pathArray[0][i]);
  32692. ar2.push(pathArray[0][i + offset]);
  32693. }
  32694. pathArray = [ar1, ar2];
  32695. }
  32696. // positions and horizontal distances (u)
  32697. var idc = 0;
  32698. var closePathCorr = (closePath) ? 1 : 0;
  32699. var path;
  32700. var l;
  32701. minlg = pathArray[0].length;
  32702. var vectlg;
  32703. var dist;
  32704. for (p = 0; p < pathArray.length; p++) {
  32705. uTotalDistance[p] = 0;
  32706. us[p] = [0];
  32707. path = pathArray[p];
  32708. l = path.length;
  32709. minlg = (minlg < l) ? minlg : l;
  32710. j = 0;
  32711. while (j < l) {
  32712. positions.push(path[j].x, path[j].y, path[j].z);
  32713. if (j > 0) {
  32714. vectlg = path[j].subtract(path[j - 1]).length();
  32715. dist = vectlg + uTotalDistance[p];
  32716. us[p].push(dist);
  32717. uTotalDistance[p] = dist;
  32718. }
  32719. j++;
  32720. }
  32721. if (closePath) {
  32722. j--;
  32723. positions.push(path[0].x, path[0].y, path[0].z);
  32724. vectlg = path[j].subtract(path[0]).length();
  32725. dist = vectlg + uTotalDistance[p];
  32726. us[p].push(dist);
  32727. uTotalDistance[p] = dist;
  32728. }
  32729. lg[p] = l + closePathCorr;
  32730. idx[p] = idc;
  32731. idc += (l + closePathCorr);
  32732. }
  32733. // vertical distances (v)
  32734. var path1;
  32735. var path2;
  32736. var vertex1;
  32737. var vertex2;
  32738. for (i = 0; i < minlg + closePathCorr; i++) {
  32739. vTotalDistance[i] = 0;
  32740. vs[i] = [0];
  32741. for (p = 0; p < pathArray.length - 1; p++) {
  32742. path1 = pathArray[p];
  32743. path2 = pathArray[p + 1];
  32744. if (i === minlg) {
  32745. vertex1 = path1[0];
  32746. vertex2 = path2[0];
  32747. }
  32748. else {
  32749. vertex1 = path1[i];
  32750. vertex2 = path2[i];
  32751. }
  32752. vectlg = vertex2.subtract(vertex1).length();
  32753. dist = vectlg + vTotalDistance[i];
  32754. vs[i].push(dist);
  32755. vTotalDistance[i] = dist;
  32756. }
  32757. if (closeArray) {
  32758. path1 = pathArray[p];
  32759. path2 = pathArray[0];
  32760. if (i === minlg) {
  32761. vertex2 = path2[0];
  32762. }
  32763. vectlg = vertex2.subtract(vertex1).length();
  32764. dist = vectlg + vTotalDistance[i];
  32765. vTotalDistance[i] = dist;
  32766. }
  32767. }
  32768. // uvs
  32769. var u;
  32770. var v;
  32771. for (p = 0; p < pathArray.length; p++) {
  32772. for (i = 0; i < minlg + closePathCorr; i++) {
  32773. u = us[p][i] / uTotalDistance[p];
  32774. v = vs[i][p] / vTotalDistance[i];
  32775. if (invertUV) {
  32776. uvs.push(v, u);
  32777. }
  32778. else {
  32779. uvs.push(u, v);
  32780. }
  32781. }
  32782. }
  32783. // indices
  32784. p = 0; // path index
  32785. var pi = 0; // positions array index
  32786. var l1 = lg[p] - 1; // path1 length
  32787. var l2 = lg[p + 1] - 1; // path2 length
  32788. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32789. var shft = idx[1] - idx[0]; // shift
  32790. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32791. while (pi <= min && p < path1nb) {
  32792. // 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
  32793. indices.push(pi, pi + shft, pi + 1);
  32794. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32795. pi += 1;
  32796. if (pi === min) {
  32797. p++;
  32798. if (p === lg.length - 1) {
  32799. shft = idx[0] - idx[p];
  32800. l1 = lg[p] - 1;
  32801. l2 = lg[0] - 1;
  32802. }
  32803. else {
  32804. shft = idx[p + 1] - idx[p];
  32805. l1 = lg[p] - 1;
  32806. l2 = lg[p + 1] - 1;
  32807. }
  32808. pi = idx[p];
  32809. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32810. }
  32811. }
  32812. // normals
  32813. VertexData.ComputeNormals(positions, indices, normals);
  32814. if (closePath) {
  32815. var indexFirst = 0;
  32816. var indexLast = 0;
  32817. for (p = 0; p < pathArray.length; p++) {
  32818. indexFirst = idx[p] * 3;
  32819. if (p + 1 < pathArray.length) {
  32820. indexLast = (idx[p + 1] - 1) * 3;
  32821. }
  32822. else {
  32823. indexLast = normals.length - 3;
  32824. }
  32825. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32826. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32827. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32828. normals[indexLast] = normals[indexFirst];
  32829. normals[indexLast + 1] = normals[indexFirst + 1];
  32830. normals[indexLast + 2] = normals[indexFirst + 2];
  32831. }
  32832. }
  32833. // sides
  32834. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32835. // Result
  32836. var vertexData = new VertexData();
  32837. vertexData.indices = indices;
  32838. vertexData.positions = positions;
  32839. vertexData.normals = normals;
  32840. vertexData.uvs = uvs;
  32841. if (closePath) {
  32842. vertexData._idx = idx;
  32843. }
  32844. return vertexData;
  32845. };
  32846. VertexData.CreateBox = function (options) {
  32847. var normalsSource = [
  32848. new BABYLON.Vector3(0, 0, 1),
  32849. new BABYLON.Vector3(0, 0, -1),
  32850. new BABYLON.Vector3(1, 0, 0),
  32851. new BABYLON.Vector3(-1, 0, 0),
  32852. new BABYLON.Vector3(0, 1, 0),
  32853. new BABYLON.Vector3(0, -1, 0)
  32854. ];
  32855. var indices = [];
  32856. var positions = [];
  32857. var normals = [];
  32858. var uvs = [];
  32859. var width = options.width || options.size || 1;
  32860. var height = options.height || options.size || 1;
  32861. var depth = options.depth || options.size || 1;
  32862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32863. var faceUV = options.faceUV || new Array(6);
  32864. var faceColors = options.faceColors;
  32865. var colors = [];
  32866. // default face colors and UV if undefined
  32867. for (var f = 0; f < 6; f++) {
  32868. if (faceUV[f] === undefined) {
  32869. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32870. }
  32871. if (faceColors && faceColors[f] === undefined) {
  32872. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32873. }
  32874. }
  32875. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32876. // Create each face in turn.
  32877. for (var index = 0; index < normalsSource.length; index++) {
  32878. var normal = normalsSource[index];
  32879. // Get two vectors perpendicular to the face normal and to each other.
  32880. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32881. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32882. // Six indices (two triangles) per face.
  32883. var verticesLength = positions.length / 3;
  32884. indices.push(verticesLength);
  32885. indices.push(verticesLength + 1);
  32886. indices.push(verticesLength + 2);
  32887. indices.push(verticesLength);
  32888. indices.push(verticesLength + 2);
  32889. indices.push(verticesLength + 3);
  32890. // Four vertices per face.
  32891. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32892. positions.push(vertex.x, vertex.y, vertex.z);
  32893. normals.push(normal.x, normal.y, normal.z);
  32894. uvs.push(faceUV[index].z, faceUV[index].w);
  32895. if (faceColors) {
  32896. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32897. }
  32898. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32899. positions.push(vertex.x, vertex.y, vertex.z);
  32900. normals.push(normal.x, normal.y, normal.z);
  32901. uvs.push(faceUV[index].x, faceUV[index].w);
  32902. if (faceColors) {
  32903. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32904. }
  32905. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32906. positions.push(vertex.x, vertex.y, vertex.z);
  32907. normals.push(normal.x, normal.y, normal.z);
  32908. uvs.push(faceUV[index].x, faceUV[index].y);
  32909. if (faceColors) {
  32910. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32911. }
  32912. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32913. positions.push(vertex.x, vertex.y, vertex.z);
  32914. normals.push(normal.x, normal.y, normal.z);
  32915. uvs.push(faceUV[index].z, faceUV[index].y);
  32916. if (faceColors) {
  32917. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32918. }
  32919. }
  32920. // sides
  32921. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32922. // Result
  32923. var vertexData = new VertexData();
  32924. vertexData.indices = indices;
  32925. vertexData.positions = positions;
  32926. vertexData.normals = normals;
  32927. vertexData.uvs = uvs;
  32928. if (faceColors) {
  32929. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32930. vertexData.colors = totalColors;
  32931. }
  32932. return vertexData;
  32933. };
  32934. VertexData.CreateSphere = function (options) {
  32935. var segments = options.segments || 32;
  32936. var diameterX = options.diameterX || options.diameter || 1;
  32937. var diameterY = options.diameterY || options.diameter || 1;
  32938. var diameterZ = options.diameterZ || options.diameter || 1;
  32939. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32940. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32941. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32942. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32943. var totalZRotationSteps = 2 + segments;
  32944. var totalYRotationSteps = 2 * totalZRotationSteps;
  32945. var indices = [];
  32946. var positions = [];
  32947. var normals = [];
  32948. var uvs = [];
  32949. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32950. var normalizedZ = zRotationStep / totalZRotationSteps;
  32951. var angleZ = normalizedZ * Math.PI * slice;
  32952. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32953. var normalizedY = yRotationStep / totalYRotationSteps;
  32954. var angleY = normalizedY * Math.PI * 2 * arc;
  32955. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32956. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32957. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32958. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32959. var vertex = complete.multiply(radius);
  32960. var normal = complete.divide(radius).normalize();
  32961. positions.push(vertex.x, vertex.y, vertex.z);
  32962. normals.push(normal.x, normal.y, normal.z);
  32963. uvs.push(normalizedY, normalizedZ);
  32964. }
  32965. if (zRotationStep > 0) {
  32966. var verticesCount = positions.length / 3;
  32967. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32968. indices.push((firstIndex));
  32969. indices.push((firstIndex + 1));
  32970. indices.push(firstIndex + totalYRotationSteps + 1);
  32971. indices.push((firstIndex + totalYRotationSteps + 1));
  32972. indices.push((firstIndex + 1));
  32973. indices.push((firstIndex + totalYRotationSteps + 2));
  32974. }
  32975. }
  32976. }
  32977. // Sides
  32978. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32979. // Result
  32980. var vertexData = new VertexData();
  32981. vertexData.indices = indices;
  32982. vertexData.positions = positions;
  32983. vertexData.normals = normals;
  32984. vertexData.uvs = uvs;
  32985. return vertexData;
  32986. };
  32987. // Cylinder and cone
  32988. VertexData.CreateCylinder = function (options) {
  32989. var height = options.height || 2;
  32990. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32991. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32992. var tessellation = options.tessellation || 24;
  32993. var subdivisions = options.subdivisions || 1;
  32994. var hasRings = options.hasRings;
  32995. var enclose = options.enclose;
  32996. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32998. var faceUV = options.faceUV || new Array(3);
  32999. var faceColors = options.faceColors;
  33000. // default face colors and UV if undefined
  33001. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33002. var ringNb = (hasRings) ? subdivisions : 1;
  33003. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33004. var f;
  33005. for (f = 0; f < surfaceNb; f++) {
  33006. if (faceColors && faceColors[f] === undefined) {
  33007. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33008. }
  33009. }
  33010. for (f = 0; f < surfaceNb; f++) {
  33011. if (faceUV && faceUV[f] === undefined) {
  33012. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33013. }
  33014. }
  33015. var indices = [];
  33016. var positions = [];
  33017. var normals = [];
  33018. var uvs = [];
  33019. var colors = [];
  33020. var angle_step = Math.PI * 2 * arc / tessellation;
  33021. var angle;
  33022. var h;
  33023. var radius;
  33024. var tan = (diameterBottom - diameterTop) / 2 / height;
  33025. var ringVertex = BABYLON.Vector3.Zero();
  33026. var ringNormal = BABYLON.Vector3.Zero();
  33027. var ringFirstVertex = BABYLON.Vector3.Zero();
  33028. var ringFirstNormal = BABYLON.Vector3.Zero();
  33029. var quadNormal = BABYLON.Vector3.Zero();
  33030. var Y = BABYLON.Axis.Y;
  33031. // positions, normals, uvs
  33032. var i;
  33033. var j;
  33034. var r;
  33035. var ringIdx = 1;
  33036. var s = 1; // surface index
  33037. var cs = 0;
  33038. var v = 0;
  33039. for (i = 0; i <= subdivisions; i++) {
  33040. h = i / subdivisions;
  33041. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33042. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33043. for (r = 0; r < ringIdx; r++) {
  33044. if (hasRings) {
  33045. s += r;
  33046. }
  33047. if (enclose) {
  33048. s += 2 * r;
  33049. }
  33050. for (j = 0; j <= tessellation; j++) {
  33051. angle = j * angle_step;
  33052. // position
  33053. ringVertex.x = Math.cos(-angle) * radius;
  33054. ringVertex.y = -height / 2 + h * height;
  33055. ringVertex.z = Math.sin(-angle) * radius;
  33056. // normal
  33057. if (diameterTop === 0 && i === subdivisions) {
  33058. // if no top cap, reuse former normals
  33059. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33060. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33061. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33062. }
  33063. else {
  33064. ringNormal.x = ringVertex.x;
  33065. ringNormal.z = ringVertex.z;
  33066. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33067. ringNormal.normalize();
  33068. }
  33069. // keep first ring vertex values for enclose
  33070. if (j === 0) {
  33071. ringFirstVertex.copyFrom(ringVertex);
  33072. ringFirstNormal.copyFrom(ringNormal);
  33073. }
  33074. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33075. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33076. if (hasRings) {
  33077. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33078. }
  33079. else {
  33080. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33081. }
  33082. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33083. if (faceColors) {
  33084. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33085. }
  33086. }
  33087. // if enclose, add four vertices and their dedicated normals
  33088. if (arc !== 1 && enclose) {
  33089. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33090. positions.push(0, ringVertex.y, 0);
  33091. positions.push(0, ringVertex.y, 0);
  33092. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33093. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33094. quadNormal.normalize();
  33095. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33096. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33097. quadNormal.normalize();
  33098. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33099. if (hasRings) {
  33100. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33101. }
  33102. else {
  33103. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33104. }
  33105. uvs.push(faceUV[s + 1].x, v);
  33106. uvs.push(faceUV[s + 1].z, v);
  33107. if (hasRings) {
  33108. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33109. }
  33110. else {
  33111. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33112. }
  33113. uvs.push(faceUV[s + 2].x, v);
  33114. uvs.push(faceUV[s + 2].z, v);
  33115. if (faceColors) {
  33116. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33117. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33118. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33119. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33120. }
  33121. }
  33122. if (cs !== s) {
  33123. cs = s;
  33124. }
  33125. }
  33126. }
  33127. // indices
  33128. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33129. var s;
  33130. i = 0;
  33131. for (s = 0; s < subdivisions; s++) {
  33132. for (j = 0; j < tessellation; j++) {
  33133. var i0 = i * (e + 1) + j;
  33134. var i1 = (i + 1) * (e + 1) + j;
  33135. var i2 = i * (e + 1) + (j + 1);
  33136. var i3 = (i + 1) * (e + 1) + (j + 1);
  33137. indices.push(i0, i1, i2);
  33138. indices.push(i3, i2, i1);
  33139. }
  33140. if (arc !== 1 && enclose) {
  33141. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33142. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33143. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33144. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33145. }
  33146. i = (hasRings) ? (i + 2) : (i + 1);
  33147. }
  33148. // Caps
  33149. var createCylinderCap = function (isTop) {
  33150. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33151. if (radius === 0) {
  33152. return;
  33153. }
  33154. // Cap positions, normals & uvs
  33155. var angle;
  33156. var circleVector;
  33157. var i;
  33158. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33159. var c;
  33160. if (faceColors) {
  33161. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33162. }
  33163. // cap center
  33164. var vbase = positions.length / 3;
  33165. var offset = isTop ? height / 2 : -height / 2;
  33166. var center = new BABYLON.Vector3(0, offset, 0);
  33167. positions.push(center.x, center.y, center.z);
  33168. normals.push(0, isTop ? 1 : -1, 0);
  33169. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33170. if (faceColors) {
  33171. colors.push(c.r, c.g, c.b, c.a);
  33172. }
  33173. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33174. for (i = 0; i <= tessellation; i++) {
  33175. angle = Math.PI * 2 * i * arc / tessellation;
  33176. var cos = Math.cos(-angle);
  33177. var sin = Math.sin(-angle);
  33178. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33179. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33180. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33181. normals.push(0, isTop ? 1 : -1, 0);
  33182. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33183. if (faceColors) {
  33184. colors.push(c.r, c.g, c.b, c.a);
  33185. }
  33186. }
  33187. // Cap indices
  33188. for (i = 0; i < tessellation; i++) {
  33189. if (!isTop) {
  33190. indices.push(vbase);
  33191. indices.push(vbase + (i + 1));
  33192. indices.push(vbase + (i + 2));
  33193. }
  33194. else {
  33195. indices.push(vbase);
  33196. indices.push(vbase + (i + 2));
  33197. indices.push(vbase + (i + 1));
  33198. }
  33199. }
  33200. };
  33201. // add caps to geometry
  33202. createCylinderCap(false);
  33203. createCylinderCap(true);
  33204. // Sides
  33205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33206. var vertexData = new VertexData();
  33207. vertexData.indices = indices;
  33208. vertexData.positions = positions;
  33209. vertexData.normals = normals;
  33210. vertexData.uvs = uvs;
  33211. if (faceColors) {
  33212. vertexData.colors = colors;
  33213. }
  33214. return vertexData;
  33215. };
  33216. VertexData.CreateTorus = function (options) {
  33217. var indices = [];
  33218. var positions = [];
  33219. var normals = [];
  33220. var uvs = [];
  33221. var diameter = options.diameter || 1;
  33222. var thickness = options.thickness || 0.5;
  33223. var tessellation = options.tessellation || 16;
  33224. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33225. var stride = tessellation + 1;
  33226. for (var i = 0; i <= tessellation; i++) {
  33227. var u = i / tessellation;
  33228. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33229. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33230. for (var j = 0; j <= tessellation; j++) {
  33231. var v = 1 - j / tessellation;
  33232. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33233. var dx = Math.cos(innerAngle);
  33234. var dy = Math.sin(innerAngle);
  33235. // Create a vertex.
  33236. var normal = new BABYLON.Vector3(dx, dy, 0);
  33237. var position = normal.scale(thickness / 2);
  33238. var textureCoordinate = new BABYLON.Vector2(u, v);
  33239. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33240. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33241. positions.push(position.x, position.y, position.z);
  33242. normals.push(normal.x, normal.y, normal.z);
  33243. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33244. // And create indices for two triangles.
  33245. var nextI = (i + 1) % stride;
  33246. var nextJ = (j + 1) % stride;
  33247. indices.push(i * stride + j);
  33248. indices.push(i * stride + nextJ);
  33249. indices.push(nextI * stride + j);
  33250. indices.push(i * stride + nextJ);
  33251. indices.push(nextI * stride + nextJ);
  33252. indices.push(nextI * stride + j);
  33253. }
  33254. }
  33255. // Sides
  33256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33257. // Result
  33258. var vertexData = new VertexData();
  33259. vertexData.indices = indices;
  33260. vertexData.positions = positions;
  33261. vertexData.normals = normals;
  33262. vertexData.uvs = uvs;
  33263. return vertexData;
  33264. };
  33265. VertexData.CreateLineSystem = function (options) {
  33266. var indices = [];
  33267. var positions = [];
  33268. var lines = options.lines;
  33269. var idx = 0;
  33270. for (var l = 0; l < lines.length; l++) {
  33271. var points = lines[l];
  33272. for (var index = 0; index < points.length; index++) {
  33273. positions.push(points[index].x, points[index].y, points[index].z);
  33274. if (index > 0) {
  33275. indices.push(idx - 1);
  33276. indices.push(idx);
  33277. }
  33278. idx++;
  33279. }
  33280. }
  33281. var vertexData = new VertexData();
  33282. vertexData.indices = indices;
  33283. vertexData.positions = positions;
  33284. return vertexData;
  33285. };
  33286. VertexData.CreateDashedLines = function (options) {
  33287. var dashSize = options.dashSize || 3;
  33288. var gapSize = options.gapSize || 1;
  33289. var dashNb = options.dashNb || 200;
  33290. var points = options.points;
  33291. var positions = new Array();
  33292. var indices = new Array();
  33293. var curvect = BABYLON.Vector3.Zero();
  33294. var lg = 0;
  33295. var nb = 0;
  33296. var shft = 0;
  33297. var dashshft = 0;
  33298. var curshft = 0;
  33299. var idx = 0;
  33300. var i = 0;
  33301. for (i = 0; i < points.length - 1; i++) {
  33302. points[i + 1].subtractToRef(points[i], curvect);
  33303. lg += curvect.length();
  33304. }
  33305. shft = lg / dashNb;
  33306. dashshft = dashSize * shft / (dashSize + gapSize);
  33307. for (i = 0; i < points.length - 1; i++) {
  33308. points[i + 1].subtractToRef(points[i], curvect);
  33309. nb = Math.floor(curvect.length() / shft);
  33310. curvect.normalize();
  33311. for (var j = 0; j < nb; j++) {
  33312. curshft = shft * j;
  33313. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33314. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33315. indices.push(idx, idx + 1);
  33316. idx += 2;
  33317. }
  33318. }
  33319. // Result
  33320. var vertexData = new VertexData();
  33321. vertexData.positions = positions;
  33322. vertexData.indices = indices;
  33323. return vertexData;
  33324. };
  33325. VertexData.CreateGround = function (options) {
  33326. var indices = [];
  33327. var positions = [];
  33328. var normals = [];
  33329. var uvs = [];
  33330. var row, col;
  33331. var width = options.width || 1;
  33332. var height = options.height || 1;
  33333. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33334. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33335. for (row = 0; row <= subdivisionsY; row++) {
  33336. for (col = 0; col <= subdivisionsX; col++) {
  33337. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33338. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33339. positions.push(position.x, position.y, position.z);
  33340. normals.push(normal.x, normal.y, normal.z);
  33341. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33342. }
  33343. }
  33344. for (row = 0; row < subdivisionsY; row++) {
  33345. for (col = 0; col < subdivisionsX; col++) {
  33346. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33347. indices.push(col + 1 + row * (subdivisionsX + 1));
  33348. indices.push(col + row * (subdivisionsX + 1));
  33349. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33350. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33351. indices.push(col + row * (subdivisionsX + 1));
  33352. }
  33353. }
  33354. // Result
  33355. var vertexData = new VertexData();
  33356. vertexData.indices = indices;
  33357. vertexData.positions = positions;
  33358. vertexData.normals = normals;
  33359. vertexData.uvs = uvs;
  33360. return vertexData;
  33361. };
  33362. VertexData.CreateTiledGround = function (options) {
  33363. var xmin = options.xmin || -1.0;
  33364. var zmin = options.zmin || -1.0;
  33365. var xmax = options.xmax || 1.0;
  33366. var zmax = options.zmax || 1.0;
  33367. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33368. var precision = options.precision || { w: 1, h: 1 };
  33369. var indices = [];
  33370. var positions = [];
  33371. var normals = [];
  33372. var uvs = [];
  33373. var row, col, tileRow, tileCol;
  33374. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33375. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33376. precision.w = (precision.w < 1) ? 1 : precision.w;
  33377. precision.h = (precision.h < 1) ? 1 : precision.h;
  33378. var tileSize = {
  33379. 'w': (xmax - xmin) / subdivisions.w,
  33380. 'h': (zmax - zmin) / subdivisions.h
  33381. };
  33382. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33383. // Indices
  33384. var base = positions.length / 3;
  33385. var rowLength = precision.w + 1;
  33386. for (row = 0; row < precision.h; row++) {
  33387. for (col = 0; col < precision.w; col++) {
  33388. var square = [
  33389. base + col + row * rowLength,
  33390. base + (col + 1) + row * rowLength,
  33391. base + (col + 1) + (row + 1) * rowLength,
  33392. base + col + (row + 1) * rowLength
  33393. ];
  33394. indices.push(square[1]);
  33395. indices.push(square[2]);
  33396. indices.push(square[3]);
  33397. indices.push(square[0]);
  33398. indices.push(square[1]);
  33399. indices.push(square[3]);
  33400. }
  33401. }
  33402. // Position, normals and uvs
  33403. var position = BABYLON.Vector3.Zero();
  33404. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33405. for (row = 0; row <= precision.h; row++) {
  33406. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33407. for (col = 0; col <= precision.w; col++) {
  33408. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33409. position.y = 0;
  33410. positions.push(position.x, position.y, position.z);
  33411. normals.push(normal.x, normal.y, normal.z);
  33412. uvs.push(col / precision.w, row / precision.h);
  33413. }
  33414. }
  33415. }
  33416. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33417. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33418. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33419. }
  33420. }
  33421. // Result
  33422. var vertexData = new VertexData();
  33423. vertexData.indices = indices;
  33424. vertexData.positions = positions;
  33425. vertexData.normals = normals;
  33426. vertexData.uvs = uvs;
  33427. return vertexData;
  33428. };
  33429. VertexData.CreateGroundFromHeightMap = function (options) {
  33430. var indices = [];
  33431. var positions = [];
  33432. var normals = [];
  33433. var uvs = [];
  33434. var row, col;
  33435. // Vertices
  33436. for (row = 0; row <= options.subdivisions; row++) {
  33437. for (col = 0; col <= options.subdivisions; col++) {
  33438. 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));
  33439. // Compute height
  33440. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33441. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33442. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33443. var r = options.buffer[pos] / 255.0;
  33444. var g = options.buffer[pos + 1] / 255.0;
  33445. var b = options.buffer[pos + 2] / 255.0;
  33446. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33447. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33448. // Add vertex
  33449. positions.push(position.x, position.y, position.z);
  33450. normals.push(0, 0, 0);
  33451. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33452. }
  33453. }
  33454. // Indices
  33455. for (row = 0; row < options.subdivisions; row++) {
  33456. for (col = 0; col < options.subdivisions; col++) {
  33457. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33458. indices.push(col + 1 + row * (options.subdivisions + 1));
  33459. indices.push(col + row * (options.subdivisions + 1));
  33460. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33461. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33462. indices.push(col + row * (options.subdivisions + 1));
  33463. }
  33464. }
  33465. // Normals
  33466. VertexData.ComputeNormals(positions, indices, normals);
  33467. // Result
  33468. var vertexData = new VertexData();
  33469. vertexData.indices = indices;
  33470. vertexData.positions = positions;
  33471. vertexData.normals = normals;
  33472. vertexData.uvs = uvs;
  33473. return vertexData;
  33474. };
  33475. VertexData.CreatePlane = function (options) {
  33476. var indices = [];
  33477. var positions = [];
  33478. var normals = [];
  33479. var uvs = [];
  33480. var width = options.width || options.size || 1;
  33481. var height = options.height || options.size || 1;
  33482. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33483. // Vertices
  33484. var halfWidth = width / 2.0;
  33485. var halfHeight = height / 2.0;
  33486. positions.push(-halfWidth, -halfHeight, 0);
  33487. normals.push(0, 0, -1.0);
  33488. uvs.push(0.0, 0.0);
  33489. positions.push(halfWidth, -halfHeight, 0);
  33490. normals.push(0, 0, -1.0);
  33491. uvs.push(1.0, 0.0);
  33492. positions.push(halfWidth, halfHeight, 0);
  33493. normals.push(0, 0, -1.0);
  33494. uvs.push(1.0, 1.0);
  33495. positions.push(-halfWidth, halfHeight, 0);
  33496. normals.push(0, 0, -1.0);
  33497. uvs.push(0.0, 1.0);
  33498. // Indices
  33499. indices.push(0);
  33500. indices.push(1);
  33501. indices.push(2);
  33502. indices.push(0);
  33503. indices.push(2);
  33504. indices.push(3);
  33505. // Sides
  33506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33507. // Result
  33508. var vertexData = new VertexData();
  33509. vertexData.indices = indices;
  33510. vertexData.positions = positions;
  33511. vertexData.normals = normals;
  33512. vertexData.uvs = uvs;
  33513. return vertexData;
  33514. };
  33515. VertexData.CreateDisc = function (options) {
  33516. var positions = [];
  33517. var indices = [];
  33518. var normals = [];
  33519. var uvs = [];
  33520. var radius = options.radius || 0.5;
  33521. var tessellation = options.tessellation || 64;
  33522. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33523. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33524. // positions and uvs
  33525. positions.push(0, 0, 0); // disc center first
  33526. uvs.push(0.5, 0.5);
  33527. var theta = Math.PI * 2 * arc;
  33528. var step = theta / tessellation;
  33529. for (var a = 0; a < theta; a += step) {
  33530. var x = Math.cos(a);
  33531. var y = Math.sin(a);
  33532. var u = (x + 1) / 2;
  33533. var v = (1 - y) / 2;
  33534. positions.push(radius * x, radius * y, 0);
  33535. uvs.push(u, v);
  33536. }
  33537. if (arc === 1) {
  33538. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33539. uvs.push(uvs[2], uvs[3]);
  33540. }
  33541. //indices
  33542. var vertexNb = positions.length / 3;
  33543. for (var i = 1; i < vertexNb - 1; i++) {
  33544. indices.push(i + 1, 0, i);
  33545. }
  33546. // result
  33547. VertexData.ComputeNormals(positions, indices, normals);
  33548. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33549. var vertexData = new VertexData();
  33550. vertexData.indices = indices;
  33551. vertexData.positions = positions;
  33552. vertexData.normals = normals;
  33553. vertexData.uvs = uvs;
  33554. return vertexData;
  33555. };
  33556. VertexData.CreateIcoSphere = function (options) {
  33557. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33558. var radius = options.radius || 1;
  33559. var flat = (options.flat === undefined) ? true : options.flat;
  33560. var subdivisions = options.subdivisions || 4;
  33561. var radiusX = options.radiusX || radius;
  33562. var radiusY = options.radiusY || radius;
  33563. var radiusZ = options.radiusZ || radius;
  33564. var t = (1 + Math.sqrt(5)) / 2;
  33565. // 12 vertex x,y,z
  33566. var ico_vertices = [
  33567. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33568. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33569. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33570. ];
  33571. // index of 3 vertex makes a face of icopshere
  33572. var ico_indices = [
  33573. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33574. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33575. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33576. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33577. ];
  33578. // vertex for uv have aliased position, not for UV
  33579. var vertices_unalias_id = [
  33580. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33581. // vertex alias
  33582. 0,
  33583. 2,
  33584. 3,
  33585. 3,
  33586. 3,
  33587. 4,
  33588. 7,
  33589. 8,
  33590. 9,
  33591. 9,
  33592. 10,
  33593. 11 // 23: B + 12
  33594. ];
  33595. // uv as integer step (not pixels !)
  33596. var ico_vertexuv = [
  33597. 5, 1, 3, 1, 6, 4, 0, 0,
  33598. 5, 3, 4, 2, 2, 2, 4, 0,
  33599. 2, 0, 1, 1, 6, 0, 6, 2,
  33600. // vertex alias (for same vertex on different faces)
  33601. 0, 4,
  33602. 3, 3,
  33603. 4, 4,
  33604. 3, 1,
  33605. 4, 2,
  33606. 4, 4,
  33607. 0, 2,
  33608. 1, 1,
  33609. 2, 2,
  33610. 3, 3,
  33611. 1, 3,
  33612. 2, 4 // 23: B + 12
  33613. ];
  33614. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33615. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33616. // First island of uv mapping
  33617. // v = 4h 3+ 2
  33618. // v = 3h 9+ 4
  33619. // v = 2h 9+ 5 B
  33620. // v = 1h 9 1 0
  33621. // v = 0h 3 8 7 A
  33622. // u = 0 1 2 3 4 5 6 *a
  33623. // Second island of uv mapping
  33624. // v = 4h 0+ B+ 4+
  33625. // v = 3h A+ 2+
  33626. // v = 2h 7+ 6 3+
  33627. // v = 1h 8+ 3+
  33628. // v = 0h
  33629. // u = 0 1 2 3 4 5 6 *a
  33630. // Face layout on texture UV mapping
  33631. // ============
  33632. // \ 4 /\ 16 / ======
  33633. // \ / \ / /\ 11 /
  33634. // \/ 7 \/ / \ /
  33635. // ======= / 10 \/
  33636. // /\ 17 /\ =======
  33637. // / \ / \ \ 15 /\
  33638. // / 8 \/ 12 \ \ / \
  33639. // ============ \/ 6 \
  33640. // \ 18 /\ ============
  33641. // \ / \ \ 5 /\ 0 /
  33642. // \/ 13 \ \ / \ /
  33643. // ======= \/ 1 \/
  33644. // =============
  33645. // /\ 19 /\ 2 /\
  33646. // / \ / \ / \
  33647. // / 14 \/ 9 \/ 3 \
  33648. // ===================
  33649. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33650. var ustep = 138 / 1024;
  33651. var vstep = 239 / 1024;
  33652. var uoffset = 60 / 1024;
  33653. var voffset = 26 / 1024;
  33654. // Second island should have margin, not to touch the first island
  33655. // avoid any borderline artefact in pixel rounding
  33656. var island_u_offset = -40 / 1024;
  33657. var island_v_offset = +20 / 1024;
  33658. // face is either island 0 or 1 :
  33659. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33660. var island = [
  33661. 0, 0, 0, 0, 1,
  33662. 0, 0, 1, 1, 0,
  33663. 0, 0, 1, 1, 0,
  33664. 0, 1, 1, 1, 0 // 15 - 19
  33665. ];
  33666. var indices = [];
  33667. var positions = [];
  33668. var normals = [];
  33669. var uvs = [];
  33670. var current_indice = 0;
  33671. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33672. var face_vertex_pos = new Array(3);
  33673. var face_vertex_uv = new Array(3);
  33674. var v012;
  33675. for (v012 = 0; v012 < 3; v012++) {
  33676. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33677. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33678. }
  33679. // create all with normals
  33680. for (var face = 0; face < 20; face++) {
  33681. // 3 vertex per face
  33682. for (v012 = 0; v012 < 3; v012++) {
  33683. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33684. var v_id = ico_indices[3 * face + v012];
  33685. // vertex have 3D position (x,y,z)
  33686. 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]);
  33687. // Normalize to get normal, then scale to radius
  33688. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33689. // uv Coordinates from vertex ID
  33690. 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);
  33691. }
  33692. // Subdivide the face (interpolate pos, norm, uv)
  33693. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33694. // - norm is linear interpolation of vertex corner normal
  33695. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33696. // - uv is linear interpolation
  33697. //
  33698. // Topology is as below for sub-divide by 2
  33699. // vertex shown as v0,v1,v2
  33700. // interp index is i1 to progress in range [v0,v1[
  33701. // interp index is i2 to progress in range [v0,v2[
  33702. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33703. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33704. //
  33705. //
  33706. // i2 v2
  33707. // ^ ^
  33708. // / / \
  33709. // / / \
  33710. // / / \
  33711. // / / (0,1) \
  33712. // / #---------\
  33713. // / / \ (0,0)'/ \
  33714. // / / \ / \
  33715. // / / \ / \
  33716. // / / (0,0) \ / (1,0) \
  33717. // / #---------#---------\
  33718. // v0 v1
  33719. //
  33720. // --------------------> i1
  33721. //
  33722. // interp of (i1,i2):
  33723. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33724. // along i1 : lerp(x0,x1, i1/(S-i2))
  33725. //
  33726. // centroid of triangle is needed to get help normal computation
  33727. // (c1,c2) are used for centroid location
  33728. var interp_vertex = function (i1, i2, c1, c2) {
  33729. // vertex is interpolated from
  33730. // - face_vertex_pos[0..2]
  33731. // - face_vertex_uv[0..2]
  33732. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33733. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33734. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33735. pos_interp.normalize();
  33736. var vertex_normal;
  33737. if (flat) {
  33738. // in flat mode, recalculate normal as face centroid normal
  33739. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33740. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33741. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33742. }
  33743. else {
  33744. // in smooth mode, recalculate normal from each single vertex position
  33745. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33746. }
  33747. // Vertex normal need correction due to X,Y,Z radius scaling
  33748. vertex_normal.x /= radiusX;
  33749. vertex_normal.y /= radiusY;
  33750. vertex_normal.z /= radiusZ;
  33751. vertex_normal.normalize();
  33752. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33753. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33754. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33755. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33756. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33757. uvs.push(uv_interp.x, uv_interp.y);
  33758. // push each vertex has member of a face
  33759. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33760. indices.push(current_indice);
  33761. current_indice++;
  33762. };
  33763. for (var i2 = 0; i2 < subdivisions; i2++) {
  33764. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33765. // face : (i1,i2) for /\ :
  33766. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33767. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33768. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33769. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33770. if (i1 + i2 + 1 < subdivisions) {
  33771. // face : (i1,i2)' for \/ :
  33772. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33773. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33774. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33775. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33776. }
  33777. }
  33778. }
  33779. }
  33780. // Sides
  33781. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33782. // Result
  33783. var vertexData = new VertexData();
  33784. vertexData.indices = indices;
  33785. vertexData.positions = positions;
  33786. vertexData.normals = normals;
  33787. vertexData.uvs = uvs;
  33788. return vertexData;
  33789. };
  33790. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33791. VertexData.CreatePolyhedron = function (options) {
  33792. // provided polyhedron types :
  33793. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33794. // 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)
  33795. var polyhedra = [];
  33796. 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]] };
  33797. 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]] };
  33798. polyhedra[2] = {
  33799. 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]],
  33800. 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]]
  33801. };
  33802. polyhedra[3] = {
  33803. 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]],
  33804. 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]]
  33805. };
  33806. polyhedra[4] = {
  33807. 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]],
  33808. 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]]
  33809. };
  33810. 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]] };
  33811. 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]] };
  33812. 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]] };
  33813. 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]] };
  33814. 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]] };
  33815. 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]] };
  33816. 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]] };
  33817. 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]] };
  33818. 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]] };
  33819. polyhedra[14] = {
  33820. 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]],
  33821. 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]]
  33822. };
  33823. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33824. var size = options.size;
  33825. var sizeX = options.sizeX || size || 1;
  33826. var sizeY = options.sizeY || size || 1;
  33827. var sizeZ = options.sizeZ || size || 1;
  33828. var data = options.custom || polyhedra[type];
  33829. var nbfaces = data.face.length;
  33830. var faceUV = options.faceUV || new Array(nbfaces);
  33831. var faceColors = options.faceColors;
  33832. var flat = (options.flat === undefined) ? true : options.flat;
  33833. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33834. var positions = [];
  33835. var indices = [];
  33836. var normals = [];
  33837. var uvs = [];
  33838. var colors = [];
  33839. var index = 0;
  33840. var faceIdx = 0; // face cursor in the array "indexes"
  33841. var indexes = [];
  33842. var i = 0;
  33843. var f = 0;
  33844. var u, v, ang, x, y, tmp;
  33845. // default face colors and UV if undefined
  33846. if (flat) {
  33847. for (f = 0; f < nbfaces; f++) {
  33848. if (faceColors && faceColors[f] === undefined) {
  33849. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33850. }
  33851. if (faceUV && faceUV[f] === undefined) {
  33852. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33853. }
  33854. }
  33855. }
  33856. if (!flat) {
  33857. for (i = 0; i < data.vertex.length; i++) {
  33858. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33859. uvs.push(0, 0);
  33860. }
  33861. for (f = 0; f < nbfaces; f++) {
  33862. for (i = 0; i < data.face[f].length - 2; i++) {
  33863. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33864. }
  33865. }
  33866. }
  33867. else {
  33868. for (f = 0; f < nbfaces; f++) {
  33869. var fl = data.face[f].length; // number of vertices of the current face
  33870. ang = 2 * Math.PI / fl;
  33871. x = 0.5 * Math.tan(ang / 2);
  33872. y = 0.5;
  33873. // positions, uvs, colors
  33874. for (i = 0; i < fl; i++) {
  33875. // positions
  33876. 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);
  33877. indexes.push(index);
  33878. index++;
  33879. // uvs
  33880. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33881. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33882. uvs.push(u, v);
  33883. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33884. y = x * Math.sin(ang) + y * Math.cos(ang);
  33885. x = tmp;
  33886. // colors
  33887. if (faceColors) {
  33888. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33889. }
  33890. }
  33891. // indices from indexes
  33892. for (i = 0; i < fl - 2; i++) {
  33893. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33894. }
  33895. faceIdx += fl;
  33896. }
  33897. }
  33898. VertexData.ComputeNormals(positions, indices, normals);
  33899. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33900. var vertexData = new VertexData();
  33901. vertexData.positions = positions;
  33902. vertexData.indices = indices;
  33903. vertexData.normals = normals;
  33904. vertexData.uvs = uvs;
  33905. if (faceColors && flat) {
  33906. vertexData.colors = colors;
  33907. }
  33908. return vertexData;
  33909. };
  33910. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33911. VertexData.CreateTorusKnot = function (options) {
  33912. var indices = [];
  33913. var positions = [];
  33914. var normals = [];
  33915. var uvs = [];
  33916. var radius = options.radius || 2;
  33917. var tube = options.tube || 0.5;
  33918. var radialSegments = options.radialSegments || 32;
  33919. var tubularSegments = options.tubularSegments || 32;
  33920. var p = options.p || 2;
  33921. var q = options.q || 3;
  33922. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33923. // Helper
  33924. var getPos = function (angle) {
  33925. var cu = Math.cos(angle);
  33926. var su = Math.sin(angle);
  33927. var quOverP = q / p * angle;
  33928. var cs = Math.cos(quOverP);
  33929. var tx = radius * (2 + cs) * 0.5 * cu;
  33930. var ty = radius * (2 + cs) * su * 0.5;
  33931. var tz = radius * Math.sin(quOverP) * 0.5;
  33932. return new BABYLON.Vector3(tx, ty, tz);
  33933. };
  33934. // Vertices
  33935. var i;
  33936. var j;
  33937. for (i = 0; i <= radialSegments; i++) {
  33938. var modI = i % radialSegments;
  33939. var u = modI / radialSegments * 2 * p * Math.PI;
  33940. var p1 = getPos(u);
  33941. var p2 = getPos(u + 0.01);
  33942. var tang = p2.subtract(p1);
  33943. var n = p2.add(p1);
  33944. var bitan = BABYLON.Vector3.Cross(tang, n);
  33945. n = BABYLON.Vector3.Cross(bitan, tang);
  33946. bitan.normalize();
  33947. n.normalize();
  33948. for (j = 0; j < tubularSegments; j++) {
  33949. var modJ = j % tubularSegments;
  33950. var v = modJ / tubularSegments * 2 * Math.PI;
  33951. var cx = -tube * Math.cos(v);
  33952. var cy = tube * Math.sin(v);
  33953. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33954. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33955. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33956. uvs.push(i / radialSegments);
  33957. uvs.push(j / tubularSegments);
  33958. }
  33959. }
  33960. for (i = 0; i < radialSegments; i++) {
  33961. for (j = 0; j < tubularSegments; j++) {
  33962. var jNext = (j + 1) % tubularSegments;
  33963. var a = i * tubularSegments + j;
  33964. var b = (i + 1) * tubularSegments + j;
  33965. var c = (i + 1) * tubularSegments + jNext;
  33966. var d = i * tubularSegments + jNext;
  33967. indices.push(d);
  33968. indices.push(b);
  33969. indices.push(a);
  33970. indices.push(d);
  33971. indices.push(c);
  33972. indices.push(b);
  33973. }
  33974. }
  33975. // Normals
  33976. VertexData.ComputeNormals(positions, indices, normals);
  33977. // Sides
  33978. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33979. // Result
  33980. var vertexData = new VertexData();
  33981. vertexData.indices = indices;
  33982. vertexData.positions = positions;
  33983. vertexData.normals = normals;
  33984. vertexData.uvs = uvs;
  33985. return vertexData;
  33986. };
  33987. // Tools
  33988. /**
  33989. * @param {any} - positions (number[] or Float32Array)
  33990. * @param {any} - indices (number[] or Uint16Array)
  33991. * @param {any} - normals (number[] or Float32Array)
  33992. */
  33993. VertexData.ComputeNormals = function (positions, indices, normals) {
  33994. var index = 0;
  33995. var p1p2x = 0.0;
  33996. var p1p2y = 0.0;
  33997. var p1p2z = 0.0;
  33998. var p3p2x = 0.0;
  33999. var p3p2y = 0.0;
  34000. var p3p2z = 0.0;
  34001. var faceNormalx = 0.0;
  34002. var faceNormaly = 0.0;
  34003. var faceNormalz = 0.0;
  34004. var length = 0.0;
  34005. var i1 = 0;
  34006. var i2 = 0;
  34007. var i3 = 0;
  34008. for (index = 0; index < positions.length; index++) {
  34009. normals[index] = 0.0;
  34010. }
  34011. // indice triplet = 1 face
  34012. var nbFaces = indices.length / 3;
  34013. for (index = 0; index < nbFaces; index++) {
  34014. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34015. i2 = indices[index * 3 + 1];
  34016. i3 = indices[index * 3 + 2];
  34017. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34018. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34019. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34020. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34021. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34022. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34023. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34024. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34025. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34026. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34027. length = (length === 0) ? 1.0 : length;
  34028. faceNormalx /= length; // normalize this normal
  34029. faceNormaly /= length;
  34030. faceNormalz /= length;
  34031. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34032. normals[i1 * 3 + 1] += faceNormaly;
  34033. normals[i1 * 3 + 2] += faceNormalz;
  34034. normals[i2 * 3] += faceNormalx;
  34035. normals[i2 * 3 + 1] += faceNormaly;
  34036. normals[i2 * 3 + 2] += faceNormalz;
  34037. normals[i3 * 3] += faceNormalx;
  34038. normals[i3 * 3 + 1] += faceNormaly;
  34039. normals[i3 * 3 + 2] += faceNormalz;
  34040. }
  34041. // last normalization of each normal
  34042. for (index = 0; index < normals.length / 3; index++) {
  34043. faceNormalx = normals[index * 3];
  34044. faceNormaly = normals[index * 3 + 1];
  34045. faceNormalz = normals[index * 3 + 2];
  34046. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34047. length = (length === 0) ? 1.0 : length;
  34048. faceNormalx /= length;
  34049. faceNormaly /= length;
  34050. faceNormalz /= length;
  34051. normals[index * 3] = faceNormalx;
  34052. normals[index * 3 + 1] = faceNormaly;
  34053. normals[index * 3 + 2] = faceNormalz;
  34054. }
  34055. };
  34056. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34057. var li = indices.length;
  34058. var ln = normals.length;
  34059. var i;
  34060. var n;
  34061. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34062. switch (sideOrientation) {
  34063. case BABYLON.Mesh.FRONTSIDE:
  34064. // nothing changed
  34065. break;
  34066. case BABYLON.Mesh.BACKSIDE:
  34067. var tmp;
  34068. // indices
  34069. for (i = 0; i < li; i += 3) {
  34070. tmp = indices[i];
  34071. indices[i] = indices[i + 2];
  34072. indices[i + 2] = tmp;
  34073. }
  34074. // normals
  34075. for (n = 0; n < ln; n++) {
  34076. normals[n] = -normals[n];
  34077. }
  34078. break;
  34079. case BABYLON.Mesh.DOUBLESIDE:
  34080. // positions
  34081. var lp = positions.length;
  34082. var l = lp / 3;
  34083. for (var p = 0; p < lp; p++) {
  34084. positions[lp + p] = positions[p];
  34085. }
  34086. // indices
  34087. for (i = 0; i < li; i += 3) {
  34088. indices[i + li] = indices[i + 2] + l;
  34089. indices[i + 1 + li] = indices[i + 1] + l;
  34090. indices[i + 2 + li] = indices[i] + l;
  34091. }
  34092. // normals
  34093. for (n = 0; n < ln; n++) {
  34094. normals[ln + n] = -normals[n];
  34095. }
  34096. // uvs
  34097. var lu = uvs.length;
  34098. for (var u = 0; u < lu; u++) {
  34099. uvs[u + lu] = uvs[u];
  34100. }
  34101. break;
  34102. }
  34103. };
  34104. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34105. var vertexData = new VertexData();
  34106. // positions
  34107. var positions = parsedVertexData.positions;
  34108. if (positions) {
  34109. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34110. }
  34111. // normals
  34112. var normals = parsedVertexData.normals;
  34113. if (normals) {
  34114. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34115. }
  34116. // uvs
  34117. var uvs = parsedVertexData.uvs;
  34118. if (uvs) {
  34119. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34120. }
  34121. // uv2s
  34122. var uv2s = parsedVertexData.uv2s;
  34123. if (uv2s) {
  34124. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34125. }
  34126. // uv3s
  34127. var uv3s = parsedVertexData.uv3s;
  34128. if (uv3s) {
  34129. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34130. }
  34131. // uv4s
  34132. var uv4s = parsedVertexData.uv4s;
  34133. if (uv4s) {
  34134. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34135. }
  34136. // uv5s
  34137. var uv5s = parsedVertexData.uv5s;
  34138. if (uv5s) {
  34139. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34140. }
  34141. // uv6s
  34142. var uv6s = parsedVertexData.uv6s;
  34143. if (uv6s) {
  34144. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34145. }
  34146. // colors
  34147. var colors = parsedVertexData.colors;
  34148. if (colors) {
  34149. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34150. }
  34151. // matricesIndices
  34152. var matricesIndices = parsedVertexData.matricesIndices;
  34153. if (matricesIndices) {
  34154. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34155. }
  34156. // matricesWeights
  34157. var matricesWeights = parsedVertexData.matricesWeights;
  34158. if (matricesWeights) {
  34159. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34160. }
  34161. // indices
  34162. var indices = parsedVertexData.indices;
  34163. if (indices) {
  34164. vertexData.indices = indices;
  34165. }
  34166. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34167. };
  34168. return VertexData;
  34169. }());
  34170. BABYLON.VertexData = VertexData;
  34171. })(BABYLON || (BABYLON = {}));
  34172. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34173. var BABYLON;
  34174. (function (BABYLON) {
  34175. var Tags = (function () {
  34176. function Tags() {
  34177. }
  34178. Tags.EnableFor = function (obj) {
  34179. obj._tags = obj._tags || {};
  34180. obj.hasTags = function () {
  34181. return Tags.HasTags(obj);
  34182. };
  34183. obj.addTags = function (tagsString) {
  34184. return Tags.AddTagsTo(obj, tagsString);
  34185. };
  34186. obj.removeTags = function (tagsString) {
  34187. return Tags.RemoveTagsFrom(obj, tagsString);
  34188. };
  34189. obj.matchesTagsQuery = function (tagsQuery) {
  34190. return Tags.MatchesQuery(obj, tagsQuery);
  34191. };
  34192. };
  34193. Tags.DisableFor = function (obj) {
  34194. delete obj._tags;
  34195. delete obj.hasTags;
  34196. delete obj.addTags;
  34197. delete obj.removeTags;
  34198. delete obj.matchesTagsQuery;
  34199. };
  34200. Tags.HasTags = function (obj) {
  34201. if (!obj._tags) {
  34202. return false;
  34203. }
  34204. return !BABYLON.Tools.IsEmpty(obj._tags);
  34205. };
  34206. Tags.GetTags = function (obj, asString) {
  34207. if (asString === void 0) { asString = true; }
  34208. if (!obj._tags) {
  34209. return null;
  34210. }
  34211. if (asString) {
  34212. var tagsArray = [];
  34213. for (var tag in obj._tags) {
  34214. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34215. tagsArray.push(tag);
  34216. }
  34217. }
  34218. return tagsArray.join(" ");
  34219. }
  34220. else {
  34221. return obj._tags;
  34222. }
  34223. };
  34224. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34225. // a tag cannot start with '||', '&&', and '!'
  34226. // it cannot contain whitespaces
  34227. Tags.AddTagsTo = function (obj, tagsString) {
  34228. if (!tagsString) {
  34229. return;
  34230. }
  34231. if (typeof tagsString !== "string") {
  34232. return;
  34233. }
  34234. var tags = tagsString.split(" ");
  34235. tags.forEach(function (tag, index, array) {
  34236. Tags._AddTagTo(obj, tag);
  34237. });
  34238. };
  34239. Tags._AddTagTo = function (obj, tag) {
  34240. tag = tag.trim();
  34241. if (tag === "" || tag === "true" || tag === "false") {
  34242. return;
  34243. }
  34244. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34245. return;
  34246. }
  34247. Tags.EnableFor(obj);
  34248. obj._tags[tag] = true;
  34249. };
  34250. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34251. if (!Tags.HasTags(obj)) {
  34252. return;
  34253. }
  34254. var tags = tagsString.split(" ");
  34255. for (var t in tags) {
  34256. Tags._RemoveTagFrom(obj, tags[t]);
  34257. }
  34258. };
  34259. Tags._RemoveTagFrom = function (obj, tag) {
  34260. delete obj._tags[tag];
  34261. };
  34262. Tags.MatchesQuery = function (obj, tagsQuery) {
  34263. if (tagsQuery === undefined) {
  34264. return true;
  34265. }
  34266. if (tagsQuery === "") {
  34267. return Tags.HasTags(obj);
  34268. }
  34269. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34270. };
  34271. return Tags;
  34272. }());
  34273. BABYLON.Tags = Tags;
  34274. })(BABYLON || (BABYLON = {}));
  34275. //# sourceMappingURL=babylon.tags.js.map
  34276. var BABYLON;
  34277. (function (BABYLON) {
  34278. var Internals;
  34279. (function (Internals) {
  34280. var AndOrNotEvaluator = (function () {
  34281. function AndOrNotEvaluator() {
  34282. }
  34283. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34284. if (!query.match(/\([^\(\)]*\)/g)) {
  34285. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34286. }
  34287. else {
  34288. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34289. // remove parenthesis
  34290. r = r.slice(1, r.length - 1);
  34291. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34292. });
  34293. }
  34294. if (query === "true") {
  34295. return true;
  34296. }
  34297. if (query === "false") {
  34298. return false;
  34299. }
  34300. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34301. };
  34302. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34303. evaluateCallback = evaluateCallback || (function (r) {
  34304. return r === "true" ? true : false;
  34305. });
  34306. var result;
  34307. var or = parenthesisContent.split("||");
  34308. for (var i in or) {
  34309. if (or.hasOwnProperty(i)) {
  34310. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34311. var and = ori.split("&&");
  34312. if (and.length > 1) {
  34313. for (var j = 0; j < and.length; ++j) {
  34314. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34315. if (andj !== "true" && andj !== "false") {
  34316. if (andj[0] === "!") {
  34317. result = !evaluateCallback(andj.substring(1));
  34318. }
  34319. else {
  34320. result = evaluateCallback(andj);
  34321. }
  34322. }
  34323. else {
  34324. result = andj === "true" ? true : false;
  34325. }
  34326. if (!result) {
  34327. ori = "false";
  34328. break;
  34329. }
  34330. }
  34331. }
  34332. if (result || ori === "true") {
  34333. result = true;
  34334. break;
  34335. }
  34336. // result equals false (or undefined)
  34337. if (ori !== "true" && ori !== "false") {
  34338. if (ori[0] === "!") {
  34339. result = !evaluateCallback(ori.substring(1));
  34340. }
  34341. else {
  34342. result = evaluateCallback(ori);
  34343. }
  34344. }
  34345. else {
  34346. result = ori === "true" ? true : false;
  34347. }
  34348. }
  34349. }
  34350. // the whole parenthesis scope is replaced by 'true' or 'false'
  34351. return result ? "true" : "false";
  34352. };
  34353. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34354. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34355. // remove whitespaces
  34356. r = r.replace(/[\s]/g, function () { return ""; });
  34357. return r.length % 2 ? "!" : "";
  34358. });
  34359. booleanString = booleanString.trim();
  34360. if (booleanString === "!true") {
  34361. booleanString = "false";
  34362. }
  34363. else if (booleanString === "!false") {
  34364. booleanString = "true";
  34365. }
  34366. return booleanString;
  34367. };
  34368. return AndOrNotEvaluator;
  34369. }());
  34370. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34371. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34372. })(BABYLON || (BABYLON = {}));
  34373. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34374. var BABYLON;
  34375. (function (BABYLON) {
  34376. var PostProcessRenderPass = (function () {
  34377. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34378. this._enabled = true;
  34379. this._refCount = 0;
  34380. this._name = name;
  34381. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34382. this.setRenderList(renderList);
  34383. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34384. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34385. this._scene = scene;
  34386. this._renderList = renderList;
  34387. }
  34388. // private
  34389. PostProcessRenderPass.prototype._incRefCount = function () {
  34390. if (this._refCount === 0) {
  34391. this._scene.customRenderTargets.push(this._renderTexture);
  34392. }
  34393. return ++this._refCount;
  34394. };
  34395. PostProcessRenderPass.prototype._decRefCount = function () {
  34396. this._refCount--;
  34397. if (this._refCount <= 0) {
  34398. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34399. }
  34400. return this._refCount;
  34401. };
  34402. PostProcessRenderPass.prototype._update = function () {
  34403. this.setRenderList(this._renderList);
  34404. };
  34405. // public
  34406. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34407. this._renderTexture.renderList = renderList;
  34408. };
  34409. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34410. return this._renderTexture;
  34411. };
  34412. return PostProcessRenderPass;
  34413. }());
  34414. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34415. })(BABYLON || (BABYLON = {}));
  34416. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34417. var BABYLON;
  34418. (function (BABYLON) {
  34419. var PostProcessRenderEffect = (function () {
  34420. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34421. this._engine = engine;
  34422. this._name = name;
  34423. this._singleInstance = singleInstance || true;
  34424. this._getPostProcess = getPostProcess;
  34425. this._cameras = [];
  34426. this._indicesForCamera = [];
  34427. this._postProcesses = {};
  34428. this._renderPasses = {};
  34429. this._renderEffectAsPasses = {};
  34430. }
  34431. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34432. get: function () {
  34433. for (var index in this._postProcesses) {
  34434. if (!this._postProcesses[index].isSupported) {
  34435. return false;
  34436. }
  34437. }
  34438. return true;
  34439. },
  34440. enumerable: true,
  34441. configurable: true
  34442. });
  34443. PostProcessRenderEffect.prototype._update = function () {
  34444. for (var renderPassName in this._renderPasses) {
  34445. this._renderPasses[renderPassName]._update();
  34446. }
  34447. };
  34448. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34449. this._renderPasses[renderPass._name] = renderPass;
  34450. this._linkParameters();
  34451. };
  34452. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34453. delete this._renderPasses[renderPass._name];
  34454. this._linkParameters();
  34455. };
  34456. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34457. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34458. this._linkParameters();
  34459. };
  34460. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34461. for (var renderPassName in this._renderPasses) {
  34462. if (renderPassName === passName) {
  34463. return this._renderPasses[passName];
  34464. }
  34465. }
  34466. };
  34467. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34468. this._renderPasses = {};
  34469. this._linkParameters();
  34470. };
  34471. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34472. var cameraKey;
  34473. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34474. for (var i = 0; i < _cam.length; i++) {
  34475. var camera = _cam[i];
  34476. var cameraName = camera.name;
  34477. if (this._singleInstance) {
  34478. cameraKey = 0;
  34479. }
  34480. else {
  34481. cameraKey = cameraName;
  34482. }
  34483. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34484. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34485. if (!this._indicesForCamera[cameraName]) {
  34486. this._indicesForCamera[cameraName] = [];
  34487. }
  34488. this._indicesForCamera[cameraName].push(index);
  34489. if (this._cameras.indexOf(camera) === -1) {
  34490. this._cameras[cameraName] = camera;
  34491. }
  34492. for (var passName in this._renderPasses) {
  34493. this._renderPasses[passName]._incRefCount();
  34494. }
  34495. }
  34496. this._linkParameters();
  34497. };
  34498. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34499. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34500. for (var i = 0; i < _cam.length; i++) {
  34501. var camera = _cam[i];
  34502. var cameraName = camera.name;
  34503. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34504. var index = this._cameras.indexOf(cameraName);
  34505. this._indicesForCamera.splice(index, 1);
  34506. this._cameras.splice(index, 1);
  34507. for (var passName in this._renderPasses) {
  34508. this._renderPasses[passName]._decRefCount();
  34509. }
  34510. }
  34511. };
  34512. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34513. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34514. for (var i = 0; i < _cam.length; i++) {
  34515. var camera = _cam[i];
  34516. var cameraName = camera.name;
  34517. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34518. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34519. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34520. }
  34521. }
  34522. for (var passName in this._renderPasses) {
  34523. this._renderPasses[passName]._incRefCount();
  34524. }
  34525. }
  34526. };
  34527. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34528. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34529. for (var i = 0; i < _cam.length; i++) {
  34530. var camera = _cam[i];
  34531. var cameraName = camera.Name;
  34532. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34533. for (var passName in this._renderPasses) {
  34534. this._renderPasses[passName]._decRefCount();
  34535. }
  34536. }
  34537. };
  34538. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34539. if (this._singleInstance) {
  34540. return this._postProcesses[0];
  34541. }
  34542. else {
  34543. return this._postProcesses[camera.name];
  34544. }
  34545. };
  34546. PostProcessRenderEffect.prototype._linkParameters = function () {
  34547. var _this = this;
  34548. for (var index in this._postProcesses) {
  34549. if (this.applyParameters) {
  34550. this.applyParameters(this._postProcesses[index]);
  34551. }
  34552. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34553. _this._linkTextures(effect);
  34554. });
  34555. }
  34556. };
  34557. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34558. for (var renderPassName in this._renderPasses) {
  34559. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34560. }
  34561. for (var renderEffectName in this._renderEffectAsPasses) {
  34562. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34563. }
  34564. };
  34565. return PostProcessRenderEffect;
  34566. }());
  34567. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34568. })(BABYLON || (BABYLON = {}));
  34569. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34570. var BABYLON;
  34571. (function (BABYLON) {
  34572. var PostProcessRenderPipeline = (function () {
  34573. function PostProcessRenderPipeline(engine, name) {
  34574. this._engine = engine;
  34575. this._name = name;
  34576. this._renderEffects = {};
  34577. this._renderEffectsForIsolatedPass = {};
  34578. this._cameras = [];
  34579. }
  34580. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34581. get: function () {
  34582. for (var renderEffectName in this._renderEffects) {
  34583. if (!this._renderEffects[renderEffectName].isSupported) {
  34584. return false;
  34585. }
  34586. }
  34587. return true;
  34588. },
  34589. enumerable: true,
  34590. configurable: true
  34591. });
  34592. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34593. this._renderEffects[renderEffect._name] = renderEffect;
  34594. };
  34595. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34596. var renderEffects = this._renderEffects[renderEffectName];
  34597. if (!renderEffects) {
  34598. return;
  34599. }
  34600. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34601. };
  34602. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34603. var renderEffects = this._renderEffects[renderEffectName];
  34604. if (!renderEffects) {
  34605. return;
  34606. }
  34607. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34608. };
  34609. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34610. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34611. var indicesToDelete = [];
  34612. var i;
  34613. for (i = 0; i < _cam.length; i++) {
  34614. var camera = _cam[i];
  34615. var cameraName = camera.name;
  34616. if (this._cameras.indexOf(camera) === -1) {
  34617. this._cameras[cameraName] = camera;
  34618. }
  34619. else if (unique) {
  34620. indicesToDelete.push(i);
  34621. }
  34622. }
  34623. for (i = 0; i < indicesToDelete.length; i++) {
  34624. cameras.splice(indicesToDelete[i], 1);
  34625. }
  34626. for (var renderEffectName in this._renderEffects) {
  34627. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34628. }
  34629. };
  34630. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34631. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34632. for (var renderEffectName in this._renderEffects) {
  34633. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34634. }
  34635. for (var i = 0; i < _cam.length; i++) {
  34636. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34637. }
  34638. };
  34639. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34640. var _this = this;
  34641. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34642. var pass = null;
  34643. var renderEffectName;
  34644. for (renderEffectName in this._renderEffects) {
  34645. pass = this._renderEffects[renderEffectName].getPass(passName);
  34646. if (pass != null) {
  34647. break;
  34648. }
  34649. }
  34650. if (pass === null) {
  34651. return;
  34652. }
  34653. for (renderEffectName in this._renderEffects) {
  34654. this._renderEffects[renderEffectName]._disable(_cam);
  34655. }
  34656. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  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].emptyPasses();
  34662. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34663. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34664. }
  34665. };
  34666. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34667. var _this = this;
  34668. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34669. for (var i = 0; i < _cam.length; i++) {
  34670. var camera = _cam[i];
  34671. var cameraName = camera.name;
  34672. 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); });
  34673. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34674. }
  34675. for (var renderEffectName in this._renderEffects) {
  34676. this._renderEffects[renderEffectName]._enable(_cam);
  34677. }
  34678. };
  34679. PostProcessRenderPipeline.prototype._update = function () {
  34680. for (var renderEffectName in this._renderEffects) {
  34681. this._renderEffects[renderEffectName]._update();
  34682. }
  34683. for (var i = 0; i < this._cameras.length; i++) {
  34684. var cameraName = this._cameras[i].name;
  34685. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34686. this._renderEffectsForIsolatedPass[cameraName]._update();
  34687. }
  34688. }
  34689. };
  34690. PostProcessRenderPipeline.prototype.dispose = function () {
  34691. // Must be implemented by children
  34692. };
  34693. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34694. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34695. return PostProcessRenderPipeline;
  34696. }());
  34697. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34698. })(BABYLON || (BABYLON = {}));
  34699. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34700. var BABYLON;
  34701. (function (BABYLON) {
  34702. var PostProcessRenderPipelineManager = (function () {
  34703. function PostProcessRenderPipelineManager() {
  34704. this._renderPipelines = {};
  34705. }
  34706. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34707. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34708. };
  34709. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34710. var renderPipeline = this._renderPipelines[renderPipelineName];
  34711. if (!renderPipeline) {
  34712. return;
  34713. }
  34714. renderPipeline._attachCameras(cameras, unique);
  34715. };
  34716. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34717. var renderPipeline = this._renderPipelines[renderPipelineName];
  34718. if (!renderPipeline) {
  34719. return;
  34720. }
  34721. renderPipeline._detachCameras(cameras);
  34722. };
  34723. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34724. var renderPipeline = this._renderPipelines[renderPipelineName];
  34725. if (!renderPipeline) {
  34726. return;
  34727. }
  34728. renderPipeline._enableEffect(renderEffectName, cameras);
  34729. };
  34730. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34731. var renderPipeline = this._renderPipelines[renderPipelineName];
  34732. if (!renderPipeline) {
  34733. return;
  34734. }
  34735. renderPipeline._disableEffect(renderEffectName, cameras);
  34736. };
  34737. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34738. var renderPipeline = this._renderPipelines[renderPipelineName];
  34739. if (!renderPipeline) {
  34740. return;
  34741. }
  34742. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34743. };
  34744. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34745. var renderPipeline = this._renderPipelines[renderPipelineName];
  34746. if (!renderPipeline) {
  34747. return;
  34748. }
  34749. renderPipeline._disableDisplayOnlyPass(cameras);
  34750. };
  34751. PostProcessRenderPipelineManager.prototype.update = function () {
  34752. for (var renderPipelineName in this._renderPipelines) {
  34753. var pipeline = this._renderPipelines[renderPipelineName];
  34754. if (!pipeline.isSupported) {
  34755. pipeline.dispose();
  34756. delete this._renderPipelines[renderPipelineName];
  34757. }
  34758. else {
  34759. pipeline._update();
  34760. }
  34761. }
  34762. };
  34763. return PostProcessRenderPipelineManager;
  34764. }());
  34765. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34766. })(BABYLON || (BABYLON = {}));
  34767. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34768. var BABYLON;
  34769. (function (BABYLON) {
  34770. var BoundingBoxRenderer = (function () {
  34771. function BoundingBoxRenderer(scene) {
  34772. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34773. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34774. this.showBackLines = true;
  34775. this.renderList = new BABYLON.SmartArray(32);
  34776. this._vertexBuffers = {};
  34777. this._scene = scene;
  34778. }
  34779. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34780. if (this._colorShader) {
  34781. return;
  34782. }
  34783. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34784. attributes: [BABYLON.VertexBuffer.PositionKind],
  34785. uniforms: ["worldViewProjection", "color"]
  34786. });
  34787. var engine = this._scene.getEngine();
  34788. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34789. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34790. 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]);
  34791. };
  34792. BoundingBoxRenderer.prototype.reset = function () {
  34793. this.renderList.reset();
  34794. };
  34795. BoundingBoxRenderer.prototype.render = function () {
  34796. if (this.renderList.length === 0) {
  34797. return;
  34798. }
  34799. this._prepareRessources();
  34800. if (!this._colorShader.isReady()) {
  34801. return;
  34802. }
  34803. var engine = this._scene.getEngine();
  34804. engine.setDepthWrite(false);
  34805. this._colorShader._preBind();
  34806. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34807. var boundingBox = this.renderList.data[boundingBoxIndex];
  34808. var min = boundingBox.minimum;
  34809. var max = boundingBox.maximum;
  34810. var diff = max.subtract(min);
  34811. var median = min.add(diff.scale(0.5));
  34812. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34813. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34814. .multiply(boundingBox.getWorldMatrix());
  34815. // VBOs
  34816. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34817. if (this.showBackLines) {
  34818. // Back
  34819. engine.setDepthFunctionToGreaterOrEqual();
  34820. this._scene.resetCachedMaterial();
  34821. this._colorShader.setColor4("color", this.backColor.toColor4());
  34822. this._colorShader.bind(worldMatrix);
  34823. // Draw order
  34824. engine.draw(false, 0, 24);
  34825. }
  34826. // Front
  34827. engine.setDepthFunctionToLess();
  34828. this._scene.resetCachedMaterial();
  34829. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34830. this._colorShader.bind(worldMatrix);
  34831. // Draw order
  34832. engine.draw(false, 0, 24);
  34833. }
  34834. this._colorShader.unbind();
  34835. engine.setDepthFunctionToLessOrEqual();
  34836. engine.setDepthWrite(true);
  34837. };
  34838. BoundingBoxRenderer.prototype.dispose = function () {
  34839. if (!this._colorShader) {
  34840. return;
  34841. }
  34842. this._colorShader.dispose();
  34843. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34844. if (buffer) {
  34845. buffer.dispose();
  34846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34847. }
  34848. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34849. };
  34850. return BoundingBoxRenderer;
  34851. }());
  34852. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34853. })(BABYLON || (BABYLON = {}));
  34854. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34855. var BABYLON;
  34856. (function (BABYLON) {
  34857. var Condition = (function () {
  34858. function Condition(actionManager) {
  34859. this._actionManager = actionManager;
  34860. }
  34861. Condition.prototype.isValid = function () {
  34862. return true;
  34863. };
  34864. Condition.prototype._getProperty = function (propertyPath) {
  34865. return this._actionManager._getProperty(propertyPath);
  34866. };
  34867. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34868. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34869. };
  34870. Condition.prototype.serialize = function () {
  34871. };
  34872. Condition.prototype._serialize = function (serializedCondition) {
  34873. return {
  34874. type: 2,
  34875. children: [],
  34876. name: serializedCondition.name,
  34877. properties: serializedCondition.properties
  34878. };
  34879. };
  34880. return Condition;
  34881. }());
  34882. BABYLON.Condition = Condition;
  34883. var ValueCondition = (function (_super) {
  34884. __extends(ValueCondition, _super);
  34885. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34886. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34887. _super.call(this, actionManager);
  34888. this.propertyPath = propertyPath;
  34889. this.value = value;
  34890. this.operator = operator;
  34891. this._target = target;
  34892. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34893. this._property = this._getProperty(this.propertyPath);
  34894. }
  34895. Object.defineProperty(ValueCondition, "IsEqual", {
  34896. get: function () {
  34897. return ValueCondition._IsEqual;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(ValueCondition, "IsDifferent", {
  34903. get: function () {
  34904. return ValueCondition._IsDifferent;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. Object.defineProperty(ValueCondition, "IsGreater", {
  34910. get: function () {
  34911. return ValueCondition._IsGreater;
  34912. },
  34913. enumerable: true,
  34914. configurable: true
  34915. });
  34916. Object.defineProperty(ValueCondition, "IsLesser", {
  34917. get: function () {
  34918. return ValueCondition._IsLesser;
  34919. },
  34920. enumerable: true,
  34921. configurable: true
  34922. });
  34923. // Methods
  34924. ValueCondition.prototype.isValid = function () {
  34925. switch (this.operator) {
  34926. case ValueCondition.IsGreater:
  34927. return this._effectiveTarget[this._property] > this.value;
  34928. case ValueCondition.IsLesser:
  34929. return this._effectiveTarget[this._property] < this.value;
  34930. case ValueCondition.IsEqual:
  34931. case ValueCondition.IsDifferent:
  34932. var check;
  34933. if (this.value.equals) {
  34934. check = this.value.equals(this._effectiveTarget[this._property]);
  34935. }
  34936. else {
  34937. check = this.value === this._effectiveTarget[this._property];
  34938. }
  34939. return this.operator === ValueCondition.IsEqual ? check : !check;
  34940. }
  34941. return false;
  34942. };
  34943. ValueCondition.prototype.serialize = function () {
  34944. return this._serialize({
  34945. name: "ValueCondition",
  34946. properties: [
  34947. BABYLON.Action._GetTargetProperty(this._target),
  34948. { name: "propertyPath", value: this.propertyPath },
  34949. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34950. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34951. ]
  34952. });
  34953. };
  34954. ValueCondition.GetOperatorName = function (operator) {
  34955. switch (operator) {
  34956. case ValueCondition._IsEqual: return "IsEqual";
  34957. case ValueCondition._IsDifferent: return "IsDifferent";
  34958. case ValueCondition._IsGreater: return "IsGreater";
  34959. case ValueCondition._IsLesser: return "IsLesser";
  34960. default: return "";
  34961. }
  34962. };
  34963. // Statics
  34964. ValueCondition._IsEqual = 0;
  34965. ValueCondition._IsDifferent = 1;
  34966. ValueCondition._IsGreater = 2;
  34967. ValueCondition._IsLesser = 3;
  34968. return ValueCondition;
  34969. }(Condition));
  34970. BABYLON.ValueCondition = ValueCondition;
  34971. var PredicateCondition = (function (_super) {
  34972. __extends(PredicateCondition, _super);
  34973. function PredicateCondition(actionManager, predicate) {
  34974. _super.call(this, actionManager);
  34975. this.predicate = predicate;
  34976. }
  34977. PredicateCondition.prototype.isValid = function () {
  34978. return this.predicate();
  34979. };
  34980. return PredicateCondition;
  34981. }(Condition));
  34982. BABYLON.PredicateCondition = PredicateCondition;
  34983. var StateCondition = (function (_super) {
  34984. __extends(StateCondition, _super);
  34985. function StateCondition(actionManager, target, value) {
  34986. _super.call(this, actionManager);
  34987. this.value = value;
  34988. this._target = target;
  34989. }
  34990. // Methods
  34991. StateCondition.prototype.isValid = function () {
  34992. return this._target.state === this.value;
  34993. };
  34994. StateCondition.prototype.serialize = function () {
  34995. return this._serialize({
  34996. name: "StateCondition",
  34997. properties: [
  34998. BABYLON.Action._GetTargetProperty(this._target),
  34999. { name: "value", value: this.value }
  35000. ]
  35001. });
  35002. };
  35003. return StateCondition;
  35004. }(Condition));
  35005. BABYLON.StateCondition = StateCondition;
  35006. })(BABYLON || (BABYLON = {}));
  35007. //# sourceMappingURL=babylon.condition.js.map
  35008. var BABYLON;
  35009. (function (BABYLON) {
  35010. var Action = (function () {
  35011. function Action(triggerOptions, condition) {
  35012. this.triggerOptions = triggerOptions;
  35013. if (triggerOptions.parameter) {
  35014. this.trigger = triggerOptions.trigger;
  35015. this._triggerParameter = triggerOptions.parameter;
  35016. }
  35017. else {
  35018. this.trigger = triggerOptions;
  35019. }
  35020. this._nextActiveAction = this;
  35021. this._condition = condition;
  35022. }
  35023. // Methods
  35024. Action.prototype._prepare = function () {
  35025. };
  35026. Action.prototype.getTriggerParameter = function () {
  35027. return this._triggerParameter;
  35028. };
  35029. Action.prototype._executeCurrent = function (evt) {
  35030. if (this._nextActiveAction._condition) {
  35031. var condition = this._nextActiveAction._condition;
  35032. var currentRenderId = this._actionManager.getScene().getRenderId();
  35033. // We cache the current evaluation for the current frame
  35034. if (condition._evaluationId === currentRenderId) {
  35035. if (!condition._currentResult) {
  35036. return;
  35037. }
  35038. }
  35039. else {
  35040. condition._evaluationId = currentRenderId;
  35041. if (!condition.isValid()) {
  35042. condition._currentResult = false;
  35043. return;
  35044. }
  35045. condition._currentResult = true;
  35046. }
  35047. }
  35048. this._nextActiveAction.execute(evt);
  35049. this.skipToNextActiveAction();
  35050. };
  35051. Action.prototype.execute = function (evt) {
  35052. };
  35053. Action.prototype.skipToNextActiveAction = function () {
  35054. if (this._nextActiveAction._child) {
  35055. if (!this._nextActiveAction._child._actionManager) {
  35056. this._nextActiveAction._child._actionManager = this._actionManager;
  35057. }
  35058. this._nextActiveAction = this._nextActiveAction._child;
  35059. }
  35060. else {
  35061. this._nextActiveAction = this;
  35062. }
  35063. };
  35064. Action.prototype.then = function (action) {
  35065. this._child = action;
  35066. action._actionManager = this._actionManager;
  35067. action._prepare();
  35068. return action;
  35069. };
  35070. Action.prototype._getProperty = function (propertyPath) {
  35071. return this._actionManager._getProperty(propertyPath);
  35072. };
  35073. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35074. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35075. };
  35076. Action.prototype.serialize = function (parent) {
  35077. };
  35078. // Called by BABYLON.Action objects in serialize(...). Internal use
  35079. Action.prototype._serialize = function (serializedAction, parent) {
  35080. var serializationObject = {
  35081. type: 1,
  35082. children: [],
  35083. name: serializedAction.name,
  35084. properties: serializedAction.properties || []
  35085. };
  35086. // Serialize child
  35087. if (this._child) {
  35088. this._child.serialize(serializationObject);
  35089. }
  35090. // Check if "this" has a condition
  35091. if (this._condition) {
  35092. var serializedCondition = this._condition.serialize();
  35093. serializedCondition.children.push(serializationObject);
  35094. if (parent) {
  35095. parent.children.push(serializedCondition);
  35096. }
  35097. return serializedCondition;
  35098. }
  35099. if (parent) {
  35100. parent.children.push(serializationObject);
  35101. }
  35102. return serializationObject;
  35103. };
  35104. Action._SerializeValueAsString = function (value) {
  35105. if (typeof value === "number") {
  35106. return value.toString();
  35107. }
  35108. if (typeof value === "boolean") {
  35109. return value ? "true" : "false";
  35110. }
  35111. if (value instanceof BABYLON.Vector2) {
  35112. return value.x + ", " + value.y;
  35113. }
  35114. if (value instanceof BABYLON.Vector3) {
  35115. return value.x + ", " + value.y + ", " + value.z;
  35116. }
  35117. if (value instanceof BABYLON.Color3) {
  35118. return value.r + ", " + value.g + ", " + value.b;
  35119. }
  35120. if (value instanceof BABYLON.Color4) {
  35121. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35122. }
  35123. return value; // string
  35124. };
  35125. Action._GetTargetProperty = function (target) {
  35126. return {
  35127. name: "target",
  35128. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35129. : target instanceof BABYLON.Light ? "LightProperties"
  35130. : target instanceof BABYLON.Camera ? "CameraProperties"
  35131. : "SceneProperties",
  35132. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35133. };
  35134. };
  35135. return Action;
  35136. }());
  35137. BABYLON.Action = Action;
  35138. })(BABYLON || (BABYLON = {}));
  35139. //# sourceMappingURL=babylon.action.js.map
  35140. var BABYLON;
  35141. (function (BABYLON) {
  35142. /**
  35143. * ActionEvent is the event beint sent when an action is triggered.
  35144. */
  35145. var ActionEvent = (function () {
  35146. /**
  35147. * @constructor
  35148. * @param source The mesh or sprite that triggered the action.
  35149. * @param pointerX The X mouse cursor position at the time of the event
  35150. * @param pointerY The Y mouse cursor position at the time of the event
  35151. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35152. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35153. */
  35154. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35155. this.source = source;
  35156. this.pointerX = pointerX;
  35157. this.pointerY = pointerY;
  35158. this.meshUnderPointer = meshUnderPointer;
  35159. this.sourceEvent = sourceEvent;
  35160. this.additionalData = additionalData;
  35161. }
  35162. /**
  35163. * Helper function to auto-create an ActionEvent from a source mesh.
  35164. * @param source The source mesh that triggered the event
  35165. * @param evt {Event} The original (browser) event
  35166. */
  35167. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35168. var scene = source.getScene();
  35169. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35170. };
  35171. /**
  35172. * Helper function to auto-create an ActionEvent from a source mesh.
  35173. * @param source The source sprite that triggered the event
  35174. * @param scene Scene associated with the sprite
  35175. * @param evt {Event} The original (browser) event
  35176. */
  35177. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35178. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35179. };
  35180. /**
  35181. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35182. * @param scene the scene where the event occurred
  35183. * @param evt {Event} The original (browser) event
  35184. */
  35185. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35186. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35187. };
  35188. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35189. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35190. };
  35191. return ActionEvent;
  35192. }());
  35193. BABYLON.ActionEvent = ActionEvent;
  35194. /**
  35195. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35196. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35197. */
  35198. var ActionManager = (function () {
  35199. function ActionManager(scene) {
  35200. // Members
  35201. this.actions = new Array();
  35202. this.hoverCursor = '';
  35203. this._scene = scene;
  35204. scene._actionManagers.push(this);
  35205. }
  35206. Object.defineProperty(ActionManager, "NothingTrigger", {
  35207. get: function () {
  35208. return ActionManager._NothingTrigger;
  35209. },
  35210. enumerable: true,
  35211. configurable: true
  35212. });
  35213. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35214. get: function () {
  35215. return ActionManager._OnPickTrigger;
  35216. },
  35217. enumerable: true,
  35218. configurable: true
  35219. });
  35220. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35221. get: function () {
  35222. return ActionManager._OnLeftPickTrigger;
  35223. },
  35224. enumerable: true,
  35225. configurable: true
  35226. });
  35227. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35228. get: function () {
  35229. return ActionManager._OnRightPickTrigger;
  35230. },
  35231. enumerable: true,
  35232. configurable: true
  35233. });
  35234. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35235. get: function () {
  35236. return ActionManager._OnCenterPickTrigger;
  35237. },
  35238. enumerable: true,
  35239. configurable: true
  35240. });
  35241. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35242. get: function () {
  35243. return ActionManager._OnPickDownTrigger;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35249. get: function () {
  35250. return ActionManager._OnPickUpTrigger;
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35256. /// This trigger will only be raised if you also declared a OnPickDown
  35257. get: function () {
  35258. return ActionManager._OnPickOutTrigger;
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35264. get: function () {
  35265. return ActionManager._OnLongPressTrigger;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35271. get: function () {
  35272. return ActionManager._OnPointerOverTrigger;
  35273. },
  35274. enumerable: true,
  35275. configurable: true
  35276. });
  35277. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35278. get: function () {
  35279. return ActionManager._OnPointerOutTrigger;
  35280. },
  35281. enumerable: true,
  35282. configurable: true
  35283. });
  35284. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35285. get: function () {
  35286. return ActionManager._OnEveryFrameTrigger;
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35292. get: function () {
  35293. return ActionManager._OnIntersectionEnterTrigger;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35299. get: function () {
  35300. return ActionManager._OnIntersectionExitTrigger;
  35301. },
  35302. enumerable: true,
  35303. configurable: true
  35304. });
  35305. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35306. get: function () {
  35307. return ActionManager._OnKeyDownTrigger;
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35313. get: function () {
  35314. return ActionManager._OnKeyUpTrigger;
  35315. },
  35316. enumerable: true,
  35317. configurable: true
  35318. });
  35319. // Methods
  35320. ActionManager.prototype.dispose = function () {
  35321. var index = this._scene._actionManagers.indexOf(this);
  35322. if (index > -1) {
  35323. this._scene._actionManagers.splice(index, 1);
  35324. }
  35325. };
  35326. ActionManager.prototype.getScene = function () {
  35327. return this._scene;
  35328. };
  35329. /**
  35330. * Does this action manager handles actions of any of the given triggers
  35331. * @param {number[]} triggers - the triggers to be tested
  35332. * @return {boolean} whether one (or more) of the triggers is handeled
  35333. */
  35334. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35335. for (var index = 0; index < this.actions.length; index++) {
  35336. var action = this.actions[index];
  35337. if (triggers.indexOf(action.trigger) > -1) {
  35338. return true;
  35339. }
  35340. }
  35341. return false;
  35342. };
  35343. /**
  35344. * Does this action manager handles actions of a given trigger
  35345. * @param {number} trigger - the trigger to be tested
  35346. * @return {boolean} whether the trigger is handeled
  35347. */
  35348. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35349. for (var index = 0; index < this.actions.length; index++) {
  35350. var action = this.actions[index];
  35351. if (action.trigger === trigger) {
  35352. return true;
  35353. }
  35354. }
  35355. return false;
  35356. };
  35357. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35358. /**
  35359. * Does this action manager has pointer triggers
  35360. * @return {boolean} whether or not it has pointer triggers
  35361. */
  35362. get: function () {
  35363. for (var index = 0; index < this.actions.length; index++) {
  35364. var action = this.actions[index];
  35365. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35366. return true;
  35367. }
  35368. }
  35369. return false;
  35370. },
  35371. enumerable: true,
  35372. configurable: true
  35373. });
  35374. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35375. /**
  35376. * Does this action manager has pick triggers
  35377. * @return {boolean} whether or not it has pick triggers
  35378. */
  35379. get: function () {
  35380. for (var index = 0; index < this.actions.length; index++) {
  35381. var action = this.actions[index];
  35382. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35383. return true;
  35384. }
  35385. }
  35386. return false;
  35387. },
  35388. enumerable: true,
  35389. configurable: true
  35390. });
  35391. /**
  35392. * Registers an action to this action manager
  35393. * @param {BABYLON.Action} action - the action to be registered
  35394. * @return {BABYLON.Action} the action amended (prepared) after registration
  35395. */
  35396. ActionManager.prototype.registerAction = function (action) {
  35397. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35398. if (this.getScene().actionManager !== this) {
  35399. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35400. return null;
  35401. }
  35402. }
  35403. this.actions.push(action);
  35404. action._actionManager = this;
  35405. action._prepare();
  35406. return action;
  35407. };
  35408. /**
  35409. * Process a specific trigger
  35410. * @param {number} trigger - the trigger to process
  35411. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35412. */
  35413. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35414. for (var index = 0; index < this.actions.length; index++) {
  35415. var action = this.actions[index];
  35416. if (action.trigger === trigger) {
  35417. if (trigger === ActionManager.OnKeyUpTrigger
  35418. || trigger === ActionManager.OnKeyDownTrigger) {
  35419. var parameter = action.getTriggerParameter();
  35420. if (parameter) {
  35421. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35422. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35423. if (actualkey !== parameter.toLowerCase()) {
  35424. continue;
  35425. }
  35426. }
  35427. }
  35428. action._executeCurrent(evt);
  35429. }
  35430. }
  35431. };
  35432. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35433. var properties = propertyPath.split(".");
  35434. for (var index = 0; index < properties.length - 1; index++) {
  35435. target = target[properties[index]];
  35436. }
  35437. return target;
  35438. };
  35439. ActionManager.prototype._getProperty = function (propertyPath) {
  35440. var properties = propertyPath.split(".");
  35441. return properties[properties.length - 1];
  35442. };
  35443. ActionManager.prototype.serialize = function (name) {
  35444. var root = {
  35445. children: [],
  35446. name: name,
  35447. type: 3,
  35448. properties: [] // Empty for root but required
  35449. };
  35450. for (var i = 0; i < this.actions.length; i++) {
  35451. var triggerObject = {
  35452. type: 0,
  35453. children: [],
  35454. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35455. properties: []
  35456. };
  35457. var triggerOptions = this.actions[i].triggerOptions;
  35458. if (triggerOptions && typeof triggerOptions !== "number") {
  35459. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35460. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35461. }
  35462. else {
  35463. var parameter = {};
  35464. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35465. if (triggerOptions.parameter.mesh) {
  35466. parameter._meshId = triggerOptions.parameter.mesh.id;
  35467. }
  35468. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35469. }
  35470. }
  35471. // Serialize child action, recursively
  35472. this.actions[i].serialize(triggerObject);
  35473. // Add serialized trigger
  35474. root.children.push(triggerObject);
  35475. }
  35476. return root;
  35477. };
  35478. ActionManager.Parse = function (parsedActions, object, scene) {
  35479. var actionManager = new BABYLON.ActionManager(scene);
  35480. if (object === null)
  35481. scene.actionManager = actionManager;
  35482. else
  35483. object.actionManager = actionManager;
  35484. // instanciate a new object
  35485. var instanciate = function (name, params) {
  35486. var newInstance = Object.create(BABYLON[name].prototype);
  35487. newInstance.constructor.apply(newInstance, params);
  35488. return newInstance;
  35489. };
  35490. var parseParameter = function (name, value, target, propertyPath) {
  35491. if (propertyPath === null) {
  35492. // String, boolean or float
  35493. var floatValue = parseFloat(value);
  35494. if (value === "true" || value === "false")
  35495. return value === "true";
  35496. else
  35497. return isNaN(floatValue) ? value : floatValue;
  35498. }
  35499. var effectiveTarget = propertyPath.split(".");
  35500. var values = value.split(",");
  35501. // Get effective Target
  35502. for (var i = 0; i < effectiveTarget.length; i++) {
  35503. target = target[effectiveTarget[i]];
  35504. }
  35505. // Return appropriate value with its type
  35506. if (typeof (target) === "boolean")
  35507. return values[0] === "true";
  35508. if (typeof (target) === "string")
  35509. return values[0];
  35510. // Parameters with multiple values such as Vector3 etc.
  35511. var split = new Array();
  35512. for (var i = 0; i < values.length; i++)
  35513. split.push(parseFloat(values[i]));
  35514. if (target instanceof BABYLON.Vector3)
  35515. return BABYLON.Vector3.FromArray(split);
  35516. if (target instanceof BABYLON.Vector4)
  35517. return BABYLON.Vector4.FromArray(split);
  35518. if (target instanceof BABYLON.Color3)
  35519. return BABYLON.Color3.FromArray(split);
  35520. if (target instanceof BABYLON.Color4)
  35521. return BABYLON.Color4.FromArray(split);
  35522. return parseFloat(values[0]);
  35523. };
  35524. // traverse graph per trigger
  35525. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35526. if (combineArray === void 0) { combineArray = null; }
  35527. if (parsedAction.detached)
  35528. return;
  35529. var parameters = new Array();
  35530. var target = null;
  35531. var propertyPath = null;
  35532. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35533. // Parameters
  35534. if (parsedAction.type === 2)
  35535. parameters.push(actionManager);
  35536. else
  35537. parameters.push(trigger);
  35538. if (combine) {
  35539. var actions = new Array();
  35540. for (var j = 0; j < parsedAction.combine.length; j++) {
  35541. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35542. }
  35543. parameters.push(actions);
  35544. }
  35545. else {
  35546. for (var i = 0; i < parsedAction.properties.length; i++) {
  35547. var value = parsedAction.properties[i].value;
  35548. var name = parsedAction.properties[i].name;
  35549. var targetType = parsedAction.properties[i].targetType;
  35550. if (name === "target")
  35551. if (targetType !== null && targetType === "SceneProperties")
  35552. value = target = scene;
  35553. else
  35554. value = target = scene.getNodeByName(value);
  35555. else if (name === "parent")
  35556. value = scene.getNodeByName(value);
  35557. else if (name === "sound")
  35558. value = scene.getSoundByName(value);
  35559. else if (name !== "propertyPath") {
  35560. if (parsedAction.type === 2 && name === "operator")
  35561. value = BABYLON.ValueCondition[value];
  35562. else
  35563. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35564. }
  35565. else {
  35566. propertyPath = value;
  35567. }
  35568. parameters.push(value);
  35569. }
  35570. }
  35571. if (combineArray === null) {
  35572. parameters.push(condition);
  35573. }
  35574. else {
  35575. parameters.push(null);
  35576. }
  35577. // If interpolate value action
  35578. if (parsedAction.name === "InterpolateValueAction") {
  35579. var param = parameters[parameters.length - 2];
  35580. parameters[parameters.length - 1] = param;
  35581. parameters[parameters.length - 2] = condition;
  35582. }
  35583. // Action or condition(s) and not CombineAction
  35584. var newAction = instanciate(parsedAction.name, parameters);
  35585. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35586. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35587. if (action)
  35588. action.then(nothing);
  35589. else
  35590. actionManager.registerAction(nothing);
  35591. action = nothing;
  35592. }
  35593. if (combineArray === null) {
  35594. if (newAction instanceof BABYLON.Condition) {
  35595. condition = newAction;
  35596. newAction = action;
  35597. }
  35598. else {
  35599. condition = null;
  35600. if (action)
  35601. action.then(newAction);
  35602. else
  35603. actionManager.registerAction(newAction);
  35604. }
  35605. }
  35606. else {
  35607. combineArray.push(newAction);
  35608. }
  35609. for (var i = 0; i < parsedAction.children.length; i++)
  35610. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35611. };
  35612. // triggers
  35613. for (var i = 0; i < parsedActions.children.length; i++) {
  35614. var triggerParams;
  35615. var trigger = parsedActions.children[i];
  35616. if (trigger.properties.length > 0) {
  35617. var param = trigger.properties[0].value;
  35618. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35619. if (value._meshId) {
  35620. value.mesh = scene.getMeshByID(value._meshId);
  35621. }
  35622. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35623. }
  35624. else
  35625. triggerParams = BABYLON.ActionManager[trigger.name];
  35626. for (var j = 0; j < trigger.children.length; j++) {
  35627. if (!trigger.detached)
  35628. traverse(trigger.children[j], triggerParams, null, null);
  35629. }
  35630. }
  35631. };
  35632. ActionManager.GetTriggerName = function (trigger) {
  35633. switch (trigger) {
  35634. case 0: return "NothingTrigger";
  35635. case 1: return "OnPickTrigger";
  35636. case 2: return "OnLeftPickTrigger";
  35637. case 3: return "OnRightPickTrigger";
  35638. case 4: return "OnCenterPickTrigger";
  35639. case 5: return "OnPickDownTrigger";
  35640. case 6: return "OnPickUpTrigger";
  35641. case 7: return "OnLongPressTrigger";
  35642. case 8: return "OnPointerOverTrigger";
  35643. case 9: return "OnPointerOutTrigger";
  35644. case 10: return "OnEveryFrameTrigger";
  35645. case 11: return "OnIntersectionEnterTrigger";
  35646. case 12: return "OnIntersectionExitTrigger";
  35647. case 13: return "OnKeyDownTrigger";
  35648. case 14: return "OnKeyUpTrigger";
  35649. case 15: return "OnPickOutTrigger";
  35650. default: return "";
  35651. }
  35652. };
  35653. // Statics
  35654. ActionManager._NothingTrigger = 0;
  35655. ActionManager._OnPickTrigger = 1;
  35656. ActionManager._OnLeftPickTrigger = 2;
  35657. ActionManager._OnRightPickTrigger = 3;
  35658. ActionManager._OnCenterPickTrigger = 4;
  35659. ActionManager._OnPickDownTrigger = 5;
  35660. ActionManager._OnPickUpTrigger = 6;
  35661. ActionManager._OnLongPressTrigger = 7;
  35662. ActionManager._OnPointerOverTrigger = 8;
  35663. ActionManager._OnPointerOutTrigger = 9;
  35664. ActionManager._OnEveryFrameTrigger = 10;
  35665. ActionManager._OnIntersectionEnterTrigger = 11;
  35666. ActionManager._OnIntersectionExitTrigger = 12;
  35667. ActionManager._OnKeyDownTrigger = 13;
  35668. ActionManager._OnKeyUpTrigger = 14;
  35669. ActionManager._OnPickOutTrigger = 15;
  35670. ActionManager.DragMovementThreshold = 10; // in pixels
  35671. ActionManager.LongPressDelay = 500; // in milliseconds
  35672. return ActionManager;
  35673. }());
  35674. BABYLON.ActionManager = ActionManager;
  35675. })(BABYLON || (BABYLON = {}));
  35676. //# sourceMappingURL=babylon.actionManager.js.map
  35677. var BABYLON;
  35678. (function (BABYLON) {
  35679. var InterpolateValueAction = (function (_super) {
  35680. __extends(InterpolateValueAction, _super);
  35681. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35682. if (duration === void 0) { duration = 1000; }
  35683. _super.call(this, triggerOptions, condition);
  35684. this.propertyPath = propertyPath;
  35685. this.value = value;
  35686. this.duration = duration;
  35687. this.stopOtherAnimations = stopOtherAnimations;
  35688. this.onInterpolationDone = onInterpolationDone;
  35689. this._target = this._effectiveTarget = target;
  35690. }
  35691. InterpolateValueAction.prototype._prepare = function () {
  35692. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35693. this._property = this._getProperty(this.propertyPath);
  35694. };
  35695. InterpolateValueAction.prototype.execute = function () {
  35696. var scene = this._actionManager.getScene();
  35697. var keys = [
  35698. {
  35699. frame: 0,
  35700. value: this._effectiveTarget[this._property]
  35701. }, {
  35702. frame: 100,
  35703. value: this.value
  35704. }
  35705. ];
  35706. var dataType;
  35707. if (typeof this.value === "number") {
  35708. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35709. }
  35710. else if (this.value instanceof BABYLON.Color3) {
  35711. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35712. }
  35713. else if (this.value instanceof BABYLON.Vector3) {
  35714. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35715. }
  35716. else if (this.value instanceof BABYLON.Matrix) {
  35717. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35718. }
  35719. else if (this.value instanceof BABYLON.Quaternion) {
  35720. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35721. }
  35722. else {
  35723. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35724. return;
  35725. }
  35726. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35727. animation.setKeys(keys);
  35728. if (this.stopOtherAnimations) {
  35729. scene.stopAnimation(this._effectiveTarget);
  35730. }
  35731. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35732. };
  35733. InterpolateValueAction.prototype.serialize = function (parent) {
  35734. return _super.prototype._serialize.call(this, {
  35735. name: "InterpolateValueAction",
  35736. properties: [
  35737. BABYLON.Action._GetTargetProperty(this._target),
  35738. { name: "propertyPath", value: this.propertyPath },
  35739. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35740. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35741. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35742. ]
  35743. }, parent);
  35744. };
  35745. return InterpolateValueAction;
  35746. }(BABYLON.Action));
  35747. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35748. })(BABYLON || (BABYLON = {}));
  35749. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35750. var BABYLON;
  35751. (function (BABYLON) {
  35752. var SwitchBooleanAction = (function (_super) {
  35753. __extends(SwitchBooleanAction, _super);
  35754. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35755. _super.call(this, triggerOptions, condition);
  35756. this.propertyPath = propertyPath;
  35757. this._target = this._effectiveTarget = target;
  35758. }
  35759. SwitchBooleanAction.prototype._prepare = function () {
  35760. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35761. this._property = this._getProperty(this.propertyPath);
  35762. };
  35763. SwitchBooleanAction.prototype.execute = function () {
  35764. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35765. };
  35766. SwitchBooleanAction.prototype.serialize = function (parent) {
  35767. return _super.prototype._serialize.call(this, {
  35768. name: "SwitchBooleanAction",
  35769. properties: [
  35770. BABYLON.Action._GetTargetProperty(this._target),
  35771. { name: "propertyPath", value: this.propertyPath }
  35772. ]
  35773. }, parent);
  35774. };
  35775. return SwitchBooleanAction;
  35776. }(BABYLON.Action));
  35777. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35778. var SetStateAction = (function (_super) {
  35779. __extends(SetStateAction, _super);
  35780. function SetStateAction(triggerOptions, target, value, condition) {
  35781. _super.call(this, triggerOptions, condition);
  35782. this.value = value;
  35783. this._target = target;
  35784. }
  35785. SetStateAction.prototype.execute = function () {
  35786. this._target.state = this.value;
  35787. };
  35788. SetStateAction.prototype.serialize = function (parent) {
  35789. return _super.prototype._serialize.call(this, {
  35790. name: "SetStateAction",
  35791. properties: [
  35792. BABYLON.Action._GetTargetProperty(this._target),
  35793. { name: "value", value: this.value }
  35794. ]
  35795. }, parent);
  35796. };
  35797. return SetStateAction;
  35798. }(BABYLON.Action));
  35799. BABYLON.SetStateAction = SetStateAction;
  35800. var SetValueAction = (function (_super) {
  35801. __extends(SetValueAction, _super);
  35802. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35803. _super.call(this, triggerOptions, condition);
  35804. this.propertyPath = propertyPath;
  35805. this.value = value;
  35806. this._target = this._effectiveTarget = target;
  35807. }
  35808. SetValueAction.prototype._prepare = function () {
  35809. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35810. this._property = this._getProperty(this.propertyPath);
  35811. };
  35812. SetValueAction.prototype.execute = function () {
  35813. this._effectiveTarget[this._property] = this.value;
  35814. if (this._target.markAsDirty) {
  35815. this._target.markAsDirty(this._property);
  35816. }
  35817. };
  35818. SetValueAction.prototype.serialize = function (parent) {
  35819. return _super.prototype._serialize.call(this, {
  35820. name: "SetValueAction",
  35821. properties: [
  35822. BABYLON.Action._GetTargetProperty(this._target),
  35823. { name: "propertyPath", value: this.propertyPath },
  35824. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35825. ]
  35826. }, parent);
  35827. };
  35828. return SetValueAction;
  35829. }(BABYLON.Action));
  35830. BABYLON.SetValueAction = SetValueAction;
  35831. var IncrementValueAction = (function (_super) {
  35832. __extends(IncrementValueAction, _super);
  35833. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35834. _super.call(this, triggerOptions, condition);
  35835. this.propertyPath = propertyPath;
  35836. this.value = value;
  35837. this._target = this._effectiveTarget = target;
  35838. }
  35839. IncrementValueAction.prototype._prepare = function () {
  35840. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35841. this._property = this._getProperty(this.propertyPath);
  35842. if (typeof this._effectiveTarget[this._property] !== "number") {
  35843. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35844. }
  35845. };
  35846. IncrementValueAction.prototype.execute = function () {
  35847. this._effectiveTarget[this._property] += this.value;
  35848. if (this._target.markAsDirty) {
  35849. this._target.markAsDirty(this._property);
  35850. }
  35851. };
  35852. IncrementValueAction.prototype.serialize = function (parent) {
  35853. return _super.prototype._serialize.call(this, {
  35854. name: "IncrementValueAction",
  35855. properties: [
  35856. BABYLON.Action._GetTargetProperty(this._target),
  35857. { name: "propertyPath", value: this.propertyPath },
  35858. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35859. ]
  35860. }, parent);
  35861. };
  35862. return IncrementValueAction;
  35863. }(BABYLON.Action));
  35864. BABYLON.IncrementValueAction = IncrementValueAction;
  35865. var PlayAnimationAction = (function (_super) {
  35866. __extends(PlayAnimationAction, _super);
  35867. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35868. _super.call(this, triggerOptions, condition);
  35869. this.from = from;
  35870. this.to = to;
  35871. this.loop = loop;
  35872. this._target = target;
  35873. }
  35874. PlayAnimationAction.prototype._prepare = function () {
  35875. };
  35876. PlayAnimationAction.prototype.execute = function () {
  35877. var scene = this._actionManager.getScene();
  35878. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35879. };
  35880. PlayAnimationAction.prototype.serialize = function (parent) {
  35881. return _super.prototype._serialize.call(this, {
  35882. name: "PlayAnimationAction",
  35883. properties: [
  35884. BABYLON.Action._GetTargetProperty(this._target),
  35885. { name: "from", value: String(this.from) },
  35886. { name: "to", value: String(this.to) },
  35887. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35888. ]
  35889. }, parent);
  35890. };
  35891. return PlayAnimationAction;
  35892. }(BABYLON.Action));
  35893. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35894. var StopAnimationAction = (function (_super) {
  35895. __extends(StopAnimationAction, _super);
  35896. function StopAnimationAction(triggerOptions, target, condition) {
  35897. _super.call(this, triggerOptions, condition);
  35898. this._target = target;
  35899. }
  35900. StopAnimationAction.prototype._prepare = function () {
  35901. };
  35902. StopAnimationAction.prototype.execute = function () {
  35903. var scene = this._actionManager.getScene();
  35904. scene.stopAnimation(this._target);
  35905. };
  35906. StopAnimationAction.prototype.serialize = function (parent) {
  35907. return _super.prototype._serialize.call(this, {
  35908. name: "StopAnimationAction",
  35909. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35910. }, parent);
  35911. };
  35912. return StopAnimationAction;
  35913. }(BABYLON.Action));
  35914. BABYLON.StopAnimationAction = StopAnimationAction;
  35915. var DoNothingAction = (function (_super) {
  35916. __extends(DoNothingAction, _super);
  35917. function DoNothingAction(triggerOptions, condition) {
  35918. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35919. _super.call(this, triggerOptions, condition);
  35920. }
  35921. DoNothingAction.prototype.execute = function () {
  35922. };
  35923. DoNothingAction.prototype.serialize = function (parent) {
  35924. return _super.prototype._serialize.call(this, {
  35925. name: "DoNothingAction",
  35926. properties: []
  35927. }, parent);
  35928. };
  35929. return DoNothingAction;
  35930. }(BABYLON.Action));
  35931. BABYLON.DoNothingAction = DoNothingAction;
  35932. var CombineAction = (function (_super) {
  35933. __extends(CombineAction, _super);
  35934. function CombineAction(triggerOptions, children, condition) {
  35935. _super.call(this, triggerOptions, condition);
  35936. this.children = children;
  35937. }
  35938. CombineAction.prototype._prepare = function () {
  35939. for (var index = 0; index < this.children.length; index++) {
  35940. this.children[index]._actionManager = this._actionManager;
  35941. this.children[index]._prepare();
  35942. }
  35943. };
  35944. CombineAction.prototype.execute = function (evt) {
  35945. for (var index = 0; index < this.children.length; index++) {
  35946. this.children[index].execute(evt);
  35947. }
  35948. };
  35949. CombineAction.prototype.serialize = function (parent) {
  35950. var serializationObject = _super.prototype._serialize.call(this, {
  35951. name: "CombineAction",
  35952. properties: [],
  35953. combine: []
  35954. }, parent);
  35955. for (var i = 0; i < this.children.length; i++) {
  35956. serializationObject.combine.push(this.children[i].serialize(null));
  35957. }
  35958. return serializationObject;
  35959. };
  35960. return CombineAction;
  35961. }(BABYLON.Action));
  35962. BABYLON.CombineAction = CombineAction;
  35963. var ExecuteCodeAction = (function (_super) {
  35964. __extends(ExecuteCodeAction, _super);
  35965. function ExecuteCodeAction(triggerOptions, func, condition) {
  35966. _super.call(this, triggerOptions, condition);
  35967. this.func = func;
  35968. }
  35969. ExecuteCodeAction.prototype.execute = function (evt) {
  35970. this.func(evt);
  35971. };
  35972. return ExecuteCodeAction;
  35973. }(BABYLON.Action));
  35974. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  35975. var SetParentAction = (function (_super) {
  35976. __extends(SetParentAction, _super);
  35977. function SetParentAction(triggerOptions, target, parent, condition) {
  35978. _super.call(this, triggerOptions, condition);
  35979. this._target = target;
  35980. this._parent = parent;
  35981. }
  35982. SetParentAction.prototype._prepare = function () {
  35983. };
  35984. SetParentAction.prototype.execute = function () {
  35985. if (this._target.parent === this._parent) {
  35986. return;
  35987. }
  35988. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  35989. invertParentWorldMatrix.invert();
  35990. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  35991. this._target.parent = this._parent;
  35992. };
  35993. SetParentAction.prototype.serialize = function (parent) {
  35994. return _super.prototype._serialize.call(this, {
  35995. name: "SetParentAction",
  35996. properties: [
  35997. BABYLON.Action._GetTargetProperty(this._target),
  35998. BABYLON.Action._GetTargetProperty(this._parent),
  35999. ]
  36000. }, parent);
  36001. };
  36002. return SetParentAction;
  36003. }(BABYLON.Action));
  36004. BABYLON.SetParentAction = SetParentAction;
  36005. var PlaySoundAction = (function (_super) {
  36006. __extends(PlaySoundAction, _super);
  36007. function PlaySoundAction(triggerOptions, sound, condition) {
  36008. _super.call(this, triggerOptions, condition);
  36009. this._sound = sound;
  36010. }
  36011. PlaySoundAction.prototype._prepare = function () {
  36012. };
  36013. PlaySoundAction.prototype.execute = function () {
  36014. if (this._sound !== undefined)
  36015. this._sound.play();
  36016. };
  36017. PlaySoundAction.prototype.serialize = function (parent) {
  36018. return _super.prototype._serialize.call(this, {
  36019. name: "PlaySoundAction",
  36020. properties: [{ name: "sound", value: this._sound.name }]
  36021. }, parent);
  36022. };
  36023. return PlaySoundAction;
  36024. }(BABYLON.Action));
  36025. BABYLON.PlaySoundAction = PlaySoundAction;
  36026. var StopSoundAction = (function (_super) {
  36027. __extends(StopSoundAction, _super);
  36028. function StopSoundAction(triggerOptions, sound, condition) {
  36029. _super.call(this, triggerOptions, condition);
  36030. this._sound = sound;
  36031. }
  36032. StopSoundAction.prototype._prepare = function () {
  36033. };
  36034. StopSoundAction.prototype.execute = function () {
  36035. if (this._sound !== undefined)
  36036. this._sound.stop();
  36037. };
  36038. StopSoundAction.prototype.serialize = function (parent) {
  36039. return _super.prototype._serialize.call(this, {
  36040. name: "StopSoundAction",
  36041. properties: [{ name: "sound", value: this._sound.name }]
  36042. }, parent);
  36043. };
  36044. return StopSoundAction;
  36045. }(BABYLON.Action));
  36046. BABYLON.StopSoundAction = StopSoundAction;
  36047. })(BABYLON || (BABYLON = {}));
  36048. //# sourceMappingURL=babylon.directActions.js.map
  36049. var BABYLON;
  36050. (function (BABYLON) {
  36051. var Geometry = (function () {
  36052. function Geometry(id, scene, vertexData, updatable, mesh) {
  36053. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36054. this._totalVertices = 0;
  36055. this._isDisposed = false;
  36056. this.id = id;
  36057. this._engine = scene.getEngine();
  36058. this._meshes = [];
  36059. this._scene = scene;
  36060. //Init vertex buffer cache
  36061. this._vertexBuffers = {};
  36062. this._indices = [];
  36063. // vertexData
  36064. if (vertexData) {
  36065. this.setAllVerticesData(vertexData, updatable);
  36066. }
  36067. else {
  36068. this._totalVertices = 0;
  36069. this._indices = [];
  36070. }
  36071. // applyToMesh
  36072. if (mesh) {
  36073. if (mesh instanceof BABYLON.LinesMesh) {
  36074. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36075. this.updateExtend();
  36076. }
  36077. this.applyToMesh(mesh);
  36078. mesh.computeWorldMatrix(true);
  36079. }
  36080. }
  36081. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36082. /**
  36083. * 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
  36084. * @returns The Bias Vector
  36085. */
  36086. get: function () {
  36087. return this._boundingBias;
  36088. },
  36089. set: function (value) {
  36090. if (this._boundingBias && this._boundingBias.equals(value)) {
  36091. return;
  36092. }
  36093. this._boundingBias = value.clone();
  36094. this.updateBoundingInfo(true, null);
  36095. },
  36096. enumerable: true,
  36097. configurable: true
  36098. });
  36099. Object.defineProperty(Geometry.prototype, "extend", {
  36100. get: function () {
  36101. return this._extend;
  36102. },
  36103. enumerable: true,
  36104. configurable: true
  36105. });
  36106. Geometry.prototype.getScene = function () {
  36107. return this._scene;
  36108. };
  36109. Geometry.prototype.getEngine = function () {
  36110. return this._engine;
  36111. };
  36112. Geometry.prototype.isReady = function () {
  36113. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36114. };
  36115. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36116. get: function () {
  36117. for (var index = 0; index < this._meshes.length; index++) {
  36118. if (!this._meshes[index].doNotSerialize) {
  36119. return false;
  36120. }
  36121. }
  36122. return true;
  36123. },
  36124. enumerable: true,
  36125. configurable: true
  36126. });
  36127. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36128. vertexData.applyToGeometry(this, updatable);
  36129. this.notifyUpdate();
  36130. };
  36131. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36132. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36133. this.setVerticesBuffer(buffer);
  36134. };
  36135. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36136. var kind = buffer.getKind();
  36137. if (this._vertexBuffers[kind]) {
  36138. this._vertexBuffers[kind].dispose();
  36139. }
  36140. this._vertexBuffers[kind] = buffer;
  36141. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36142. var data = buffer.getData();
  36143. var stride = buffer.getStrideSize();
  36144. this._totalVertices = data.length / stride;
  36145. this.updateExtend(data, stride);
  36146. var meshes = this._meshes;
  36147. var numOfMeshes = meshes.length;
  36148. for (var index = 0; index < numOfMeshes; index++) {
  36149. var mesh = meshes[index];
  36150. mesh._resetPointsArrayCache();
  36151. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36152. mesh._createGlobalSubMesh();
  36153. mesh.computeWorldMatrix(true);
  36154. }
  36155. }
  36156. this.notifyUpdate(kind);
  36157. };
  36158. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36159. var vertexBuffer = this.getVertexBuffer(kind);
  36160. if (!vertexBuffer) {
  36161. return;
  36162. }
  36163. vertexBuffer.updateDirectly(data, offset);
  36164. this.notifyUpdate(kind);
  36165. };
  36166. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36167. var vertexBuffer = this.getVertexBuffer(kind);
  36168. if (!vertexBuffer) {
  36169. return;
  36170. }
  36171. vertexBuffer.update(data);
  36172. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36173. var stride = vertexBuffer.getStrideSize();
  36174. this._totalVertices = data.length / stride;
  36175. this.updateBoundingInfo(updateExtends, data);
  36176. }
  36177. this.notifyUpdate(kind);
  36178. };
  36179. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36180. if (updateExtends) {
  36181. this.updateExtend(data);
  36182. }
  36183. var meshes = this._meshes;
  36184. var numOfMeshes = meshes.length;
  36185. for (var index = 0; index < numOfMeshes; index++) {
  36186. var mesh = meshes[index];
  36187. mesh._resetPointsArrayCache();
  36188. if (updateExtends) {
  36189. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36190. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36191. var subMesh = mesh.subMeshes[subIndex];
  36192. subMesh.refreshBoundingInfo();
  36193. }
  36194. }
  36195. }
  36196. };
  36197. Geometry.prototype.getTotalVertices = function () {
  36198. if (!this.isReady()) {
  36199. return 0;
  36200. }
  36201. return this._totalVertices;
  36202. };
  36203. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36204. var vertexBuffer = this.getVertexBuffer(kind);
  36205. if (!vertexBuffer) {
  36206. return null;
  36207. }
  36208. var orig = vertexBuffer.getData();
  36209. if (!copyWhenShared || this._meshes.length === 1) {
  36210. return orig;
  36211. }
  36212. else {
  36213. var len = orig.length;
  36214. var copy = [];
  36215. for (var i = 0; i < len; i++) {
  36216. copy.push(orig[i]);
  36217. }
  36218. return copy;
  36219. }
  36220. };
  36221. Geometry.prototype.getVertexBuffer = function (kind) {
  36222. if (!this.isReady()) {
  36223. return null;
  36224. }
  36225. return this._vertexBuffers[kind];
  36226. };
  36227. Geometry.prototype.getVertexBuffers = function () {
  36228. if (!this.isReady()) {
  36229. return null;
  36230. }
  36231. return this._vertexBuffers;
  36232. };
  36233. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36234. if (!this._vertexBuffers) {
  36235. if (this._delayInfo) {
  36236. return this._delayInfo.indexOf(kind) !== -1;
  36237. }
  36238. return false;
  36239. }
  36240. return this._vertexBuffers[kind] !== undefined;
  36241. };
  36242. Geometry.prototype.getVerticesDataKinds = function () {
  36243. var result = [];
  36244. var kind;
  36245. if (!this._vertexBuffers && this._delayInfo) {
  36246. for (kind in this._delayInfo) {
  36247. result.push(kind);
  36248. }
  36249. }
  36250. else {
  36251. for (kind in this._vertexBuffers) {
  36252. result.push(kind);
  36253. }
  36254. }
  36255. return result;
  36256. };
  36257. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36258. if (this._indexBuffer) {
  36259. this._engine._releaseBuffer(this._indexBuffer);
  36260. }
  36261. this._indices = indices;
  36262. if (this._meshes.length !== 0 && this._indices) {
  36263. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36264. }
  36265. if (totalVertices !== undefined) {
  36266. this._totalVertices = totalVertices;
  36267. }
  36268. var meshes = this._meshes;
  36269. var numOfMeshes = meshes.length;
  36270. for (var index = 0; index < numOfMeshes; index++) {
  36271. meshes[index]._createGlobalSubMesh();
  36272. }
  36273. this.notifyUpdate();
  36274. };
  36275. Geometry.prototype.getTotalIndices = function () {
  36276. if (!this.isReady()) {
  36277. return 0;
  36278. }
  36279. return this._indices.length;
  36280. };
  36281. Geometry.prototype.getIndices = function (copyWhenShared) {
  36282. if (!this.isReady()) {
  36283. return null;
  36284. }
  36285. var orig = this._indices;
  36286. if (!copyWhenShared || this._meshes.length === 1) {
  36287. return orig;
  36288. }
  36289. else {
  36290. var len = orig.length;
  36291. var copy = [];
  36292. for (var i = 0; i < len; i++) {
  36293. copy.push(orig[i]);
  36294. }
  36295. return copy;
  36296. }
  36297. };
  36298. Geometry.prototype.getIndexBuffer = function () {
  36299. if (!this.isReady()) {
  36300. return null;
  36301. }
  36302. return this._indexBuffer;
  36303. };
  36304. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36305. var meshes = this._meshes;
  36306. var index = meshes.indexOf(mesh);
  36307. if (index === -1) {
  36308. return;
  36309. }
  36310. for (var kind in this._vertexBuffers) {
  36311. this._vertexBuffers[kind].dispose();
  36312. }
  36313. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36314. this._indexBuffer = null;
  36315. }
  36316. meshes.splice(index, 1);
  36317. mesh._geometry = null;
  36318. if (meshes.length === 0 && shouldDispose) {
  36319. this.dispose();
  36320. }
  36321. };
  36322. Geometry.prototype.applyToMesh = function (mesh) {
  36323. if (mesh._geometry === this) {
  36324. return;
  36325. }
  36326. var previousGeometry = mesh._geometry;
  36327. if (previousGeometry) {
  36328. previousGeometry.releaseForMesh(mesh);
  36329. }
  36330. var meshes = this._meshes;
  36331. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36332. mesh._geometry = this;
  36333. this._scene.pushGeometry(this);
  36334. meshes.push(mesh);
  36335. if (this.isReady()) {
  36336. this._applyToMesh(mesh);
  36337. }
  36338. else {
  36339. mesh._boundingInfo = this._boundingInfo;
  36340. }
  36341. };
  36342. Geometry.prototype.updateExtend = function (data, stride) {
  36343. if (data === void 0) { data = null; }
  36344. if (!data) {
  36345. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36346. }
  36347. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36348. };
  36349. Geometry.prototype._applyToMesh = function (mesh) {
  36350. var numOfMeshes = this._meshes.length;
  36351. // vertexBuffers
  36352. for (var kind in this._vertexBuffers) {
  36353. if (numOfMeshes === 1) {
  36354. this._vertexBuffers[kind].create();
  36355. }
  36356. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36357. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36358. mesh._resetPointsArrayCache();
  36359. if (!this._extend) {
  36360. this.updateExtend(this._vertexBuffers[kind].getData());
  36361. }
  36362. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36363. mesh._createGlobalSubMesh();
  36364. //bounding info was just created again, world matrix should be applied again.
  36365. mesh._updateBoundingInfo();
  36366. }
  36367. }
  36368. // indexBuffer
  36369. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36370. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36371. }
  36372. if (this._indexBuffer) {
  36373. this._indexBuffer.references = numOfMeshes;
  36374. }
  36375. };
  36376. Geometry.prototype.notifyUpdate = function (kind) {
  36377. if (this.onGeometryUpdated) {
  36378. this.onGeometryUpdated(this, kind);
  36379. }
  36380. };
  36381. Geometry.prototype.load = function (scene, onLoaded) {
  36382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36383. return;
  36384. }
  36385. if (this.isReady()) {
  36386. if (onLoaded) {
  36387. onLoaded();
  36388. }
  36389. return;
  36390. }
  36391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36392. this._queueLoad(scene, onLoaded);
  36393. };
  36394. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36395. var _this = this;
  36396. scene._addPendingData(this);
  36397. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36398. _this._delayLoadingFunction(JSON.parse(data), _this);
  36399. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36400. _this._delayInfo = [];
  36401. scene._removePendingData(_this);
  36402. var meshes = _this._meshes;
  36403. var numOfMeshes = meshes.length;
  36404. for (var index = 0; index < numOfMeshes; index++) {
  36405. _this._applyToMesh(meshes[index]);
  36406. }
  36407. if (onLoaded) {
  36408. onLoaded();
  36409. }
  36410. }, function () { }, scene.database);
  36411. };
  36412. /**
  36413. * Invert the geometry to move from a right handed system to a left handed one.
  36414. */
  36415. Geometry.prototype.toLeftHanded = function () {
  36416. // Flip faces
  36417. var tIndices = this.getIndices(false);
  36418. if (tIndices != null && tIndices.length > 0) {
  36419. for (var i = 0; i < tIndices.length; i += 3) {
  36420. var tTemp = tIndices[i + 0];
  36421. tIndices[i + 0] = tIndices[i + 2];
  36422. tIndices[i + 2] = tTemp;
  36423. }
  36424. this.setIndices(tIndices);
  36425. }
  36426. // Negate position.z
  36427. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36428. if (tPositions != null && tPositions.length > 0) {
  36429. for (var i = 0; i < tPositions.length; i += 3) {
  36430. tPositions[i + 2] = -tPositions[i + 2];
  36431. }
  36432. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36433. }
  36434. // Negate normal.z
  36435. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36436. if (tNormals != null && tNormals.length > 0) {
  36437. for (var i = 0; i < tNormals.length; i += 3) {
  36438. tNormals[i + 2] = -tNormals[i + 2];
  36439. }
  36440. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36441. }
  36442. };
  36443. Geometry.prototype.isDisposed = function () {
  36444. return this._isDisposed;
  36445. };
  36446. Geometry.prototype.dispose = function () {
  36447. var meshes = this._meshes;
  36448. var numOfMeshes = meshes.length;
  36449. var index;
  36450. for (index = 0; index < numOfMeshes; index++) {
  36451. this.releaseForMesh(meshes[index]);
  36452. }
  36453. this._meshes = [];
  36454. for (var kind in this._vertexBuffers) {
  36455. this._vertexBuffers[kind].dispose();
  36456. }
  36457. this._vertexBuffers = {};
  36458. this._totalVertices = 0;
  36459. if (this._indexBuffer) {
  36460. this._engine._releaseBuffer(this._indexBuffer);
  36461. }
  36462. this._indexBuffer = null;
  36463. this._indices = [];
  36464. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36465. this.delayLoadingFile = null;
  36466. this._delayLoadingFunction = null;
  36467. this._delayInfo = [];
  36468. this._boundingInfo = null;
  36469. this._scene.removeGeometry(this);
  36470. this._isDisposed = true;
  36471. };
  36472. Geometry.prototype.copy = function (id) {
  36473. var vertexData = new BABYLON.VertexData();
  36474. vertexData.indices = [];
  36475. var indices = this.getIndices();
  36476. for (var index = 0; index < indices.length; index++) {
  36477. vertexData.indices.push(indices[index]);
  36478. }
  36479. var updatable = false;
  36480. var stopChecking = false;
  36481. var kind;
  36482. for (kind in this._vertexBuffers) {
  36483. // using slice() to make a copy of the array and not just reference it
  36484. var data = this.getVerticesData(kind);
  36485. if (data instanceof Float32Array) {
  36486. vertexData.set(new Float32Array(data), kind);
  36487. }
  36488. else {
  36489. vertexData.set(data.slice(0), kind);
  36490. }
  36491. if (!stopChecking) {
  36492. updatable = this.getVertexBuffer(kind).isUpdatable();
  36493. stopChecking = !updatable;
  36494. }
  36495. }
  36496. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36497. geometry.delayLoadState = this.delayLoadState;
  36498. geometry.delayLoadingFile = this.delayLoadingFile;
  36499. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36500. for (kind in this._delayInfo) {
  36501. geometry._delayInfo = geometry._delayInfo || [];
  36502. geometry._delayInfo.push(kind);
  36503. }
  36504. // Bounding info
  36505. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36506. return geometry;
  36507. };
  36508. Geometry.prototype.serialize = function () {
  36509. var serializationObject = {};
  36510. serializationObject.id = this.id;
  36511. if (BABYLON.Tags.HasTags(this)) {
  36512. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36513. }
  36514. return serializationObject;
  36515. };
  36516. Geometry.prototype.serializeVerticeData = function () {
  36517. var serializationObject = this.serialize();
  36518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36519. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36520. }
  36521. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36522. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36523. }
  36524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36525. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36526. }
  36527. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36528. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36529. }
  36530. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36531. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36532. }
  36533. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36534. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36535. }
  36536. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36537. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36538. }
  36539. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36540. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36541. }
  36542. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36543. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36544. }
  36545. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36546. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36547. serializationObject.matricesIndices._isExpanded = true;
  36548. }
  36549. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36550. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36551. }
  36552. serializationObject.indices = this.getIndices();
  36553. return serializationObject;
  36554. };
  36555. // Statics
  36556. Geometry.ExtractFromMesh = function (mesh, id) {
  36557. var geometry = mesh._geometry;
  36558. if (!geometry) {
  36559. return null;
  36560. }
  36561. return geometry.copy(id);
  36562. };
  36563. /**
  36564. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36565. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36566. * Be aware Math.random() could cause collisions, but:
  36567. * "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"
  36568. */
  36569. Geometry.RandomId = function () {
  36570. return BABYLON.Tools.RandomId();
  36571. };
  36572. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36573. var scene = mesh.getScene();
  36574. // Geometry
  36575. var geometryId = parsedGeometry.geometryId;
  36576. if (geometryId) {
  36577. var geometry = scene.getGeometryByID(geometryId);
  36578. if (geometry) {
  36579. geometry.applyToMesh(mesh);
  36580. }
  36581. }
  36582. else if (parsedGeometry instanceof ArrayBuffer) {
  36583. var binaryInfo = mesh._binaryInfo;
  36584. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36585. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36586. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36587. }
  36588. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36589. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36590. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36591. }
  36592. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36593. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36594. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36595. }
  36596. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36597. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36598. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36599. }
  36600. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36601. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36602. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36603. }
  36604. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36605. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36606. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36607. }
  36608. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36609. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36610. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36611. }
  36612. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36613. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36614. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36615. }
  36616. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36617. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36618. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36619. }
  36620. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36621. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36623. }
  36624. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36625. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36627. }
  36628. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36629. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36630. mesh.setIndices(indicesData);
  36631. }
  36632. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36633. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36634. mesh.subMeshes = [];
  36635. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36636. var materialIndex = subMeshesData[(i * 5) + 0];
  36637. var verticesStart = subMeshesData[(i * 5) + 1];
  36638. var verticesCount = subMeshesData[(i * 5) + 2];
  36639. var indexStart = subMeshesData[(i * 5) + 3];
  36640. var indexCount = subMeshesData[(i * 5) + 4];
  36641. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36642. }
  36643. }
  36644. }
  36645. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36646. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36647. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36648. if (parsedGeometry.uvs) {
  36649. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36650. }
  36651. if (parsedGeometry.uvs2) {
  36652. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36653. }
  36654. if (parsedGeometry.uvs3) {
  36655. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36656. }
  36657. if (parsedGeometry.uvs4) {
  36658. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36659. }
  36660. if (parsedGeometry.uvs5) {
  36661. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36662. }
  36663. if (parsedGeometry.uvs6) {
  36664. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36665. }
  36666. if (parsedGeometry.colors) {
  36667. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36668. }
  36669. if (parsedGeometry.matricesIndices) {
  36670. if (!parsedGeometry.matricesIndices._isExpanded) {
  36671. var floatIndices = [];
  36672. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36673. var matricesIndex = parsedGeometry.matricesIndices[i];
  36674. floatIndices.push(matricesIndex & 0x000000FF);
  36675. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36676. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36677. floatIndices.push(matricesIndex >> 24);
  36678. }
  36679. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36680. }
  36681. else {
  36682. delete parsedGeometry.matricesIndices._isExpanded;
  36683. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36684. }
  36685. }
  36686. if (parsedGeometry.matricesIndicesExtra) {
  36687. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36688. var floatIndices = [];
  36689. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36690. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36691. floatIndices.push(matricesIndex & 0x000000FF);
  36692. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36693. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36694. floatIndices.push(matricesIndex >> 24);
  36695. }
  36696. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36697. }
  36698. else {
  36699. delete parsedGeometry.matricesIndices._isExpanded;
  36700. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36701. }
  36702. }
  36703. if (parsedGeometry.matricesWeights) {
  36704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36705. }
  36706. if (parsedGeometry.matricesWeightsExtra) {
  36707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36708. }
  36709. mesh.setIndices(parsedGeometry.indices);
  36710. }
  36711. // SubMeshes
  36712. if (parsedGeometry.subMeshes) {
  36713. mesh.subMeshes = [];
  36714. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36715. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36716. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36717. }
  36718. }
  36719. // Flat shading
  36720. if (mesh._shouldGenerateFlatShading) {
  36721. mesh.convertToFlatShadedMesh();
  36722. delete mesh._shouldGenerateFlatShading;
  36723. }
  36724. // Update
  36725. mesh.computeWorldMatrix(true);
  36726. // Octree
  36727. if (scene['_selectionOctree']) {
  36728. scene['_selectionOctree'].addMesh(mesh);
  36729. }
  36730. };
  36731. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36732. if (scene.getGeometryByID(parsedVertexData.id)) {
  36733. return null; // null since geometry could be something else than a box...
  36734. }
  36735. var geometry = new Geometry(parsedVertexData.id, scene);
  36736. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36737. if (parsedVertexData.delayLoadingFile) {
  36738. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36739. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36740. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36741. geometry._delayInfo = [];
  36742. if (parsedVertexData.hasUVs) {
  36743. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36744. }
  36745. if (parsedVertexData.hasUVs2) {
  36746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36747. }
  36748. if (parsedVertexData.hasUVs3) {
  36749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36750. }
  36751. if (parsedVertexData.hasUVs4) {
  36752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36753. }
  36754. if (parsedVertexData.hasUVs5) {
  36755. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36756. }
  36757. if (parsedVertexData.hasUVs6) {
  36758. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36759. }
  36760. if (parsedVertexData.hasColors) {
  36761. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36762. }
  36763. if (parsedVertexData.hasMatricesIndices) {
  36764. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36765. }
  36766. if (parsedVertexData.hasMatricesWeights) {
  36767. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36768. }
  36769. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36770. }
  36771. else {
  36772. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36773. }
  36774. scene.pushGeometry(geometry, true);
  36775. return geometry;
  36776. };
  36777. return Geometry;
  36778. }());
  36779. BABYLON.Geometry = Geometry;
  36780. /////// Primitives //////////////////////////////////////////////
  36781. var Geometry;
  36782. (function (Geometry) {
  36783. var Primitives;
  36784. (function (Primitives) {
  36785. /// Abstract class
  36786. var _Primitive = (function (_super) {
  36787. __extends(_Primitive, _super);
  36788. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36789. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  36790. this._canBeRegenerated = _canBeRegenerated;
  36791. this._beingRegenerated = true;
  36792. this.regenerate();
  36793. this._beingRegenerated = false;
  36794. }
  36795. _Primitive.prototype.canBeRegenerated = function () {
  36796. return this._canBeRegenerated;
  36797. };
  36798. _Primitive.prototype.regenerate = function () {
  36799. if (!this._canBeRegenerated) {
  36800. return;
  36801. }
  36802. this._beingRegenerated = true;
  36803. this.setAllVerticesData(this._regenerateVertexData(), false);
  36804. this._beingRegenerated = false;
  36805. };
  36806. _Primitive.prototype.asNewGeometry = function (id) {
  36807. return _super.prototype.copy.call(this, id);
  36808. };
  36809. // overrides
  36810. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36811. if (!this._beingRegenerated) {
  36812. return;
  36813. }
  36814. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36815. };
  36816. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36817. if (!this._beingRegenerated) {
  36818. return;
  36819. }
  36820. _super.prototype.setVerticesData.call(this, kind, data, false);
  36821. };
  36822. // to override
  36823. // protected
  36824. _Primitive.prototype._regenerateVertexData = function () {
  36825. throw new Error("Abstract method");
  36826. };
  36827. _Primitive.prototype.copy = function (id) {
  36828. throw new Error("Must be overriden in sub-classes.");
  36829. };
  36830. _Primitive.prototype.serialize = function () {
  36831. var serializationObject = _super.prototype.serialize.call(this);
  36832. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36833. return serializationObject;
  36834. };
  36835. return _Primitive;
  36836. }(Geometry));
  36837. Primitives._Primitive = _Primitive;
  36838. var Ribbon = (function (_super) {
  36839. __extends(Ribbon, _super);
  36840. // Members
  36841. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36842. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36843. _super.call(this, id, scene, canBeRegenerated, mesh);
  36844. this.pathArray = pathArray;
  36845. this.closeArray = closeArray;
  36846. this.closePath = closePath;
  36847. this.offset = offset;
  36848. this.side = side;
  36849. }
  36850. Ribbon.prototype._regenerateVertexData = function () {
  36851. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36852. };
  36853. Ribbon.prototype.copy = function (id) {
  36854. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36855. };
  36856. return Ribbon;
  36857. }(_Primitive));
  36858. Primitives.Ribbon = Ribbon;
  36859. var Box = (function (_super) {
  36860. __extends(Box, _super);
  36861. // Members
  36862. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36863. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36864. _super.call(this, id, scene, canBeRegenerated, mesh);
  36865. this.size = size;
  36866. this.side = side;
  36867. }
  36868. Box.prototype._regenerateVertexData = function () {
  36869. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36870. };
  36871. Box.prototype.copy = function (id) {
  36872. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36873. };
  36874. Box.prototype.serialize = function () {
  36875. var serializationObject = _super.prototype.serialize.call(this);
  36876. serializationObject.size = this.size;
  36877. return serializationObject;
  36878. };
  36879. Box.Parse = function (parsedBox, scene) {
  36880. if (scene.getGeometryByID(parsedBox.id)) {
  36881. return null; // null since geometry could be something else than a box...
  36882. }
  36883. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36884. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36885. scene.pushGeometry(box, true);
  36886. return box;
  36887. };
  36888. return Box;
  36889. }(_Primitive));
  36890. Primitives.Box = Box;
  36891. var Sphere = (function (_super) {
  36892. __extends(Sphere, _super);
  36893. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36894. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36895. _super.call(this, id, scene, canBeRegenerated, mesh);
  36896. this.segments = segments;
  36897. this.diameter = diameter;
  36898. this.side = side;
  36899. }
  36900. Sphere.prototype._regenerateVertexData = function () {
  36901. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36902. };
  36903. Sphere.prototype.copy = function (id) {
  36904. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36905. };
  36906. Sphere.prototype.serialize = function () {
  36907. var serializationObject = _super.prototype.serialize.call(this);
  36908. serializationObject.segments = this.segments;
  36909. serializationObject.diameter = this.diameter;
  36910. return serializationObject;
  36911. };
  36912. Sphere.Parse = function (parsedSphere, scene) {
  36913. if (scene.getGeometryByID(parsedSphere.id)) {
  36914. return null; // null since geometry could be something else than a sphere...
  36915. }
  36916. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36917. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36918. scene.pushGeometry(sphere, true);
  36919. return sphere;
  36920. };
  36921. return Sphere;
  36922. }(_Primitive));
  36923. Primitives.Sphere = Sphere;
  36924. var Disc = (function (_super) {
  36925. __extends(Disc, _super);
  36926. // Members
  36927. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36929. _super.call(this, id, scene, canBeRegenerated, mesh);
  36930. this.radius = radius;
  36931. this.tessellation = tessellation;
  36932. this.side = side;
  36933. }
  36934. Disc.prototype._regenerateVertexData = function () {
  36935. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36936. };
  36937. Disc.prototype.copy = function (id) {
  36938. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36939. };
  36940. return Disc;
  36941. }(_Primitive));
  36942. Primitives.Disc = Disc;
  36943. var Cylinder = (function (_super) {
  36944. __extends(Cylinder, _super);
  36945. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36946. if (subdivisions === void 0) { subdivisions = 1; }
  36947. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36948. _super.call(this, id, scene, canBeRegenerated, mesh);
  36949. this.height = height;
  36950. this.diameterTop = diameterTop;
  36951. this.diameterBottom = diameterBottom;
  36952. this.tessellation = tessellation;
  36953. this.subdivisions = subdivisions;
  36954. this.side = side;
  36955. }
  36956. Cylinder.prototype._regenerateVertexData = function () {
  36957. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36958. };
  36959. Cylinder.prototype.copy = function (id) {
  36960. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36961. };
  36962. Cylinder.prototype.serialize = function () {
  36963. var serializationObject = _super.prototype.serialize.call(this);
  36964. serializationObject.height = this.height;
  36965. serializationObject.diameterTop = this.diameterTop;
  36966. serializationObject.diameterBottom = this.diameterBottom;
  36967. serializationObject.tessellation = this.tessellation;
  36968. return serializationObject;
  36969. };
  36970. Cylinder.Parse = function (parsedCylinder, scene) {
  36971. if (scene.getGeometryByID(parsedCylinder.id)) {
  36972. return null; // null since geometry could be something else than a cylinder...
  36973. }
  36974. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36975. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36976. scene.pushGeometry(cylinder, true);
  36977. return cylinder;
  36978. };
  36979. return Cylinder;
  36980. }(_Primitive));
  36981. Primitives.Cylinder = Cylinder;
  36982. var Torus = (function (_super) {
  36983. __extends(Torus, _super);
  36984. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  36985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36986. _super.call(this, id, scene, canBeRegenerated, mesh);
  36987. this.diameter = diameter;
  36988. this.thickness = thickness;
  36989. this.tessellation = tessellation;
  36990. this.side = side;
  36991. }
  36992. Torus.prototype._regenerateVertexData = function () {
  36993. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36994. };
  36995. Torus.prototype.copy = function (id) {
  36996. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36997. };
  36998. Torus.prototype.serialize = function () {
  36999. var serializationObject = _super.prototype.serialize.call(this);
  37000. serializationObject.diameter = this.diameter;
  37001. serializationObject.thickness = this.thickness;
  37002. serializationObject.tessellation = this.tessellation;
  37003. return serializationObject;
  37004. };
  37005. Torus.Parse = function (parsedTorus, scene) {
  37006. if (scene.getGeometryByID(parsedTorus.id)) {
  37007. return null; // null since geometry could be something else than a torus...
  37008. }
  37009. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37010. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37011. scene.pushGeometry(torus, true);
  37012. return torus;
  37013. };
  37014. return Torus;
  37015. }(_Primitive));
  37016. Primitives.Torus = Torus;
  37017. var Ground = (function (_super) {
  37018. __extends(Ground, _super);
  37019. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37020. _super.call(this, id, scene, canBeRegenerated, mesh);
  37021. this.width = width;
  37022. this.height = height;
  37023. this.subdivisions = subdivisions;
  37024. }
  37025. Ground.prototype._regenerateVertexData = function () {
  37026. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37027. };
  37028. Ground.prototype.copy = function (id) {
  37029. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37030. };
  37031. Ground.prototype.serialize = function () {
  37032. var serializationObject = _super.prototype.serialize.call(this);
  37033. serializationObject.width = this.width;
  37034. serializationObject.height = this.height;
  37035. serializationObject.subdivisions = this.subdivisions;
  37036. return serializationObject;
  37037. };
  37038. Ground.Parse = function (parsedGround, scene) {
  37039. if (scene.getGeometryByID(parsedGround.id)) {
  37040. return null; // null since geometry could be something else than a ground...
  37041. }
  37042. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37043. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37044. scene.pushGeometry(ground, true);
  37045. return ground;
  37046. };
  37047. return Ground;
  37048. }(_Primitive));
  37049. Primitives.Ground = Ground;
  37050. var TiledGround = (function (_super) {
  37051. __extends(TiledGround, _super);
  37052. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37053. _super.call(this, id, scene, canBeRegenerated, mesh);
  37054. this.xmin = xmin;
  37055. this.zmin = zmin;
  37056. this.xmax = xmax;
  37057. this.zmax = zmax;
  37058. this.subdivisions = subdivisions;
  37059. this.precision = precision;
  37060. }
  37061. TiledGround.prototype._regenerateVertexData = function () {
  37062. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37063. };
  37064. TiledGround.prototype.copy = function (id) {
  37065. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37066. };
  37067. return TiledGround;
  37068. }(_Primitive));
  37069. Primitives.TiledGround = TiledGround;
  37070. var Plane = (function (_super) {
  37071. __extends(Plane, _super);
  37072. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37074. _super.call(this, id, scene, canBeRegenerated, mesh);
  37075. this.size = size;
  37076. this.side = side;
  37077. }
  37078. Plane.prototype._regenerateVertexData = function () {
  37079. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37080. };
  37081. Plane.prototype.copy = function (id) {
  37082. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37083. };
  37084. Plane.prototype.serialize = function () {
  37085. var serializationObject = _super.prototype.serialize.call(this);
  37086. serializationObject.size = this.size;
  37087. return serializationObject;
  37088. };
  37089. Plane.Parse = function (parsedPlane, scene) {
  37090. if (scene.getGeometryByID(parsedPlane.id)) {
  37091. return null; // null since geometry could be something else than a ground...
  37092. }
  37093. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37094. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37095. scene.pushGeometry(plane, true);
  37096. return plane;
  37097. };
  37098. return Plane;
  37099. }(_Primitive));
  37100. Primitives.Plane = Plane;
  37101. var TorusKnot = (function (_super) {
  37102. __extends(TorusKnot, _super);
  37103. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37104. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37105. _super.call(this, id, scene, canBeRegenerated, mesh);
  37106. this.radius = radius;
  37107. this.tube = tube;
  37108. this.radialSegments = radialSegments;
  37109. this.tubularSegments = tubularSegments;
  37110. this.p = p;
  37111. this.q = q;
  37112. this.side = side;
  37113. }
  37114. TorusKnot.prototype._regenerateVertexData = function () {
  37115. 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 });
  37116. };
  37117. TorusKnot.prototype.copy = function (id) {
  37118. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37119. };
  37120. TorusKnot.prototype.serialize = function () {
  37121. var serializationObject = _super.prototype.serialize.call(this);
  37122. serializationObject.radius = this.radius;
  37123. serializationObject.tube = this.tube;
  37124. serializationObject.radialSegments = this.radialSegments;
  37125. serializationObject.tubularSegments = this.tubularSegments;
  37126. serializationObject.p = this.p;
  37127. serializationObject.q = this.q;
  37128. return serializationObject;
  37129. };
  37130. ;
  37131. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37132. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37133. return null; // null since geometry could be something else than a ground...
  37134. }
  37135. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37136. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37137. scene.pushGeometry(torusKnot, true);
  37138. return torusKnot;
  37139. };
  37140. return TorusKnot;
  37141. }(_Primitive));
  37142. Primitives.TorusKnot = TorusKnot;
  37143. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37144. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37145. })(BABYLON || (BABYLON = {}));
  37146. //# sourceMappingURL=babylon.geometry.js.map
  37147. var BABYLON;
  37148. (function (BABYLON) {
  37149. var GroundMesh = (function (_super) {
  37150. __extends(GroundMesh, _super);
  37151. function GroundMesh(name, scene) {
  37152. _super.call(this, name, scene);
  37153. this.generateOctree = false;
  37154. this._worldInverse = new BABYLON.Matrix();
  37155. }
  37156. GroundMesh.prototype.getClassName = function () {
  37157. return "GroundMesh";
  37158. };
  37159. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37160. get: function () {
  37161. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37162. },
  37163. enumerable: true,
  37164. configurable: true
  37165. });
  37166. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37167. get: function () {
  37168. return this._subdivisionsX;
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37174. get: function () {
  37175. return this._subdivisionsY;
  37176. },
  37177. enumerable: true,
  37178. configurable: true
  37179. });
  37180. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37181. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37182. this._subdivisionsX = chunksCount;
  37183. this._subdivisionsY = chunksCount;
  37184. this.subdivide(chunksCount);
  37185. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37186. };
  37187. /**
  37188. * Returns a height (y) value in the Worl system :
  37189. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37190. * Returns the ground y position if (x, z) are outside the ground surface.
  37191. * Not pertinent if the ground is rotated.
  37192. */
  37193. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37194. // express x and y in the ground local system
  37195. x -= this.position.x;
  37196. z -= this.position.z;
  37197. x /= this.scaling.x;
  37198. z /= this.scaling.z;
  37199. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37200. return this.position.y;
  37201. }
  37202. if (!this._heightQuads || this._heightQuads.length == 0) {
  37203. this._initHeightQuads();
  37204. this._computeHeightQuads();
  37205. }
  37206. var facet = this._getFacetAt(x, z);
  37207. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37208. // return y in the World system
  37209. return y * this.scaling.y + this.position.y;
  37210. };
  37211. /**
  37212. * Returns a normalized vector (Vector3) orthogonal to the ground
  37213. * at the ground coordinates (x, z) expressed in the World system.
  37214. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37215. * Not pertinent if the ground is rotated.
  37216. */
  37217. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37218. var normal = new BABYLON.Vector3(0, 1, 0);
  37219. this.getNormalAtCoordinatesToRef(x, z, normal);
  37220. return normal;
  37221. };
  37222. /**
  37223. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37224. * at the ground coordinates (x, z) expressed in the World system.
  37225. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37226. * Not pertinent if the ground is rotated.
  37227. */
  37228. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37229. // express x and y in the ground local system
  37230. x -= this.position.x;
  37231. z -= this.position.z;
  37232. x /= this.scaling.x;
  37233. z /= this.scaling.z;
  37234. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37235. return;
  37236. }
  37237. if (!this._heightQuads || this._heightQuads.length == 0) {
  37238. this._initHeightQuads();
  37239. this._computeHeightQuads();
  37240. }
  37241. var facet = this._getFacetAt(x, z);
  37242. ref.x = facet.x;
  37243. ref.y = facet.y;
  37244. ref.z = facet.z;
  37245. };
  37246. /**
  37247. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37248. * if the ground has been updated.
  37249. * This can be used in the render loop
  37250. */
  37251. GroundMesh.prototype.updateCoordinateHeights = function () {
  37252. if (!this._heightQuads || this._heightQuads.length == 0) {
  37253. this._initHeightQuads();
  37254. }
  37255. this._computeHeightQuads();
  37256. };
  37257. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37258. GroundMesh.prototype._getFacetAt = function (x, z) {
  37259. // retrieve col and row from x, z coordinates in the ground local system
  37260. var subdivisionsX = this._subdivisionsX;
  37261. var subdivisionsY = this._subdivisionsY;
  37262. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37263. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37264. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37265. var facet;
  37266. if (z < quad.slope.x * x + quad.slope.y) {
  37267. facet = quad.facet1;
  37268. }
  37269. else {
  37270. facet = quad.facet2;
  37271. }
  37272. return facet;
  37273. };
  37274. // Creates and populates the heightMap array with "facet" elements :
  37275. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37276. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37277. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37278. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37279. GroundMesh.prototype._initHeightQuads = function () {
  37280. var subdivisionsX = this._subdivisionsX;
  37281. var subdivisionsY = this._subdivisionsY;
  37282. this._heightQuads = new Array();
  37283. for (var row = 0; row < subdivisionsY; row++) {
  37284. for (var col = 0; col < subdivisionsX; col++) {
  37285. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37286. this._heightQuads[row * subdivisionsX + col] = quad;
  37287. }
  37288. }
  37289. };
  37290. // Compute each quad element values and update the the heightMap array :
  37291. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37292. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37293. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37294. GroundMesh.prototype._computeHeightQuads = function () {
  37295. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37296. var v1 = BABYLON.Tmp.Vector3[3];
  37297. var v2 = BABYLON.Tmp.Vector3[2];
  37298. var v3 = BABYLON.Tmp.Vector3[1];
  37299. var v4 = BABYLON.Tmp.Vector3[0];
  37300. var v1v2 = BABYLON.Tmp.Vector3[4];
  37301. var v1v3 = BABYLON.Tmp.Vector3[5];
  37302. var v1v4 = BABYLON.Tmp.Vector3[6];
  37303. var norm1 = BABYLON.Tmp.Vector3[7];
  37304. var norm2 = BABYLON.Tmp.Vector3[8];
  37305. var i = 0;
  37306. var j = 0;
  37307. var k = 0;
  37308. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37309. var h = 0;
  37310. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37311. var d2 = 0;
  37312. var subdivisionsX = this._subdivisionsX;
  37313. var subdivisionsY = this._subdivisionsY;
  37314. for (var row = 0; row < subdivisionsY; row++) {
  37315. for (var col = 0; col < subdivisionsX; col++) {
  37316. i = col * 3;
  37317. j = row * (subdivisionsX + 1) * 3;
  37318. k = (row + 1) * (subdivisionsX + 1) * 3;
  37319. v1.x = positions[j + i];
  37320. v1.y = positions[j + i + 1];
  37321. v1.z = positions[j + i + 2];
  37322. v2.x = positions[j + i + 3];
  37323. v2.y = positions[j + i + 4];
  37324. v2.z = positions[j + i + 5];
  37325. v3.x = positions[k + i];
  37326. v3.y = positions[k + i + 1];
  37327. v3.z = positions[k + i + 2];
  37328. v4.x = positions[k + i + 3];
  37329. v4.y = positions[k + i + 4];
  37330. v4.z = positions[k + i + 5];
  37331. // 2D slope V1V4
  37332. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37333. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37334. // facet equations :
  37335. // we compute each facet normal vector
  37336. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37337. // we compute the value d by applying the equation to v1 which belongs to the plane
  37338. // then we store the facet equation in a Vector4
  37339. v2.subtractToRef(v1, v1v2);
  37340. v3.subtractToRef(v1, v1v3);
  37341. v4.subtractToRef(v1, v1v4);
  37342. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37343. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37344. norm1.normalize();
  37345. norm2.normalize();
  37346. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37347. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37348. var quad = this._heightQuads[row * subdivisionsX + col];
  37349. quad.slope.copyFromFloats(cd, h);
  37350. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37351. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37352. }
  37353. }
  37354. };
  37355. return GroundMesh;
  37356. }(BABYLON.Mesh));
  37357. BABYLON.GroundMesh = GroundMesh;
  37358. })(BABYLON || (BABYLON = {}));
  37359. //# sourceMappingURL=babylon.groundMesh.js.map
  37360. var BABYLON;
  37361. (function (BABYLON) {
  37362. var LinesMesh = (function (_super) {
  37363. __extends(LinesMesh, _super);
  37364. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37365. if (parent === void 0) { parent = null; }
  37366. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  37367. this.color = new BABYLON.Color3(1, 1, 1);
  37368. this.alpha = 1;
  37369. this._positionBuffer = {};
  37370. if (source) {
  37371. this.color = source.color.clone();
  37372. this.alpha = source.alpha;
  37373. }
  37374. this._intersectionThreshold = 0.1;
  37375. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37376. attributes: [BABYLON.VertexBuffer.PositionKind],
  37377. uniforms: ["worldViewProjection", "color"],
  37378. needAlphaBlending: true
  37379. });
  37380. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37381. }
  37382. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37383. /**
  37384. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37385. * This margin is expressed in world space coordinates, so its value may vary.
  37386. * Default value is 0.1
  37387. * @returns the intersection Threshold value.
  37388. */
  37389. get: function () {
  37390. return this._intersectionThreshold;
  37391. },
  37392. /**
  37393. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37394. * This margin is expressed in world space coordinates, so its value may vary.
  37395. * @param value the new threshold to apply
  37396. */
  37397. set: function (value) {
  37398. if (this._intersectionThreshold === value) {
  37399. return;
  37400. }
  37401. this._intersectionThreshold = value;
  37402. if (this.geometry) {
  37403. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37404. }
  37405. },
  37406. enumerable: true,
  37407. configurable: true
  37408. });
  37409. LinesMesh.prototype.getClassName = function () {
  37410. return "LinesMesh";
  37411. };
  37412. Object.defineProperty(LinesMesh.prototype, "material", {
  37413. get: function () {
  37414. return this._colorShader;
  37415. },
  37416. enumerable: true,
  37417. configurable: true
  37418. });
  37419. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37420. get: function () {
  37421. return false;
  37422. },
  37423. enumerable: true,
  37424. configurable: true
  37425. });
  37426. LinesMesh.prototype.createInstance = function (name) {
  37427. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37428. return null;
  37429. };
  37430. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37431. var engine = this.getScene().getEngine();
  37432. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37433. // VBOs
  37434. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37435. // Color
  37436. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37437. };
  37438. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37439. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37440. return;
  37441. }
  37442. var engine = this.getScene().getEngine();
  37443. // Draw order
  37444. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37445. };
  37446. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37447. this._colorShader.dispose();
  37448. _super.prototype.dispose.call(this, doNotRecurse);
  37449. };
  37450. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37451. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37452. };
  37453. return LinesMesh;
  37454. }(BABYLON.Mesh));
  37455. BABYLON.LinesMesh = LinesMesh;
  37456. })(BABYLON || (BABYLON = {}));
  37457. //# sourceMappingURL=babylon.linesMesh.js.map
  37458. var BABYLON;
  37459. (function (BABYLON) {
  37460. var DefaultLoadingScreen = (function () {
  37461. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37462. var _this = this;
  37463. if (_loadingText === void 0) { _loadingText = ""; }
  37464. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37465. this._renderingCanvas = _renderingCanvas;
  37466. this._loadingText = _loadingText;
  37467. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37468. // Resize
  37469. this._resizeLoadingUI = function () {
  37470. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37471. _this._loadingDiv.style.position = "absolute";
  37472. _this._loadingDiv.style.left = canvasRect.left + "px";
  37473. _this._loadingDiv.style.top = canvasRect.top + "px";
  37474. _this._loadingDiv.style.width = canvasRect.width + "px";
  37475. _this._loadingDiv.style.height = canvasRect.height + "px";
  37476. };
  37477. }
  37478. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37479. var _this = this;
  37480. if (this._loadingDiv) {
  37481. // Do not add a loading screen if there is already one
  37482. return;
  37483. }
  37484. this._loadingDiv = document.createElement("div");
  37485. this._loadingDiv.id = "babylonjsLoadingDiv";
  37486. this._loadingDiv.style.opacity = "0";
  37487. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37488. // Loading text
  37489. this._loadingTextDiv = document.createElement("div");
  37490. this._loadingTextDiv.style.position = "absolute";
  37491. this._loadingTextDiv.style.left = "0";
  37492. this._loadingTextDiv.style.top = "50%";
  37493. this._loadingTextDiv.style.marginTop = "80px";
  37494. this._loadingTextDiv.style.width = "100%";
  37495. this._loadingTextDiv.style.height = "20px";
  37496. this._loadingTextDiv.style.fontFamily = "Arial";
  37497. this._loadingTextDiv.style.fontSize = "14px";
  37498. this._loadingTextDiv.style.color = "white";
  37499. this._loadingTextDiv.style.textAlign = "center";
  37500. this._loadingTextDiv.innerHTML = "Loading";
  37501. this._loadingDiv.appendChild(this._loadingTextDiv);
  37502. //set the predefined text
  37503. this._loadingTextDiv.innerHTML = this._loadingText;
  37504. // Loading img
  37505. var imgBack = new Image();
  37506. 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==";
  37507. imgBack.style.position = "absolute";
  37508. imgBack.style.left = "50%";
  37509. imgBack.style.top = "50%";
  37510. imgBack.style.marginLeft = "-50px";
  37511. imgBack.style.marginTop = "-50px";
  37512. imgBack.style.transition = "transform 1.0s ease";
  37513. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37514. var deg = 360;
  37515. var onTransitionEnd = function () {
  37516. deg += 360;
  37517. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37518. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37519. };
  37520. imgBack.addEventListener("transitionend", onTransitionEnd);
  37521. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37522. this._loadingDiv.appendChild(imgBack);
  37523. // front image
  37524. var imgFront = new Image();
  37525. 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=";
  37526. imgFront.style.position = "absolute";
  37527. imgFront.style.left = "50%";
  37528. imgFront.style.top = "50%";
  37529. imgFront.style.marginLeft = "-50px";
  37530. imgFront.style.marginTop = "-50px";
  37531. this._loadingDiv.appendChild(imgFront);
  37532. this._resizeLoadingUI();
  37533. window.addEventListener("resize", this._resizeLoadingUI);
  37534. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37535. document.body.appendChild(this._loadingDiv);
  37536. setTimeout(function () {
  37537. _this._loadingDiv.style.opacity = "1";
  37538. imgBack.style.transform = "rotateZ(360deg)";
  37539. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37540. }, 0);
  37541. };
  37542. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37543. var _this = this;
  37544. if (!this._loadingDiv) {
  37545. return;
  37546. }
  37547. var onTransitionEnd = function () {
  37548. if (!_this._loadingDiv) {
  37549. return;
  37550. }
  37551. document.body.removeChild(_this._loadingDiv);
  37552. window.removeEventListener("resize", _this._resizeLoadingUI);
  37553. _this._loadingDiv = null;
  37554. };
  37555. this._loadingDiv.style.opacity = "0";
  37556. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37557. };
  37558. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37559. set: function (text) {
  37560. this._loadingText = text;
  37561. if (this._loadingTextDiv) {
  37562. this._loadingTextDiv.innerHTML = this._loadingText;
  37563. }
  37564. },
  37565. enumerable: true,
  37566. configurable: true
  37567. });
  37568. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37569. get: function () {
  37570. return this._loadingDivBackgroundColor;
  37571. },
  37572. set: function (color) {
  37573. this._loadingDivBackgroundColor = color;
  37574. if (!this._loadingDiv) {
  37575. return;
  37576. }
  37577. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37578. },
  37579. enumerable: true,
  37580. configurable: true
  37581. });
  37582. return DefaultLoadingScreen;
  37583. }());
  37584. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37585. })(BABYLON || (BABYLON = {}));
  37586. //# sourceMappingURL=babylon.loadingScreen.js.map
  37587. var BABYLON;
  37588. (function (BABYLON) {
  37589. var AudioEngine = (function () {
  37590. function AudioEngine() {
  37591. this._audioContext = null;
  37592. this._audioContextInitialized = false;
  37593. this.canUseWebAudio = false;
  37594. this.WarnedWebAudioUnsupported = false;
  37595. this.unlocked = false;
  37596. this.isMP3supported = false;
  37597. this.isOGGsupported = false;
  37598. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37599. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37600. this.canUseWebAudio = true;
  37601. }
  37602. var audioElem = document.createElement('audio');
  37603. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37604. this.isMP3supported = true;
  37605. }
  37606. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37607. this.isOGGsupported = true;
  37608. }
  37609. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37610. this._unlockiOSaudio();
  37611. }
  37612. else {
  37613. this.unlocked = true;
  37614. }
  37615. }
  37616. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37617. get: function () {
  37618. if (!this._audioContextInitialized) {
  37619. this._initializeAudioContext();
  37620. }
  37621. return this._audioContext;
  37622. },
  37623. enumerable: true,
  37624. configurable: true
  37625. });
  37626. AudioEngine.prototype._unlockiOSaudio = function () {
  37627. var _this = this;
  37628. var unlockaudio = function () {
  37629. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37630. var source = _this.audioContext.createBufferSource();
  37631. source.buffer = buffer;
  37632. source.connect(_this.audioContext.destination);
  37633. source.start(0);
  37634. setTimeout(function () {
  37635. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37636. _this.unlocked = true;
  37637. window.removeEventListener('touchend', unlockaudio, false);
  37638. if (_this.onAudioUnlocked) {
  37639. _this.onAudioUnlocked();
  37640. }
  37641. }
  37642. }, 0);
  37643. };
  37644. window.addEventListener('touchend', unlockaudio, false);
  37645. };
  37646. AudioEngine.prototype._initializeAudioContext = function () {
  37647. try {
  37648. if (this.canUseWebAudio) {
  37649. this._audioContext = new AudioContext();
  37650. // create a global volume gain node
  37651. this.masterGain = this._audioContext.createGain();
  37652. this.masterGain.gain.value = 1;
  37653. this.masterGain.connect(this._audioContext.destination);
  37654. this._audioContextInitialized = true;
  37655. }
  37656. }
  37657. catch (e) {
  37658. this.canUseWebAudio = false;
  37659. BABYLON.Tools.Error("Web Audio: " + e.message);
  37660. }
  37661. };
  37662. AudioEngine.prototype.dispose = function () {
  37663. if (this.canUseWebAudio && this._audioContextInitialized) {
  37664. if (this._connectedAnalyser) {
  37665. this._connectedAnalyser.stopDebugCanvas();
  37666. this._connectedAnalyser.dispose();
  37667. this.masterGain.disconnect();
  37668. this.masterGain.connect(this._audioContext.destination);
  37669. this._connectedAnalyser = null;
  37670. }
  37671. this.masterGain.gain.value = 1;
  37672. }
  37673. this.WarnedWebAudioUnsupported = false;
  37674. };
  37675. AudioEngine.prototype.getGlobalVolume = function () {
  37676. if (this.canUseWebAudio && this._audioContextInitialized) {
  37677. return this.masterGain.gain.value;
  37678. }
  37679. else {
  37680. return -1;
  37681. }
  37682. };
  37683. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37684. if (this.canUseWebAudio && this._audioContextInitialized) {
  37685. this.masterGain.gain.value = newVolume;
  37686. }
  37687. };
  37688. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37689. if (this._connectedAnalyser) {
  37690. this._connectedAnalyser.stopDebugCanvas();
  37691. }
  37692. if (this.canUseWebAudio && this._audioContextInitialized) {
  37693. this._connectedAnalyser = analyser;
  37694. this.masterGain.disconnect();
  37695. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37696. }
  37697. };
  37698. return AudioEngine;
  37699. }());
  37700. BABYLON.AudioEngine = AudioEngine;
  37701. })(BABYLON || (BABYLON = {}));
  37702. //# sourceMappingURL=babylon.audioEngine.js.map
  37703. var BABYLON;
  37704. (function (BABYLON) {
  37705. var Sound = (function () {
  37706. /**
  37707. * Create a sound and attach it to a scene
  37708. * @param name Name of your sound
  37709. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37710. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37711. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37712. */
  37713. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37714. var _this = this;
  37715. this.autoplay = false;
  37716. this.loop = false;
  37717. this.useCustomAttenuation = false;
  37718. this.spatialSound = false;
  37719. this.refDistance = 1;
  37720. this.rolloffFactor = 1;
  37721. this.maxDistance = 100;
  37722. this.distanceModel = "linear";
  37723. this._panningModel = "equalpower";
  37724. this._playbackRate = 1;
  37725. this._streaming = false;
  37726. this._startTime = 0;
  37727. this._startOffset = 0;
  37728. this._position = BABYLON.Vector3.Zero();
  37729. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37730. this._volume = 1;
  37731. this._isLoaded = false;
  37732. this._isReadyToPlay = false;
  37733. this.isPlaying = false;
  37734. this.isPaused = false;
  37735. this._isDirectional = false;
  37736. // Used if you'd like to create a directional sound.
  37737. // If not set, the sound will be omnidirectional
  37738. this._coneInnerAngle = 360;
  37739. this._coneOuterAngle = 360;
  37740. this._coneOuterGain = 0;
  37741. this._isOutputConnected = false;
  37742. this._urlType = "Unknown";
  37743. this.name = name;
  37744. this._scene = scene;
  37745. this._readyToPlayCallback = readyToPlayCallback;
  37746. // Default custom attenuation function is a linear attenuation
  37747. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37748. if (currentDistance < maxDistance) {
  37749. return currentVolume * (1 - currentDistance / maxDistance);
  37750. }
  37751. else {
  37752. return 0;
  37753. }
  37754. };
  37755. if (options) {
  37756. this.autoplay = options.autoplay || false;
  37757. this.loop = options.loop || false;
  37758. // if volume === 0, we need another way to check this option
  37759. if (options.volume !== undefined) {
  37760. this._volume = options.volume;
  37761. }
  37762. this.spatialSound = options.spatialSound || false;
  37763. this.maxDistance = options.maxDistance || 100;
  37764. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37765. this.rolloffFactor = options.rolloffFactor || 1;
  37766. this.refDistance = options.refDistance || 1;
  37767. this.distanceModel = options.distanceModel || "linear";
  37768. this._playbackRate = options.playbackRate || 1;
  37769. this._streaming = options.streaming || false;
  37770. }
  37771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37772. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37773. this._soundGain.gain.value = this._volume;
  37774. this._inputAudioNode = this._soundGain;
  37775. this._ouputAudioNode = this._soundGain;
  37776. if (this.spatialSound) {
  37777. this._createSpatialParameters();
  37778. }
  37779. this._scene.mainSoundTrack.AddSound(this);
  37780. var validParameter = true;
  37781. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37782. if (urlOrArrayBuffer) {
  37783. if (typeof (urlOrArrayBuffer) === "string")
  37784. this._urlType = "String";
  37785. if (Array.isArray(urlOrArrayBuffer))
  37786. this._urlType = "Array";
  37787. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37788. this._urlType = "ArrayBuffer";
  37789. var urls = [];
  37790. var codecSupportedFound = false;
  37791. switch (this._urlType) {
  37792. case "ArrayBuffer":
  37793. if (urlOrArrayBuffer.byteLength > 0) {
  37794. codecSupportedFound = true;
  37795. this._soundLoaded(urlOrArrayBuffer);
  37796. }
  37797. break;
  37798. case "String":
  37799. urls.push(urlOrArrayBuffer);
  37800. case "Array":
  37801. if (urls.length === 0)
  37802. urls = urlOrArrayBuffer;
  37803. // If we found a supported format, we load it immediately and stop the loop
  37804. for (var i = 0; i < urls.length; i++) {
  37805. var url = urls[i];
  37806. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37807. codecSupportedFound = true;
  37808. }
  37809. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37810. codecSupportedFound = true;
  37811. }
  37812. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37813. codecSupportedFound = true;
  37814. }
  37815. if (codecSupportedFound) {
  37816. // Loading sound using XHR2
  37817. if (!this._streaming) {
  37818. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37819. }
  37820. else {
  37821. this._htmlAudioElement = new Audio(url);
  37822. this._htmlAudioElement.controls = false;
  37823. this._htmlAudioElement.loop = this.loop;
  37824. this._htmlAudioElement.crossOrigin = "anonymous";
  37825. this._htmlAudioElement.preload = "auto";
  37826. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37827. _this._isReadyToPlay = true;
  37828. if (_this.autoplay) {
  37829. _this.play();
  37830. }
  37831. if (_this._readyToPlayCallback) {
  37832. _this._readyToPlayCallback();
  37833. }
  37834. });
  37835. document.body.appendChild(this._htmlAudioElement);
  37836. }
  37837. break;
  37838. }
  37839. }
  37840. break;
  37841. default:
  37842. validParameter = false;
  37843. break;
  37844. }
  37845. if (!validParameter) {
  37846. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37847. }
  37848. else {
  37849. if (!codecSupportedFound) {
  37850. this._isReadyToPlay = true;
  37851. // Simulating a ready to play event to avoid breaking code path
  37852. if (this._readyToPlayCallback) {
  37853. window.setTimeout(function () {
  37854. _this._readyToPlayCallback();
  37855. }, 1000);
  37856. }
  37857. }
  37858. }
  37859. }
  37860. }
  37861. else {
  37862. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37863. this._scene.mainSoundTrack.AddSound(this);
  37864. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37865. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37866. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37867. }
  37868. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37869. if (this._readyToPlayCallback) {
  37870. window.setTimeout(function () {
  37871. _this._readyToPlayCallback();
  37872. }, 1000);
  37873. }
  37874. }
  37875. }
  37876. Sound.prototype.dispose = function () {
  37877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37878. if (this.isPlaying) {
  37879. this.stop();
  37880. }
  37881. this._isReadyToPlay = false;
  37882. if (this.soundTrackId === -1) {
  37883. this._scene.mainSoundTrack.RemoveSound(this);
  37884. }
  37885. else {
  37886. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37887. }
  37888. if (this._soundGain) {
  37889. this._soundGain.disconnect();
  37890. this._soundGain = null;
  37891. }
  37892. if (this._soundPanner) {
  37893. this._soundPanner.disconnect();
  37894. this._soundPanner = null;
  37895. }
  37896. if (this._soundSource) {
  37897. this._soundSource.disconnect();
  37898. this._soundSource = null;
  37899. }
  37900. this._audioBuffer = null;
  37901. if (this._htmlAudioElement) {
  37902. this._htmlAudioElement.pause();
  37903. this._htmlAudioElement.src = "";
  37904. document.body.removeChild(this._htmlAudioElement);
  37905. }
  37906. if (this._connectedMesh) {
  37907. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37908. this._connectedMesh = null;
  37909. }
  37910. }
  37911. };
  37912. Sound.prototype._soundLoaded = function (audioData) {
  37913. var _this = this;
  37914. this._isLoaded = true;
  37915. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37916. _this._audioBuffer = buffer;
  37917. _this._isReadyToPlay = true;
  37918. if (_this.autoplay) {
  37919. _this.play();
  37920. }
  37921. if (_this._readyToPlayCallback) {
  37922. _this._readyToPlayCallback();
  37923. }
  37924. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37925. };
  37926. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37928. this._audioBuffer = audioBuffer;
  37929. this._isReadyToPlay = true;
  37930. }
  37931. };
  37932. Sound.prototype.updateOptions = function (options) {
  37933. if (options) {
  37934. this.loop = options.loop || this.loop;
  37935. this.maxDistance = options.maxDistance || this.maxDistance;
  37936. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37937. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37938. this.refDistance = options.refDistance || this.refDistance;
  37939. this.distanceModel = options.distanceModel || this.distanceModel;
  37940. this._playbackRate = options.playbackRate || this._playbackRate;
  37941. this._updateSpatialParameters();
  37942. if (this.isPlaying) {
  37943. if (this._streaming) {
  37944. this._htmlAudioElement.playbackRate = this._playbackRate;
  37945. }
  37946. else {
  37947. this._soundSource.playbackRate.value = this._playbackRate;
  37948. }
  37949. }
  37950. }
  37951. };
  37952. Sound.prototype._createSpatialParameters = function () {
  37953. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37954. if (this._scene.headphone) {
  37955. this._panningModel = "HRTF";
  37956. }
  37957. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37958. this._updateSpatialParameters();
  37959. this._soundPanner.connect(this._ouputAudioNode);
  37960. this._inputAudioNode = this._soundPanner;
  37961. }
  37962. };
  37963. Sound.prototype._updateSpatialParameters = function () {
  37964. if (this.spatialSound) {
  37965. if (this.useCustomAttenuation) {
  37966. // Tricks to disable in a way embedded Web Audio attenuation
  37967. this._soundPanner.distanceModel = "linear";
  37968. this._soundPanner.maxDistance = Number.MAX_VALUE;
  37969. this._soundPanner.refDistance = 1;
  37970. this._soundPanner.rolloffFactor = 1;
  37971. this._soundPanner.panningModel = this._panningModel;
  37972. }
  37973. else {
  37974. this._soundPanner.distanceModel = this.distanceModel;
  37975. this._soundPanner.maxDistance = this.maxDistance;
  37976. this._soundPanner.refDistance = this.refDistance;
  37977. this._soundPanner.rolloffFactor = this.rolloffFactor;
  37978. this._soundPanner.panningModel = this._panningModel;
  37979. }
  37980. }
  37981. };
  37982. Sound.prototype.switchPanningModelToHRTF = function () {
  37983. this._panningModel = "HRTF";
  37984. this._switchPanningModel();
  37985. };
  37986. Sound.prototype.switchPanningModelToEqualPower = function () {
  37987. this._panningModel = "equalpower";
  37988. this._switchPanningModel();
  37989. };
  37990. Sound.prototype._switchPanningModel = function () {
  37991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37992. this._soundPanner.panningModel = this._panningModel;
  37993. }
  37994. };
  37995. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  37996. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37997. if (this._isOutputConnected) {
  37998. this._ouputAudioNode.disconnect();
  37999. }
  38000. this._ouputAudioNode.connect(soundTrackAudioNode);
  38001. this._isOutputConnected = true;
  38002. }
  38003. };
  38004. /**
  38005. * Transform this sound into a directional source
  38006. * @param coneInnerAngle Size of the inner cone in degree
  38007. * @param coneOuterAngle Size of the outer cone in degree
  38008. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38009. */
  38010. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38011. if (coneOuterAngle < coneInnerAngle) {
  38012. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38013. return;
  38014. }
  38015. this._coneInnerAngle = coneInnerAngle;
  38016. this._coneOuterAngle = coneOuterAngle;
  38017. this._coneOuterGain = coneOuterGain;
  38018. this._isDirectional = true;
  38019. if (this.isPlaying && this.loop) {
  38020. this.stop();
  38021. this.play();
  38022. }
  38023. };
  38024. Sound.prototype.setPosition = function (newPosition) {
  38025. this._position = newPosition;
  38026. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38027. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38028. }
  38029. };
  38030. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38031. this._localDirection = newLocalDirection;
  38032. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38033. this._updateDirection();
  38034. }
  38035. };
  38036. Sound.prototype._updateDirection = function () {
  38037. var mat = this._connectedMesh.getWorldMatrix();
  38038. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38039. direction.normalize();
  38040. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38041. };
  38042. Sound.prototype.updateDistanceFromListener = function () {
  38043. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38044. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38045. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38046. }
  38047. };
  38048. Sound.prototype.setAttenuationFunction = function (callback) {
  38049. this._customAttenuationFunction = callback;
  38050. };
  38051. /**
  38052. * Play the sound
  38053. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38054. * @param offset (optional) Start the sound setting it at a specific time
  38055. */
  38056. Sound.prototype.play = function (time, offset) {
  38057. var _this = this;
  38058. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38059. try {
  38060. if (this._startOffset < 0) {
  38061. time = -this._startOffset;
  38062. this._startOffset = 0;
  38063. }
  38064. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38065. if (!this._soundSource || !this._streamingSource) {
  38066. if (this.spatialSound) {
  38067. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38068. if (this._isDirectional) {
  38069. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38070. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38071. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38072. if (this._connectedMesh) {
  38073. this._updateDirection();
  38074. }
  38075. else {
  38076. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38077. }
  38078. }
  38079. }
  38080. }
  38081. if (this._streaming) {
  38082. if (!this._streamingSource) {
  38083. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38084. this._htmlAudioElement.onended = function () { _this._onended(); };
  38085. this._htmlAudioElement.playbackRate = this._playbackRate;
  38086. }
  38087. this._streamingSource.disconnect();
  38088. this._streamingSource.connect(this._inputAudioNode);
  38089. this._htmlAudioElement.play();
  38090. }
  38091. else {
  38092. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38093. this._soundSource.buffer = this._audioBuffer;
  38094. this._soundSource.connect(this._inputAudioNode);
  38095. this._soundSource.loop = this.loop;
  38096. this._soundSource.playbackRate.value = this._playbackRate;
  38097. this._soundSource.onended = function () { _this._onended(); };
  38098. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38099. }
  38100. this._startTime = startTime;
  38101. this.isPlaying = true;
  38102. this.isPaused = false;
  38103. }
  38104. catch (ex) {
  38105. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38106. }
  38107. }
  38108. };
  38109. Sound.prototype._onended = function () {
  38110. this.isPlaying = false;
  38111. if (this.onended) {
  38112. this.onended();
  38113. }
  38114. };
  38115. /**
  38116. * Stop the sound
  38117. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38118. */
  38119. Sound.prototype.stop = function (time) {
  38120. if (this.isPlaying) {
  38121. if (this._streaming) {
  38122. this._htmlAudioElement.pause();
  38123. // Test needed for Firefox or it will generate an Invalid State Error
  38124. if (this._htmlAudioElement.currentTime > 0) {
  38125. this._htmlAudioElement.currentTime = 0;
  38126. }
  38127. }
  38128. else {
  38129. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38130. this._soundSource.stop(stopTime);
  38131. this._soundSource.onended = null;
  38132. if (!this.isPaused) {
  38133. this._startOffset = 0;
  38134. }
  38135. }
  38136. this.isPlaying = false;
  38137. }
  38138. };
  38139. Sound.prototype.pause = function () {
  38140. if (this.isPlaying) {
  38141. this.isPaused = true;
  38142. if (this._streaming) {
  38143. this._htmlAudioElement.pause();
  38144. }
  38145. else {
  38146. this.stop(0);
  38147. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38148. }
  38149. }
  38150. };
  38151. Sound.prototype.setVolume = function (newVolume, time) {
  38152. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38153. if (time) {
  38154. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38155. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38156. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38157. }
  38158. else {
  38159. this._soundGain.gain.value = newVolume;
  38160. }
  38161. }
  38162. this._volume = newVolume;
  38163. };
  38164. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38165. this._playbackRate = newPlaybackRate;
  38166. if (this.isPlaying) {
  38167. if (this._streaming) {
  38168. this._htmlAudioElement.playbackRate = this._playbackRate;
  38169. }
  38170. else {
  38171. this._soundSource.playbackRate.value = this._playbackRate;
  38172. }
  38173. }
  38174. };
  38175. Sound.prototype.getVolume = function () {
  38176. return this._volume;
  38177. };
  38178. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38179. var _this = this;
  38180. if (this._connectedMesh) {
  38181. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38182. this._registerFunc = null;
  38183. }
  38184. this._connectedMesh = meshToConnectTo;
  38185. if (!this.spatialSound) {
  38186. this.spatialSound = true;
  38187. this._createSpatialParameters();
  38188. if (this.isPlaying && this.loop) {
  38189. this.stop();
  38190. this.play();
  38191. }
  38192. }
  38193. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38194. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38195. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38196. };
  38197. Sound.prototype.detachFromMesh = function () {
  38198. if (this._connectedMesh) {
  38199. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38200. this._registerFunc = null;
  38201. this._connectedMesh = null;
  38202. }
  38203. };
  38204. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38205. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38206. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38207. this._updateDirection();
  38208. }
  38209. };
  38210. Sound.prototype.clone = function () {
  38211. var _this = this;
  38212. if (!this._streaming) {
  38213. var setBufferAndRun = function () {
  38214. if (_this._isReadyToPlay) {
  38215. clonedSound._audioBuffer = _this.getAudioBuffer();
  38216. clonedSound._isReadyToPlay = true;
  38217. if (clonedSound.autoplay) {
  38218. clonedSound.play();
  38219. }
  38220. }
  38221. else {
  38222. window.setTimeout(setBufferAndRun, 300);
  38223. }
  38224. };
  38225. var currentOptions = {
  38226. autoplay: this.autoplay, loop: this.loop,
  38227. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38228. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38229. refDistance: this.refDistance, distanceModel: this.distanceModel
  38230. };
  38231. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38232. if (this.useCustomAttenuation) {
  38233. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38234. }
  38235. clonedSound.setPosition(this._position);
  38236. clonedSound.setPlaybackRate(this._playbackRate);
  38237. setBufferAndRun();
  38238. return clonedSound;
  38239. }
  38240. else {
  38241. return null;
  38242. }
  38243. };
  38244. Sound.prototype.getAudioBuffer = function () {
  38245. return this._audioBuffer;
  38246. };
  38247. Sound.prototype.serialize = function () {
  38248. var serializationObject = {
  38249. name: this.name,
  38250. url: this.name,
  38251. autoplay: this.autoplay,
  38252. loop: this.loop,
  38253. volume: this._volume,
  38254. spatialSound: this.spatialSound,
  38255. maxDistance: this.maxDistance,
  38256. rolloffFactor: this.rolloffFactor,
  38257. refDistance: this.refDistance,
  38258. distanceModel: this.distanceModel,
  38259. playbackRate: this._playbackRate,
  38260. panningModel: this._panningModel,
  38261. soundTrackId: this.soundTrackId
  38262. };
  38263. if (this.spatialSound) {
  38264. if (this._connectedMesh)
  38265. serializationObject.connectedMeshId = this._connectedMesh.id;
  38266. serializationObject.position = this._position.asArray();
  38267. serializationObject.refDistance = this.refDistance;
  38268. serializationObject.distanceModel = this.distanceModel;
  38269. serializationObject.isDirectional = this._isDirectional;
  38270. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38271. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38272. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38273. serializationObject.coneOuterGain = this._coneOuterGain;
  38274. }
  38275. return serializationObject;
  38276. };
  38277. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38278. var soundName = parsedSound.name;
  38279. var soundUrl;
  38280. if (parsedSound.url) {
  38281. soundUrl = rootUrl + parsedSound.url;
  38282. }
  38283. else {
  38284. soundUrl = rootUrl + soundName;
  38285. }
  38286. var options = {
  38287. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38288. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38289. rolloffFactor: parsedSound.rolloffFactor,
  38290. refDistance: parsedSound.refDistance,
  38291. distanceModel: parsedSound.distanceModel,
  38292. playbackRate: parsedSound.playbackRate
  38293. };
  38294. var newSound;
  38295. if (!sourceSound) {
  38296. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38297. scene._addPendingData(newSound);
  38298. }
  38299. else {
  38300. var setBufferAndRun = function () {
  38301. if (sourceSound._isReadyToPlay) {
  38302. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38303. newSound._isReadyToPlay = true;
  38304. if (newSound.autoplay) {
  38305. newSound.play();
  38306. }
  38307. }
  38308. else {
  38309. window.setTimeout(setBufferAndRun, 300);
  38310. }
  38311. };
  38312. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38313. setBufferAndRun();
  38314. }
  38315. if (parsedSound.position) {
  38316. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38317. newSound.setPosition(soundPosition);
  38318. }
  38319. if (parsedSound.isDirectional) {
  38320. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38321. if (parsedSound.localDirectionToMesh) {
  38322. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38323. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38324. }
  38325. }
  38326. if (parsedSound.connectedMeshId) {
  38327. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38328. if (connectedMesh) {
  38329. newSound.attachToMesh(connectedMesh);
  38330. }
  38331. }
  38332. return newSound;
  38333. };
  38334. return Sound;
  38335. }());
  38336. BABYLON.Sound = Sound;
  38337. })(BABYLON || (BABYLON = {}));
  38338. //# sourceMappingURL=babylon.sound.js.map
  38339. var BABYLON;
  38340. (function (BABYLON) {
  38341. var SoundTrack = (function () {
  38342. function SoundTrack(scene, options) {
  38343. this.id = -1;
  38344. this._isMainTrack = false;
  38345. this._isInitialized = false;
  38346. this._scene = scene;
  38347. this.soundCollection = new Array();
  38348. this._options = options;
  38349. if (!this._isMainTrack) {
  38350. this._scene.soundTracks.push(this);
  38351. this.id = this._scene.soundTracks.length - 1;
  38352. }
  38353. }
  38354. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38356. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38357. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38358. if (this._options) {
  38359. if (this._options.volume) {
  38360. this._outputAudioNode.gain.value = this._options.volume;
  38361. }
  38362. if (this._options.mainTrack) {
  38363. this._isMainTrack = this._options.mainTrack;
  38364. }
  38365. }
  38366. this._isInitialized = true;
  38367. }
  38368. };
  38369. SoundTrack.prototype.dispose = function () {
  38370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38371. if (this._connectedAnalyser) {
  38372. this._connectedAnalyser.stopDebugCanvas();
  38373. }
  38374. while (this.soundCollection.length) {
  38375. this.soundCollection[0].dispose();
  38376. }
  38377. if (this._outputAudioNode) {
  38378. this._outputAudioNode.disconnect();
  38379. }
  38380. this._outputAudioNode = null;
  38381. }
  38382. };
  38383. SoundTrack.prototype.AddSound = function (sound) {
  38384. if (!this._isInitialized) {
  38385. this._initializeSoundTrackAudioGraph();
  38386. }
  38387. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38388. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38389. }
  38390. if (sound.soundTrackId) {
  38391. if (sound.soundTrackId === -1) {
  38392. this._scene.mainSoundTrack.RemoveSound(sound);
  38393. }
  38394. else {
  38395. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38396. }
  38397. }
  38398. this.soundCollection.push(sound);
  38399. sound.soundTrackId = this.id;
  38400. };
  38401. SoundTrack.prototype.RemoveSound = function (sound) {
  38402. var index = this.soundCollection.indexOf(sound);
  38403. if (index !== -1) {
  38404. this.soundCollection.splice(index, 1);
  38405. }
  38406. };
  38407. SoundTrack.prototype.setVolume = function (newVolume) {
  38408. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38409. this._outputAudioNode.gain.value = newVolume;
  38410. }
  38411. };
  38412. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38413. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38414. for (var i = 0; i < this.soundCollection.length; i++) {
  38415. this.soundCollection[i].switchPanningModelToHRTF();
  38416. }
  38417. }
  38418. };
  38419. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38420. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38421. for (var i = 0; i < this.soundCollection.length; i++) {
  38422. this.soundCollection[i].switchPanningModelToEqualPower();
  38423. }
  38424. }
  38425. };
  38426. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38427. if (this._connectedAnalyser) {
  38428. this._connectedAnalyser.stopDebugCanvas();
  38429. }
  38430. this._connectedAnalyser = analyser;
  38431. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38432. this._outputAudioNode.disconnect();
  38433. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38434. }
  38435. };
  38436. return SoundTrack;
  38437. }());
  38438. BABYLON.SoundTrack = SoundTrack;
  38439. })(BABYLON || (BABYLON = {}));
  38440. //# sourceMappingURL=babylon.soundtrack.js.map
  38441. var BABYLON;
  38442. (function (BABYLON) {
  38443. /**
  38444. * Special Glow Blur post process only blurring the alpha channel
  38445. * It enforces keeping the most luminous color in the color channel.
  38446. */
  38447. var GlowBlurPostProcess = (function (_super) {
  38448. __extends(GlowBlurPostProcess, _super);
  38449. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38450. var _this = this;
  38451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38452. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  38453. this.direction = direction;
  38454. this.blurWidth = blurWidth;
  38455. this.onApplyObservable.add(function (effect) {
  38456. effect.setFloat2("screenSize", _this.width, _this.height);
  38457. effect.setVector2("direction", _this.direction);
  38458. effect.setFloat("blurWidth", _this.blurWidth);
  38459. });
  38460. }
  38461. return GlowBlurPostProcess;
  38462. }(BABYLON.PostProcess));
  38463. /**
  38464. * The highlight layer Helps adding a glow effect around a mesh.
  38465. *
  38466. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38467. * glowy meshes to your scene.
  38468. *
  38469. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38470. */
  38471. var HighlightLayer = (function () {
  38472. /**
  38473. * Instantiates a new highlight Layer and references it to the scene..
  38474. * @param name The name of the layer
  38475. * @param scene The scene to use the layer in
  38476. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38477. */
  38478. function HighlightLayer(name, scene, options) {
  38479. this._vertexBuffers = {};
  38480. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38481. this._meshes = {};
  38482. this._maxSize = 0;
  38483. this._shouldRender = false;
  38484. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38485. this._excludedMeshes = {};
  38486. /**
  38487. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38488. */
  38489. this.innerGlow = true;
  38490. /**
  38491. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38492. */
  38493. this.outerGlow = true;
  38494. /**
  38495. * Specifies wether the highlight layer is enabled or not.
  38496. */
  38497. this.isEnabled = true;
  38498. /**
  38499. * An event triggered when the highlight layer has been disposed.
  38500. * @type {BABYLON.Observable}
  38501. */
  38502. this.onDisposeObservable = new BABYLON.Observable();
  38503. /**
  38504. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38505. * @type {BABYLON.Observable}
  38506. */
  38507. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38508. /**
  38509. * An event triggered when the highlight layer is being blurred.
  38510. * @type {BABYLON.Observable}
  38511. */
  38512. this.onBeforeBlurObservable = new BABYLON.Observable();
  38513. /**
  38514. * An event triggered when the highlight layer has been blurred.
  38515. * @type {BABYLON.Observable}
  38516. */
  38517. this.onAfterBlurObservable = new BABYLON.Observable();
  38518. /**
  38519. * An event triggered when the glowing blurred texture is being merged in the scene.
  38520. * @type {BABYLON.Observable}
  38521. */
  38522. this.onBeforeComposeObservable = new BABYLON.Observable();
  38523. /**
  38524. * An event triggered when the glowing blurred texture has been merged in the scene.
  38525. * @type {BABYLON.Observable}
  38526. */
  38527. this.onAfterComposeObservable = new BABYLON.Observable();
  38528. /**
  38529. * An event triggered when the highlight layer changes its size.
  38530. * @type {BABYLON.Observable}
  38531. */
  38532. this.onSizeChangedObservable = new BABYLON.Observable();
  38533. this._scene = scene;
  38534. var engine = scene.getEngine();
  38535. this._engine = engine;
  38536. this._maxSize = this._engine.getCaps().maxTextureSize;
  38537. this._scene.highlightLayers.push(this);
  38538. // Warn on stencil.
  38539. if (!this._engine.isStencilEnable) {
  38540. 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 }");
  38541. }
  38542. // Adapt options
  38543. this._options = options || {
  38544. mainTextureRatio: 0.25,
  38545. blurTextureSizeRatio: 0.5,
  38546. blurHorizontalSize: 1,
  38547. blurVerticalSize: 1,
  38548. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38549. };
  38550. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38551. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38552. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38553. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38554. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38555. // VBO
  38556. var vertices = [];
  38557. vertices.push(1, 1);
  38558. vertices.push(-1, 1);
  38559. vertices.push(-1, -1);
  38560. vertices.push(1, -1);
  38561. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38562. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38563. // Indices
  38564. var indices = [];
  38565. indices.push(0);
  38566. indices.push(1);
  38567. indices.push(2);
  38568. indices.push(0);
  38569. indices.push(2);
  38570. indices.push(3);
  38571. this._indexBuffer = engine.createIndexBuffer(indices);
  38572. // Effect
  38573. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38574. // Render target
  38575. this.setMainTextureSize();
  38576. // Create Textures and post processes
  38577. this.createTextureAndPostProcesses();
  38578. }
  38579. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38580. /**
  38581. * Gets the horizontal size of the blur.
  38582. */
  38583. get: function () {
  38584. return this._horizontalBlurPostprocess.blurWidth;
  38585. },
  38586. /**
  38587. * Specifies the horizontal size of the blur.
  38588. */
  38589. set: function (value) {
  38590. this._horizontalBlurPostprocess.blurWidth = value;
  38591. },
  38592. enumerable: true,
  38593. configurable: true
  38594. });
  38595. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38596. /**
  38597. * Gets the vertical size of the blur.
  38598. */
  38599. get: function () {
  38600. return this._verticalBlurPostprocess.blurWidth;
  38601. },
  38602. /**
  38603. * Specifies the vertical size of the blur.
  38604. */
  38605. set: function (value) {
  38606. this._verticalBlurPostprocess.blurWidth = value;
  38607. },
  38608. enumerable: true,
  38609. configurable: true
  38610. });
  38611. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38612. /**
  38613. * Gets the camera attached to the layer.
  38614. */
  38615. get: function () {
  38616. return this._options.camera;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. /**
  38622. * Creates the render target textures and post processes used in the highlight layer.
  38623. */
  38624. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38625. var _this = this;
  38626. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38627. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38628. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38629. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38630. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38631. width: this._mainTextureDesiredSize.width,
  38632. height: this._mainTextureDesiredSize.height
  38633. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38634. this._mainTexture.activeCamera = this._options.camera;
  38635. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38636. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38637. this._mainTexture.anisotropicFilteringLevel = 1;
  38638. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38639. this._mainTexture.renderParticles = false;
  38640. this._mainTexture.renderList = null;
  38641. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38642. width: blurTextureWidth,
  38643. height: blurTextureHeight
  38644. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38645. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38646. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38647. this._blurTexture.anisotropicFilteringLevel = 16;
  38648. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38649. this._blurTexture.renderParticles = false;
  38650. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38651. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38652. effect.setTexture("textureSampler", _this._mainTexture);
  38653. });
  38654. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38655. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38656. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38657. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38658. });
  38659. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38660. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38661. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38662. });
  38663. }
  38664. else {
  38665. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38666. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38667. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38668. });
  38669. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38670. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38671. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38672. });
  38673. }
  38674. this._mainTexture.onAfterUnbindObservable.add(function () {
  38675. _this.onBeforeBlurObservable.notifyObservers(_this);
  38676. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38677. _this.onAfterBlurObservable.notifyObservers(_this);
  38678. });
  38679. // Custom render function
  38680. var renderSubMesh = function (subMesh) {
  38681. var mesh = subMesh.getRenderingMesh();
  38682. var scene = _this._scene;
  38683. var engine = scene.getEngine();
  38684. // Culling
  38685. engine.setState(subMesh.getMaterial().backFaceCulling);
  38686. // Managing instances
  38687. var batch = mesh._getInstancesRenderList(subMesh._id);
  38688. if (batch.mustReturn) {
  38689. return;
  38690. }
  38691. // Excluded Mesh
  38692. if (_this._excludedMeshes[mesh.id]) {
  38693. return;
  38694. }
  38695. ;
  38696. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38697. var highlightLayerMesh = _this._meshes[mesh.id];
  38698. var material = subMesh.getMaterial();
  38699. var emissiveTexture = null;
  38700. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38701. emissiveTexture = material.emissiveTexture;
  38702. }
  38703. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38704. engine.enableEffect(_this._glowMapGenerationEffect);
  38705. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38706. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38707. if (highlightLayerMesh) {
  38708. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38709. }
  38710. else {
  38711. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38712. }
  38713. // Alpha test
  38714. if (material && material.needAlphaTesting()) {
  38715. var alphaTexture = material.getAlphaTestTexture();
  38716. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38717. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38718. }
  38719. // Glow emissive only
  38720. if (emissiveTexture) {
  38721. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38722. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38723. }
  38724. // Bones
  38725. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38726. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38727. }
  38728. // Draw
  38729. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38730. }
  38731. else {
  38732. // Need to reset refresh rate of the shadowMap
  38733. _this._mainTexture.resetRefreshCounter();
  38734. }
  38735. };
  38736. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38737. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38738. var index;
  38739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38740. renderSubMesh(opaqueSubMeshes.data[index]);
  38741. }
  38742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38743. renderSubMesh(alphaTestSubMeshes.data[index]);
  38744. }
  38745. for (index = 0; index < transparentSubMeshes.length; index++) {
  38746. renderSubMesh(transparentSubMeshes.data[index]);
  38747. }
  38748. };
  38749. this._mainTexture.onClearObservable.add(function (engine) {
  38750. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38751. });
  38752. };
  38753. /**
  38754. * Checks for the readiness of the element composing the layer.
  38755. * @param subMesh the mesh to check for
  38756. * @param useInstances specify wether or not to use instances to render the mesh
  38757. * @param emissiveTexture the associated emissive texture used to generate the glow
  38758. * @return true if ready otherwise, false
  38759. */
  38760. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38761. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38762. return false;
  38763. }
  38764. var defines = [];
  38765. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38766. var mesh = subMesh.getMesh();
  38767. var material = subMesh.getMaterial();
  38768. var uv1 = false;
  38769. var uv2 = false;
  38770. // Alpha test
  38771. if (material && material.needAlphaTesting()) {
  38772. var alphaTexture = material.getAlphaTestTexture();
  38773. if (alphaTexture) {
  38774. defines.push("#define ALPHATEST");
  38775. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38776. alphaTexture.coordinatesIndex === 1) {
  38777. defines.push("#define DIFFUSEUV2");
  38778. uv2 = true;
  38779. }
  38780. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38781. defines.push("#define DIFFUSEUV1");
  38782. uv1 = true;
  38783. }
  38784. }
  38785. }
  38786. // Emissive
  38787. if (emissiveTexture) {
  38788. defines.push("#define EMISSIVE");
  38789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38790. emissiveTexture.coordinatesIndex === 1) {
  38791. defines.push("#define EMISSIVEUV2");
  38792. uv2 = true;
  38793. }
  38794. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38795. defines.push("#define EMISSIVEUV1");
  38796. uv1 = true;
  38797. }
  38798. }
  38799. if (uv1) {
  38800. attribs.push(BABYLON.VertexBuffer.UVKind);
  38801. defines.push("#define UV1");
  38802. }
  38803. if (uv2) {
  38804. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38805. defines.push("#define UV2");
  38806. }
  38807. // Bones
  38808. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38811. if (mesh.numBoneInfluencers > 4) {
  38812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38814. }
  38815. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38816. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38817. }
  38818. else {
  38819. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38820. }
  38821. // Instances
  38822. if (useInstances) {
  38823. defines.push("#define INSTANCES");
  38824. attribs.push("world0");
  38825. attribs.push("world1");
  38826. attribs.push("world2");
  38827. attribs.push("world3");
  38828. }
  38829. // Get correct effect
  38830. var join = defines.join("\n");
  38831. if (this._cachedDefines !== join) {
  38832. this._cachedDefines = join;
  38833. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38834. }
  38835. return this._glowMapGenerationEffect.isReady();
  38836. };
  38837. /**
  38838. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38839. */
  38840. HighlightLayer.prototype.render = function () {
  38841. var currentEffect = this._glowMapMergeEffect;
  38842. // Check
  38843. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38844. return;
  38845. var engine = this._scene.getEngine();
  38846. this.onBeforeComposeObservable.notifyObservers(this);
  38847. // Render
  38848. engine.enableEffect(currentEffect);
  38849. engine.setState(false);
  38850. // Cache
  38851. var previousStencilBuffer = engine.getStencilBuffer();
  38852. var previousStencilFunction = engine.getStencilFunction();
  38853. var previousStencilMask = engine.getStencilMask();
  38854. var previousAlphaMode = engine.getAlphaMode();
  38855. // Texture
  38856. currentEffect.setTexture("textureSampler", this._blurTexture);
  38857. // VBOs
  38858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38859. // Draw order
  38860. engine.setAlphaMode(this._options.alphaBlendingMode);
  38861. engine.setStencilMask(0x00);
  38862. engine.setStencilBuffer(true);
  38863. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38864. if (this.outerGlow) {
  38865. currentEffect.setFloat("offset", 0);
  38866. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38867. engine.draw(true, 0, 6);
  38868. }
  38869. if (this.innerGlow) {
  38870. currentEffect.setFloat("offset", 1);
  38871. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38872. engine.draw(true, 0, 6);
  38873. }
  38874. // Restore Cache
  38875. engine.setStencilFunction(previousStencilFunction);
  38876. engine.setStencilMask(previousStencilMask);
  38877. engine.setAlphaMode(previousAlphaMode);
  38878. engine.setStencilBuffer(previousStencilBuffer);
  38879. this.onAfterComposeObservable.notifyObservers(this);
  38880. // Handle size changes.
  38881. var size = this._mainTexture.getSize();
  38882. this.setMainTextureSize();
  38883. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38884. // Recreate RTT and post processes on size change.
  38885. this.onSizeChangedObservable.notifyObservers(this);
  38886. this.disposeTextureAndPostProcesses();
  38887. this.createTextureAndPostProcesses();
  38888. }
  38889. };
  38890. /**
  38891. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38892. * @param mesh The mesh to exclude from the highlight layer
  38893. */
  38894. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38895. var meshExcluded = this._excludedMeshes[mesh.id];
  38896. if (!meshExcluded) {
  38897. this._excludedMeshes[mesh.id] = {
  38898. mesh: mesh,
  38899. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38900. mesh.getEngine().setStencilBuffer(false);
  38901. }),
  38902. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38903. mesh.getEngine().setStencilBuffer(true);
  38904. }),
  38905. };
  38906. }
  38907. };
  38908. /**
  38909. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38910. * @param mesh The mesh to highlight
  38911. */
  38912. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38913. var meshExcluded = this._excludedMeshes[mesh.id];
  38914. if (meshExcluded) {
  38915. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38916. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38917. }
  38918. this._excludedMeshes[mesh.id] = undefined;
  38919. };
  38920. /**
  38921. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38922. * @param mesh The mesh to highlight
  38923. * @param color The color of the highlight
  38924. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38925. */
  38926. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38927. var _this = this;
  38928. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38929. var meshHighlight = this._meshes[mesh.id];
  38930. if (meshHighlight) {
  38931. meshHighlight.color = color;
  38932. }
  38933. else {
  38934. this._meshes[mesh.id] = {
  38935. mesh: mesh,
  38936. color: color,
  38937. // Lambda required for capture due to Observable this context
  38938. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38939. if (_this._excludedMeshes[mesh.id]) {
  38940. _this.defaultStencilReference(mesh);
  38941. }
  38942. else {
  38943. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38944. }
  38945. }),
  38946. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38947. glowEmissiveOnly: glowEmissiveOnly
  38948. };
  38949. }
  38950. this._shouldRender = true;
  38951. };
  38952. /**
  38953. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38954. * @param mesh The mesh to highlight
  38955. */
  38956. HighlightLayer.prototype.removeMesh = function (mesh) {
  38957. var meshHighlight = this._meshes[mesh.id];
  38958. if (meshHighlight) {
  38959. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38960. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38961. }
  38962. this._meshes[mesh.id] = undefined;
  38963. this._shouldRender = false;
  38964. for (var meshHighlightToCheck in this._meshes) {
  38965. if (meshHighlightToCheck) {
  38966. this._shouldRender = true;
  38967. break;
  38968. }
  38969. }
  38970. };
  38971. /**
  38972. * Returns true if the layer contains information to display, otherwise false.
  38973. */
  38974. HighlightLayer.prototype.shouldRender = function () {
  38975. return this.isEnabled && this._shouldRender;
  38976. };
  38977. /**
  38978. * Sets the main texture desired size which is the closest power of two
  38979. * of the engine canvas size.
  38980. */
  38981. HighlightLayer.prototype.setMainTextureSize = function () {
  38982. if (this._options.mainTextureFixedSize) {
  38983. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  38984. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  38985. }
  38986. else {
  38987. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  38988. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  38989. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  38990. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  38991. }
  38992. };
  38993. /**
  38994. * Force the stencil to the normal expected value for none glowing parts
  38995. */
  38996. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  38997. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  38998. };
  38999. /**
  39000. * Dispose only the render target textures and post process.
  39001. */
  39002. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39003. this._blurTexture.dispose();
  39004. this._mainTexture.dispose();
  39005. this._downSamplePostprocess.dispose();
  39006. this._horizontalBlurPostprocess.dispose();
  39007. this._verticalBlurPostprocess.dispose();
  39008. };
  39009. /**
  39010. * Dispose the highlight layer and free resources.
  39011. */
  39012. HighlightLayer.prototype.dispose = function () {
  39013. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39014. if (vertexBuffer) {
  39015. vertexBuffer.dispose();
  39016. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39017. }
  39018. if (this._indexBuffer) {
  39019. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39020. this._indexBuffer = null;
  39021. }
  39022. // Clean textures and post processes
  39023. this.disposeTextureAndPostProcesses();
  39024. // Clean mesh references
  39025. for (var id in this._meshes) {
  39026. var meshHighlight = this._meshes[id];
  39027. if (meshHighlight && meshHighlight.mesh) {
  39028. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39029. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39030. }
  39031. }
  39032. this._meshes = null;
  39033. for (var id in this._excludedMeshes) {
  39034. var meshHighlight = this._excludedMeshes[id];
  39035. if (meshHighlight) {
  39036. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39037. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39038. }
  39039. }
  39040. this._excludedMeshes = null;
  39041. // Remove from scene
  39042. var index = this._scene.highlightLayers.indexOf(this, 0);
  39043. if (index > -1) {
  39044. this._scene.highlightLayers.splice(index, 1);
  39045. }
  39046. // Callback
  39047. this.onDisposeObservable.notifyObservers(this);
  39048. this.onDisposeObservable.clear();
  39049. this.onBeforeRenderMainTextureObservable.clear();
  39050. this.onBeforeBlurObservable.clear();
  39051. this.onBeforeComposeObservable.clear();
  39052. this.onAfterComposeObservable.clear();
  39053. this.onSizeChangedObservable.clear();
  39054. };
  39055. /**
  39056. * The neutral color used during the preparation of the glow effect.
  39057. * This is black by default as the blend operation is a blend operation.
  39058. */
  39059. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39060. /**
  39061. * Stencil value used for glowing meshes.
  39062. */
  39063. HighlightLayer.glowingMeshStencilReference = 0x02;
  39064. /**
  39065. * Stencil value used for the other meshes in the scene.
  39066. */
  39067. HighlightLayer.normalMeshStencilReference = 0x01;
  39068. return HighlightLayer;
  39069. }());
  39070. BABYLON.HighlightLayer = HighlightLayer;
  39071. })(BABYLON || (BABYLON = {}));
  39072. //# sourceMappingURL=babylon.highlightlayer.js.map
  39073. var BABYLON;
  39074. (function (BABYLON) {
  39075. var SIMDVector3 = (function () {
  39076. function SIMDVector3() {
  39077. }
  39078. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39079. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39080. };
  39081. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39082. var m = transformation.m;
  39083. var m0 = SIMD.Float32x4.load(m, 0);
  39084. var m1 = SIMD.Float32x4.load(m, 4);
  39085. var m2 = SIMD.Float32x4.load(m, 8);
  39086. var m3 = SIMD.Float32x4.load(m, 12);
  39087. 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));
  39088. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39089. result.x = SIMD.Float32x4.extractLane(r, 0);
  39090. result.y = SIMD.Float32x4.extractLane(r, 1);
  39091. result.z = SIMD.Float32x4.extractLane(r, 2);
  39092. };
  39093. return SIMDVector3;
  39094. }());
  39095. var SIMDMatrix = (function () {
  39096. function SIMDMatrix() {
  39097. }
  39098. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39099. var tm = this.m;
  39100. var om = other.m;
  39101. var m0 = SIMD.Float32x4.load(om, 0);
  39102. var m1 = SIMD.Float32x4.load(om, 4);
  39103. var m2 = SIMD.Float32x4.load(om, 8);
  39104. var m3 = SIMD.Float32x4.load(om, 12);
  39105. for (var i = 0; i < 16; i += 4) {
  39106. 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)))));
  39107. }
  39108. return this;
  39109. };
  39110. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39111. var src = this.m;
  39112. var dest = other.m;
  39113. // Load the 4 rows
  39114. var src0 = SIMD.Float32x4.load(src, 0);
  39115. var src1 = SIMD.Float32x4.load(src, 4);
  39116. var src2 = SIMD.Float32x4.load(src, 8);
  39117. var src3 = SIMD.Float32x4.load(src, 12);
  39118. // Transpose the source matrix. Sort of. Not a true transpose operation
  39119. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39120. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39121. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39122. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39123. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39124. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39125. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39126. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39127. // This is a true transposition, but it will lead to an incorrect result
  39128. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39129. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39130. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39131. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39132. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39133. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39134. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39135. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39136. // ----
  39137. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39138. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39139. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39140. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39141. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39142. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39143. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39144. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39145. // ----
  39146. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39147. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39148. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39149. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39150. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39151. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39152. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39153. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39154. // ----
  39155. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39156. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39157. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39158. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39159. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39160. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39161. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39162. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39163. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39164. // ----
  39165. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39166. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39167. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39168. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39169. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39170. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39171. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39172. // ----
  39173. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39174. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39175. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39176. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39177. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39178. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39179. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39180. // ----
  39181. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39182. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39183. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39184. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39185. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39186. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39187. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39188. // Compute determinant
  39189. var det = SIMD.Float32x4.mul(row0, minor0);
  39190. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39191. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39192. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39193. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39194. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39195. // These shuffles aren't necessary if the faulty transposition is done
  39196. // up at the top of this function.
  39197. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39198. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39199. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39200. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39201. // Compute final values by multiplying with 1/det
  39202. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39203. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39204. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39205. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39206. return this;
  39207. };
  39208. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39209. var out = result.m;
  39210. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39211. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39212. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39213. // cc.kmVec3Subtract(f, pCenter, pEye);
  39214. var f = SIMD.Float32x4.sub(center, eye);
  39215. // cc.kmVec3Normalize(f, f);
  39216. var tmp = SIMD.Float32x4.mul(f, f);
  39217. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39218. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39219. // cc.kmVec3Assign(up, pUp);
  39220. // cc.kmVec3Normalize(up, up);
  39221. tmp = SIMD.Float32x4.mul(up, up);
  39222. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39223. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39224. // cc.kmVec3Cross(s, f, up);
  39225. 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)));
  39226. // cc.kmVec3Normalize(s, s);
  39227. tmp = SIMD.Float32x4.mul(s, s);
  39228. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39229. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39230. // cc.kmVec3Cross(u, s, f);
  39231. 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)));
  39232. // cc.kmVec3Normalize(s, s);
  39233. tmp = SIMD.Float32x4.mul(s, s);
  39234. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39235. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39236. var zero = SIMD.Float32x4.splat(0.0);
  39237. s = SIMD.Float32x4.neg(s);
  39238. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39239. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39240. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39241. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39242. 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);
  39243. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39244. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39245. 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)))));
  39246. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39247. 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)))));
  39248. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39249. 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)))));
  39250. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39251. 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)))));
  39252. };
  39253. return SIMDMatrix;
  39254. }());
  39255. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39256. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39257. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39258. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39259. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39260. var SIMDHelper = (function () {
  39261. function SIMDHelper() {
  39262. }
  39263. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39264. get: function () {
  39265. return SIMDHelper._isEnabled;
  39266. },
  39267. enumerable: true,
  39268. configurable: true
  39269. });
  39270. SIMDHelper.DisableSIMD = function () {
  39271. // Replace functions
  39272. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39273. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39274. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39275. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39276. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39277. SIMDHelper._isEnabled = false;
  39278. };
  39279. SIMDHelper.EnableSIMD = function () {
  39280. if (self.SIMD === undefined) {
  39281. return;
  39282. }
  39283. // check if polyfills needed
  39284. if (!self.Math.fround) {
  39285. self.Math.fround = (function (array) { return function (x) {
  39286. return array[0] = x, array[0];
  39287. }; })(new Float32Array(1));
  39288. }
  39289. if (!self.Math.imul) {
  39290. self.Math.imul = function (a, b) {
  39291. var ah = (a >>> 16) & 0xffff;
  39292. var al = a & 0xffff;
  39293. var bh = (b >>> 16) & 0xffff;
  39294. var bl = b & 0xffff;
  39295. // the shift by 0 fixes the sign on the high part
  39296. // the final |0 converts the unsigned value into a signed value
  39297. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39298. };
  39299. }
  39300. // Replace functions
  39301. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39302. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39303. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39304. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39305. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39306. SIMDHelper._isEnabled = true;
  39307. };
  39308. SIMDHelper._isEnabled = false;
  39309. return SIMDHelper;
  39310. }());
  39311. BABYLON.SIMDHelper = SIMDHelper;
  39312. })(BABYLON || (BABYLON = {}));
  39313. //# sourceMappingURL=babylon.math.SIMD.js.map
  39314. var BABYLON;
  39315. (function (BABYLON) {
  39316. /**
  39317. * This class describe a rectangle that were added to the map.
  39318. * You have access to its coordinates either in pixel or normalized (UV)
  39319. */
  39320. var PackedRect = (function () {
  39321. function PackedRect(root, parent, pos, size) {
  39322. this._pos = pos;
  39323. this._size = size;
  39324. this._root = root;
  39325. this._parent = parent;
  39326. this._contentSize = null;
  39327. this._bottomNode = null;
  39328. this._leftNode = null;
  39329. this._initialSize = null;
  39330. this._rightNode = null;
  39331. }
  39332. Object.defineProperty(PackedRect.prototype, "pos", {
  39333. /**
  39334. * @returns the position of this node into the map
  39335. */
  39336. get: function () {
  39337. return this._pos;
  39338. },
  39339. enumerable: true,
  39340. configurable: true
  39341. });
  39342. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39343. /**
  39344. * @returns the size of the rectangle this node handles
  39345. */
  39346. get: function () {
  39347. return this._contentSize;
  39348. },
  39349. enumerable: true,
  39350. configurable: true
  39351. });
  39352. Object.defineProperty(PackedRect.prototype, "UVs", {
  39353. /**
  39354. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39355. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39356. */
  39357. get: function () {
  39358. return this.getUVsForCustomSize(this._root._size);
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. /**
  39364. * 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.
  39365. * This method will return the UVs for this part by given the custom size of what you really use
  39366. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39367. */
  39368. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39369. var mainWidth = this._root._size.width;
  39370. var mainHeight = this._root._size.height;
  39371. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39372. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39373. var uvs = new Array();
  39374. uvs.push(topLeft);
  39375. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39376. uvs.push(rightBottom);
  39377. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39378. return uvs;
  39379. };
  39380. /**
  39381. * Free this rectangle from the map.
  39382. * Call this method when you no longer need the rectangle to be in the map.
  39383. */
  39384. PackedRect.prototype.freeContent = function () {
  39385. if (!this.contentSize) {
  39386. return;
  39387. }
  39388. this._contentSize = null;
  39389. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39390. this.attemptDefrag();
  39391. };
  39392. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39393. get: function () {
  39394. return this._contentSize != null || this._leftNode != null;
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39400. var node = this.findNode(contentSize);
  39401. // Not enough space...
  39402. if (!node) {
  39403. return null;
  39404. }
  39405. node.splitNode(contentSize);
  39406. return node;
  39407. };
  39408. PackedRect.prototype.findNode = function (size) {
  39409. var resNode = null;
  39410. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39411. if (this.isUsed) {
  39412. if (this._leftNode) {
  39413. resNode = this._leftNode.findNode(size);
  39414. }
  39415. if (!resNode && this._rightNode) {
  39416. resNode = this._rightNode.findNode(size);
  39417. }
  39418. if (!resNode && this._bottomNode) {
  39419. resNode = this._bottomNode.findNode(size);
  39420. }
  39421. }
  39422. else if (this._initialSize) {
  39423. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39424. resNode = this;
  39425. }
  39426. else {
  39427. return null;
  39428. }
  39429. }
  39430. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39431. resNode = this;
  39432. }
  39433. return resNode;
  39434. };
  39435. PackedRect.prototype.splitNode = function (contentSize) {
  39436. // 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)
  39437. if (!this._contentSize && this._initialSize) {
  39438. this._contentSize = contentSize.clone();
  39439. 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));
  39440. return this._leftNode.splitNode(contentSize);
  39441. }
  39442. else {
  39443. this._contentSize = contentSize.clone();
  39444. this._initialSize = contentSize.clone();
  39445. if (contentSize.width !== this._size.width) {
  39446. 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));
  39447. }
  39448. if (contentSize.height !== this._size.height) {
  39449. 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));
  39450. }
  39451. return this;
  39452. }
  39453. };
  39454. PackedRect.prototype.attemptDefrag = function () {
  39455. if (!this.isUsed && this.isRecursiveFree) {
  39456. this.clearNode();
  39457. if (this._parent) {
  39458. this._parent.attemptDefrag();
  39459. }
  39460. }
  39461. };
  39462. PackedRect.prototype.clearNode = function () {
  39463. this._initialSize = null;
  39464. this._rightNode = null;
  39465. this._bottomNode = null;
  39466. };
  39467. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39468. get: function () {
  39469. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39470. },
  39471. enumerable: true,
  39472. configurable: true
  39473. });
  39474. PackedRect.prototype.evalFreeSize = function (size) {
  39475. var levelSize = 0;
  39476. if (!this.isUsed) {
  39477. if (this._initialSize) {
  39478. levelSize = this._initialSize.surface;
  39479. }
  39480. else {
  39481. levelSize = this._size.surface;
  39482. }
  39483. }
  39484. if (this._rightNode) {
  39485. levelSize += this._rightNode.evalFreeSize(0);
  39486. }
  39487. if (this._bottomNode) {
  39488. levelSize += this._bottomNode.evalFreeSize(0);
  39489. }
  39490. return levelSize + size;
  39491. };
  39492. return PackedRect;
  39493. }());
  39494. BABYLON.PackedRect = PackedRect;
  39495. /**
  39496. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39497. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39498. * 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.
  39499. */
  39500. var RectPackingMap = (function (_super) {
  39501. __extends(RectPackingMap, _super);
  39502. /**
  39503. * Create an instance of the object with a dimension using the given size
  39504. * @param size The dimension of the rectangle that will contain all the sub ones.
  39505. */
  39506. function RectPackingMap(size) {
  39507. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  39508. this._root = this;
  39509. }
  39510. /**
  39511. * Add a rectangle, finding the best location to store it into the map
  39512. * @param size the dimension of the rectangle to store
  39513. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39514. */
  39515. RectPackingMap.prototype.addRect = function (size) {
  39516. var node = this.findAndSplitNode(size);
  39517. return node;
  39518. };
  39519. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39520. /**
  39521. * Return the current space free normalized between [0;1]
  39522. * @returns {}
  39523. */
  39524. get: function () {
  39525. var freeSize = 0;
  39526. freeSize = this.evalFreeSize(freeSize);
  39527. return freeSize / (this._size.width * this._size.height);
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. return RectPackingMap;
  39533. }(PackedRect));
  39534. BABYLON.RectPackingMap = RectPackingMap;
  39535. })(BABYLON || (BABYLON = {}));
  39536. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39537. var BABYLON;
  39538. (function (BABYLON) {
  39539. var DynamicFloatArrayElementInfo = (function () {
  39540. function DynamicFloatArrayElementInfo() {
  39541. }
  39542. return DynamicFloatArrayElementInfo;
  39543. }());
  39544. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39545. /**
  39546. * 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.
  39547. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39548. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39549. * 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.
  39550. * 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.
  39551. * 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".
  39552. */
  39553. var DynamicFloatArray = (function () {
  39554. /**
  39555. * Construct an instance of the dynamic float array
  39556. * @param stride size of one element in float (i.e. not bytes!)
  39557. * @param initialElementCount the number of available entries at construction
  39558. */
  39559. function DynamicFloatArray(stride, initialElementCount) {
  39560. this.compareValueOffset = null;
  39561. this.sortingAscending = true;
  39562. this._stride = stride;
  39563. this.buffer = new Float32Array(stride * initialElementCount);
  39564. this._lastUsed = 0;
  39565. this._firstFree = 0;
  39566. this._allEntries = new Array(initialElementCount);
  39567. this._freeEntries = new Array(initialElementCount);
  39568. for (var i = 0; i < initialElementCount; i++) {
  39569. var element = new DynamicFloatArrayElementInfo();
  39570. element.offset = i * stride;
  39571. this._allEntries[i] = element;
  39572. this._freeEntries[initialElementCount - i - 1] = element;
  39573. }
  39574. }
  39575. /**
  39576. * Allocate an element in the array.
  39577. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39578. * Beware, this offset may change when you call pack()
  39579. */
  39580. DynamicFloatArray.prototype.allocElement = function () {
  39581. if (this._freeEntries.length === 0) {
  39582. this._growBuffer();
  39583. }
  39584. var el = this._freeEntries.pop();
  39585. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39586. if (el.offset === this._firstFree) {
  39587. if (this._freeEntries.length > 0) {
  39588. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39589. }
  39590. else {
  39591. this._firstFree += this._stride;
  39592. }
  39593. }
  39594. return el;
  39595. };
  39596. /**
  39597. * Free the element corresponding to the given element info
  39598. * @param elInfo the element that describe the allocated element
  39599. */
  39600. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39601. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39602. this._freeEntries.push(elInfo);
  39603. };
  39604. /**
  39605. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39606. * 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().
  39607. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39608. */
  39609. DynamicFloatArray.prototype.pack = function () {
  39610. // no free slot? no need to pack
  39611. if (this._freeEntries.length === 0) {
  39612. return this.buffer;
  39613. }
  39614. // If the buffer is already packed the last used will always be lower than the first free
  39615. // 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.
  39616. if (this._lastUsed < this._firstFree) {
  39617. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39618. return elementsBuffer_1;
  39619. }
  39620. var s = this._stride;
  39621. // 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
  39622. var lastFree = new DynamicFloatArrayElementInfo();
  39623. lastFree.offset = this.totalElementCount * s;
  39624. this._freeEntries.push(lastFree);
  39625. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39626. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39627. var firstFreeSlotOffset = sortedFree[0].offset;
  39628. var freeZoneSize = 1;
  39629. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39630. var prevOffset = sortedFree[0].offset;
  39631. for (var i = 1; i < sortedFree.length; i++) {
  39632. // 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
  39633. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39634. break;
  39635. }
  39636. var curFree = sortedFree[i];
  39637. var curOffset = curFree.offset;
  39638. // Compute the distance between this offset and the previous
  39639. var distance = curOffset - prevOffset;
  39640. // If the distance is the stride size, they are adjacent, it good, move to the next
  39641. if (distance === s) {
  39642. // Free zone is one element bigger
  39643. ++freeZoneSize;
  39644. // as we're about to iterate to the next, the cur becomes the previous...
  39645. prevOffset = curOffset;
  39646. continue;
  39647. }
  39648. // Distance is bigger, which means there's x element between the previous free and this one
  39649. var usedRange = (distance / s) - 1;
  39650. // Two cases the free zone is smaller than the data to move or bigger
  39651. // Copy what can fit in the free zone
  39652. var curMoveOffset = curOffset - s;
  39653. var copyCount = Math.min(freeZoneSize, usedRange);
  39654. for (var j = 0; j < copyCount; j++) {
  39655. var freeI = firstFreeSlotOffset / s;
  39656. var curI = curMoveOffset / s;
  39657. var moveEl = sortedAll[curI];
  39658. this._moveElement(moveEl, firstFreeSlotOffset);
  39659. var replacedEl = sortedAll[freeI];
  39660. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39661. replacedEl.offset = curMoveOffset;
  39662. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39663. sortedAll[freeI] = moveEl;
  39664. sortedAll[curI] = replacedEl;
  39665. curMoveOffset -= s;
  39666. firstFreeSlotOffset += s;
  39667. }
  39668. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39669. if (freeZoneSize <= usedRange) {
  39670. firstFreeSlotOffset = curMoveOffset + s;
  39671. freeZoneSize = 1 + copyCount;
  39672. }
  39673. else {
  39674. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39675. }
  39676. // as we're about to iterate to the next, the cur becomes the previous...
  39677. prevOffset = curOffset;
  39678. }
  39679. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39680. this._lastUsed = firstFreeSlotOffset - s;
  39681. this._firstFree = firstFreeSlotOffset;
  39682. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39683. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39684. this._allEntries = sortedAll;
  39685. return elementsBuffer;
  39686. };
  39687. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39688. for (var i = 0; i < this._stride; i++) {
  39689. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39690. }
  39691. element.offset = destOffset;
  39692. };
  39693. DynamicFloatArray.prototype._growBuffer = function () {
  39694. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39695. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39696. var newBuffer = new Float32Array(newElCount * this._stride);
  39697. newBuffer.set(this.buffer);
  39698. var curCount = this.totalElementCount;
  39699. var addedCount = newElCount - this.totalElementCount;
  39700. for (var i = 0; i < addedCount; i++) {
  39701. var element = new DynamicFloatArrayElementInfo();
  39702. element.offset = (curCount + i) * this.stride;
  39703. this._allEntries.push(element);
  39704. this._freeEntries[addedCount - i - 1] = element;
  39705. }
  39706. this._firstFree = curCount * this.stride;
  39707. this.buffer = newBuffer;
  39708. };
  39709. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39710. /**
  39711. * Get the total count of entries that can fit in the current buffer
  39712. * @returns the elements count
  39713. */
  39714. get: function () {
  39715. return this._allEntries.length;
  39716. },
  39717. enumerable: true,
  39718. configurable: true
  39719. });
  39720. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39721. /**
  39722. * Get the count of free entries that can still be allocated without resizing the buffer
  39723. * @returns the free elements count
  39724. */
  39725. get: function () {
  39726. return this._freeEntries.length;
  39727. },
  39728. enumerable: true,
  39729. configurable: true
  39730. });
  39731. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39732. /**
  39733. * Get the count of allocated elements
  39734. * @returns the allocated elements count
  39735. */
  39736. get: function () {
  39737. return this._allEntries.length - this._freeEntries.length;
  39738. },
  39739. enumerable: true,
  39740. configurable: true
  39741. });
  39742. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39743. /**
  39744. * Return the size of one element in float
  39745. * @returns the size in float
  39746. */
  39747. get: function () {
  39748. return this._stride;
  39749. },
  39750. enumerable: true,
  39751. configurable: true
  39752. });
  39753. DynamicFloatArray.prototype.sort = function () {
  39754. var _this = this;
  39755. if (!this.compareValueOffset) {
  39756. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39757. }
  39758. var count = this.usedElementCount;
  39759. // Do we have to (re)create the sort table?
  39760. if (!this._sortTable || this._sortTable.length < count) {
  39761. // 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...
  39762. var newCount = Math.min(this.totalElementCount, count * 2);
  39763. this._sortTable = new Array(newCount);
  39764. }
  39765. if (!this._sortedTable || this._sortedTable.length !== count) {
  39766. this._sortedTable = new Array(count);
  39767. }
  39768. // Because, you know...
  39769. this.pack();
  39770. //let stride = this.stride;
  39771. //for (let i = 0; i < count; i++) {
  39772. // let si = this._sortTable[i];
  39773. // if (!si) {
  39774. // si = new SortInfo();
  39775. // this._sortTable[i] = si;
  39776. // }
  39777. // si.entry = this._allEntries[i];
  39778. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39779. // si.swapedOffset = null;
  39780. // this._sortedTable[i] = si;
  39781. //}
  39782. var curOffset = 0;
  39783. var stride = this.stride;
  39784. for (var i = 0; i < count; i++, curOffset += stride) {
  39785. var si = this._sortTable[i];
  39786. if (!si) {
  39787. si = new SortInfo();
  39788. this._sortTable[i] = si;
  39789. }
  39790. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39791. si.offset = curOffset;
  39792. si.swapedOffset = null;
  39793. this._sortedTable[i] = si;
  39794. }
  39795. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39796. if (this.sortingAscending) {
  39797. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39798. }
  39799. else {
  39800. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39801. }
  39802. var swapElements = function (src, dst) {
  39803. for (var i = 0; i < stride; i++) {
  39804. var tps = _this.buffer[dst + i];
  39805. _this.buffer[dst + i] = _this.buffer[src + i];
  39806. _this.buffer[src + i] = tps;
  39807. }
  39808. };
  39809. // 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:
  39810. // 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),
  39811. // and I still want something with a good algorithm complexity.
  39812. // 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,
  39813. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39814. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39815. // 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
  39816. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39817. // 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
  39818. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39819. for (var i = 0; i < count; i++) {
  39820. // Get the element to move
  39821. var sourceSI = this._sortedTable[i];
  39822. var destSI = this._sortTable[i];
  39823. var sourceOff = sourceSI.offset;
  39824. // If the source changed location, find the new one
  39825. if (sourceSI.swapedOffset) {
  39826. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39827. var curSI = sourceSI;
  39828. while (curSI.swapedOffset) {
  39829. curSI = this._sortTable[curSI.swapedOffset / stride];
  39830. }
  39831. // Finally get the right location
  39832. sourceOff = curSI.offset;
  39833. }
  39834. // Tag the element being replaced with its new location
  39835. destSI.swapedOffset = sourceOff;
  39836. // Swap elements (only if needed)
  39837. if (sourceOff !== destSI.offset) {
  39838. swapElements(sourceOff, destSI.offset);
  39839. }
  39840. // Update the offset in the corresponding DFAE
  39841. //sourceSI.entry.offset = destSI.entry.offset;
  39842. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39843. }
  39844. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39845. return true;
  39846. };
  39847. return DynamicFloatArray;
  39848. }());
  39849. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39850. var SortInfo = (function () {
  39851. function SortInfo() {
  39852. this.compareData = this.offset = this.swapedOffset = null;
  39853. }
  39854. return SortInfo;
  39855. }());
  39856. })(BABYLON || (BABYLON = {}));
  39857. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39858. var BABYLON;
  39859. (function (BABYLON) {
  39860. /**
  39861. * This class given information about a given character.
  39862. */
  39863. var CharInfo = (function () {
  39864. function CharInfo() {
  39865. }
  39866. return CharInfo;
  39867. }());
  39868. BABYLON.CharInfo = CharInfo;
  39869. var FontTexture = (function (_super) {
  39870. __extends(FontTexture, _super);
  39871. /**
  39872. * Create a new instance of the FontTexture class
  39873. * @param name the name of the texture
  39874. * @param font the font to use, use the W3C CSS notation
  39875. * @param scene the scene that owns the texture
  39876. * @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
  39877. * @param samplingMode the texture sampling mode
  39878. * @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.
  39879. */
  39880. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39881. if (maxCharCount === void 0) { maxCharCount = 200; }
  39882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39883. if (superSample === void 0) { superSample = false; }
  39884. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39885. _super.call(this, null, scene, true, false, samplingMode);
  39886. this._charInfos = {};
  39887. this._curCharCount = 0;
  39888. this._lastUpdateCharCount = -1;
  39889. this._usedCounter = 1;
  39890. this.name = name;
  39891. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39892. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39893. this._sdfScale = 8;
  39894. this._signedDistanceField = signedDistanceField;
  39895. this._superSample = false;
  39896. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39897. if (superSample || signedDistanceField) {
  39898. var sfont = this.getSuperSampleFont(font);
  39899. if (sfont) {
  39900. this._superSample = true;
  39901. font = sfont;
  39902. }
  39903. }
  39904. // First canvas creation to determine the size of the texture to create
  39905. this._canvas = document.createElement("canvas");
  39906. this._context = this._canvas.getContext("2d");
  39907. this._context.font = font;
  39908. this._context.fillStyle = "white";
  39909. this._context.textBaseline = "top";
  39910. this._cachedFontId = null;
  39911. var res = this.getFontHeight(font);
  39912. this._lineHeightSuper = res.height + 4;
  39913. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39914. this._offset = res.offset - 1;
  39915. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39916. this._yMargin = this._xMargin;
  39917. var maxCharWidth = this._context.measureText("W").width;
  39918. this._spaceWidthSuper = this._context.measureText(" ").width;
  39919. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39920. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39921. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39922. var edge = Math.sqrt(totalEstSurface);
  39923. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39924. // Create the texture that will store the font characters
  39925. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39926. var textureSize = this.getSize();
  39927. this.hasAlpha = this._signedDistanceField === false;
  39928. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39929. this._canvas = document.createElement("canvas");
  39930. this._canvas.width = textureSize.width;
  39931. this._canvas.height = textureSize.height;
  39932. this._context = this._canvas.getContext("2d");
  39933. this._context.textBaseline = "top";
  39934. this._context.font = font;
  39935. this._context.fillStyle = "white";
  39936. this._context.imageSmoothingEnabled = false;
  39937. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39938. // 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
  39939. // 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)
  39940. // So you can see this context as an intermediate one, because it is.
  39941. if (this._signedDistanceField) {
  39942. var sdfC = document.createElement("canvas");
  39943. var s = this._sdfScale;
  39944. sdfC.width = maxCharWidth * s;
  39945. sdfC.height = this._lineHeightSuper * s;
  39946. var sdfCtx = sdfC.getContext("2d");
  39947. sdfCtx.scale(s, s);
  39948. sdfCtx.textBaseline = "top";
  39949. sdfCtx.font = font;
  39950. sdfCtx.fillStyle = "white";
  39951. sdfCtx.imageSmoothingEnabled = false;
  39952. this._sdfCanvas = sdfC;
  39953. this._sdfContext = sdfCtx;
  39954. }
  39955. this._currentFreePosition = BABYLON.Vector2.Zero();
  39956. // Add the basic ASCII based characters
  39957. for (var i = 0x20; i < 0x7F; i++) {
  39958. var c = String.fromCharCode(i);
  39959. this.getChar(c);
  39960. }
  39961. this.update();
  39962. }
  39963. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39964. get: function () {
  39965. return this._superSample;
  39966. },
  39967. enumerable: true,
  39968. configurable: true
  39969. });
  39970. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  39971. get: function () {
  39972. return this._signedDistanceField;
  39973. },
  39974. enumerable: true,
  39975. configurable: true
  39976. });
  39977. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  39978. get: function () {
  39979. return this._spaceWidth;
  39980. },
  39981. enumerable: true,
  39982. configurable: true
  39983. });
  39984. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  39985. get: function () {
  39986. return this._lineHeight;
  39987. },
  39988. enumerable: true,
  39989. configurable: true
  39990. });
  39991. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39992. if (supersample === void 0) { supersample = false; }
  39993. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39994. var s = scene;
  39995. if (!s.__fontTextureCache__) {
  39996. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  39997. }
  39998. var dic = s.__fontTextureCache__;
  39999. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40000. var ft = dic.get(lfn);
  40001. if (ft) {
  40002. ++ft._usedCounter;
  40003. return ft;
  40004. }
  40005. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40006. ft._cachedFontId = lfn;
  40007. dic.add(lfn, ft);
  40008. return ft;
  40009. };
  40010. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40011. if (supersample === void 0) { supersample = false; }
  40012. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40013. var s = scene;
  40014. var dic = s.__fontTextureCache__;
  40015. if (!dic) {
  40016. return;
  40017. }
  40018. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40019. var font = dic.get(lfn);
  40020. if (--font._usedCounter === 0) {
  40021. dic.remove(lfn);
  40022. font.dispose();
  40023. }
  40024. };
  40025. /**
  40026. * Make sure the given char is present in the font map.
  40027. * @param char the character to get or add
  40028. * @return the CharInfo instance corresponding to the given character
  40029. */
  40030. FontTexture.prototype.getChar = function (char) {
  40031. if (char.length !== 1) {
  40032. return null;
  40033. }
  40034. var info = this._charInfos[char];
  40035. if (info) {
  40036. return info;
  40037. }
  40038. info = new CharInfo();
  40039. var measure = this._context.measureText(char);
  40040. var textureSize = this.getSize();
  40041. // we reached the end of the current line?
  40042. var width = Math.round(measure.width);
  40043. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40044. this._currentFreePosition.x = 0;
  40045. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40046. // No more room?
  40047. if (this._currentFreePosition.y > textureSize.height) {
  40048. return this.getChar("!");
  40049. }
  40050. }
  40051. // 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)
  40052. if (this._signedDistanceField) {
  40053. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40054. this._sdfContext.fillText(char, 0, -this._offset);
  40055. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40056. var res = this._computeSDFChar(data);
  40057. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40058. }
  40059. else {
  40060. // Draw the character in the HTML canvas
  40061. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40062. }
  40063. // Fill the CharInfo object
  40064. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40065. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40066. if (this._signedDistanceField) {
  40067. var off = 1 / textureSize.width;
  40068. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40069. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40070. }
  40071. info.charWidth = this._superSample ? (width / 2) : width;
  40072. // Add the info structure
  40073. this._charInfos[char] = info;
  40074. this._curCharCount++;
  40075. // Set the next position
  40076. this._currentFreePosition.x += width + this._xMargin;
  40077. return info;
  40078. };
  40079. FontTexture.prototype._computeSDFChar = function (source) {
  40080. var scl = this._sdfScale;
  40081. var sw = source.width;
  40082. var sh = source.height;
  40083. var dw = sw / scl;
  40084. var dh = sh / scl;
  40085. var roffx = 0;
  40086. var roffy = 0;
  40087. // We shouldn't look beyond half of the biggest between width and height
  40088. var radius = scl;
  40089. var br = radius - 1;
  40090. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40091. var sx = dx * scl;
  40092. var sy = dy * scl;
  40093. // Looking out of the area? return true to make the test going on
  40094. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40095. return true;
  40096. }
  40097. // Get the pixel we want
  40098. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40099. var res = (val > 0) === lookVis;
  40100. if (!res) {
  40101. roffx = offX;
  40102. roffy = offY;
  40103. }
  40104. return res;
  40105. };
  40106. var lookupArea = function (dx, dy, lookVis) {
  40107. // 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
  40108. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40109. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40110. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40111. lookupSrc(dx, dy, br, 0, lookVis)) {
  40112. return 0;
  40113. }
  40114. for (var i = 1; i <= radius; i++) {
  40115. // Quick test N, S, W, E
  40116. 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)) {
  40117. return i * i; // Squared Distance is simple to compute in this case
  40118. }
  40119. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40120. for (var j = 1; j <= i; j++) {
  40121. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40122. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40123. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40124. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40125. // We found the nearest texel having and opposite state, store the squared length
  40126. var res_1 = (i * i) + (j * j);
  40127. var count = 1;
  40128. // 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
  40129. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40130. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40131. ++count;
  40132. }
  40133. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40134. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40135. ++count;
  40136. }
  40137. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40138. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40139. ++count;
  40140. }
  40141. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40142. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40143. ++count;
  40144. }
  40145. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40146. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40147. ++count;
  40148. }
  40149. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40150. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40151. ++count;
  40152. }
  40153. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40154. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40155. ++count;
  40156. }
  40157. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40158. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40159. ++count;
  40160. }
  40161. // Compute the average based on the accumulated distance
  40162. return res_1 / count;
  40163. }
  40164. }
  40165. }
  40166. return 0;
  40167. };
  40168. var tmp = new Array(dw * dh);
  40169. for (var y = 0; y < dh; y++) {
  40170. for (var x = 0; x < dw; x++) {
  40171. var curState = lookupSrc(x, y, 0, 0, true);
  40172. var d = lookupArea(x, y, curState);
  40173. if (d === 0) {
  40174. d = radius * radius * 2;
  40175. }
  40176. tmp[(y * dw) + x] = curState ? d : -d;
  40177. }
  40178. }
  40179. var res = this._context.createImageData(dw, dh);
  40180. var size = dw * dh;
  40181. for (var j = 0; j < size; j++) {
  40182. var d = tmp[j];
  40183. var sign = (d < 0) ? -1 : 1;
  40184. d = Math.sqrt(Math.abs(d)) * sign;
  40185. d *= 127.5 / radius;
  40186. d += 127.5;
  40187. if (d < 0) {
  40188. d = 0;
  40189. }
  40190. else if (d > 255) {
  40191. d = 255;
  40192. }
  40193. d += 0.5;
  40194. res.data[j * 4 + 0] = d;
  40195. res.data[j * 4 + 1] = d;
  40196. res.data[j * 4 + 2] = d;
  40197. res.data[j * 4 + 3] = 255;
  40198. }
  40199. return res;
  40200. };
  40201. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40202. if (tabulationSize === void 0) { tabulationSize = 4; }
  40203. var maxWidth = 0;
  40204. var curWidth = 0;
  40205. var lineCount = 1;
  40206. var charxpos = 0;
  40207. // Parse each char of the string
  40208. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40209. var char = text_1[_i];
  40210. // Next line feed?
  40211. if (char === "\n") {
  40212. maxWidth = Math.max(maxWidth, curWidth);
  40213. charxpos = 0;
  40214. curWidth = 0;
  40215. ++lineCount;
  40216. continue;
  40217. }
  40218. // Tabulation ?
  40219. if (char === "\t") {
  40220. var nextPos = charxpos + tabulationSize;
  40221. nextPos = nextPos - (nextPos % tabulationSize);
  40222. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40223. charxpos = nextPos;
  40224. continue;
  40225. }
  40226. if (char < " ") {
  40227. continue;
  40228. }
  40229. curWidth += this.getChar(char).charWidth;
  40230. ++charxpos;
  40231. }
  40232. maxWidth = Math.max(maxWidth, curWidth);
  40233. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40234. };
  40235. FontTexture.prototype.getSuperSampleFont = function (font) {
  40236. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40237. 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*$/;
  40238. var res = font.toLocaleLowerCase().match(regex);
  40239. if (res == null) {
  40240. return null;
  40241. }
  40242. var size = parseInt(res[4]);
  40243. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40244. var newFont = "";
  40245. for (var j = 1; j < res.length; j++) {
  40246. if (res[j] != null) {
  40247. newFont += res[j] + " ";
  40248. }
  40249. }
  40250. return newFont;
  40251. };
  40252. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40253. FontTexture.prototype.getFontHeight = function (font) {
  40254. var fontDraw = document.createElement("canvas");
  40255. var ctx = fontDraw.getContext('2d');
  40256. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40257. ctx.textBaseline = 'top';
  40258. ctx.fillStyle = 'white';
  40259. ctx.font = font;
  40260. ctx.fillText('jH|', 0, 0);
  40261. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40262. var start = -1;
  40263. var end = -1;
  40264. for (var row = 0; row < fontDraw.height; row++) {
  40265. for (var column = 0; column < fontDraw.width; column++) {
  40266. var index = (row * fontDraw.width + column) * 4;
  40267. if (pixels[index] === 0) {
  40268. if (column === fontDraw.width - 1 && start !== -1) {
  40269. end = row;
  40270. row = fontDraw.height;
  40271. break;
  40272. }
  40273. continue;
  40274. }
  40275. else {
  40276. if (start === -1) {
  40277. start = row;
  40278. }
  40279. break;
  40280. }
  40281. }
  40282. }
  40283. return { height: (end - start) + 1, offset: start - 1 };
  40284. };
  40285. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40286. get: function () {
  40287. return false;
  40288. },
  40289. enumerable: true,
  40290. configurable: true
  40291. });
  40292. FontTexture.prototype.getContext = function () {
  40293. return this._context;
  40294. };
  40295. /**
  40296. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40297. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40298. */
  40299. FontTexture.prototype.update = function () {
  40300. // Update only if there's new char added since the previous update
  40301. if (this._lastUpdateCharCount < this._curCharCount) {
  40302. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40303. this._lastUpdateCharCount = this._curCharCount;
  40304. }
  40305. };
  40306. // cloning should be prohibited, there's no point to duplicate this texture at all
  40307. FontTexture.prototype.clone = function () {
  40308. return null;
  40309. };
  40310. /**
  40311. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40312. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40313. */
  40314. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40315. ++this._usedCounter;
  40316. };
  40317. /**
  40318. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40319. */
  40320. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40321. var s = this.getScene();
  40322. var dic = s.__fontTextureCache__;
  40323. if (!dic) {
  40324. return;
  40325. }
  40326. if (--this._usedCounter === 0) {
  40327. dic.remove(this._cachedFontId);
  40328. this.dispose();
  40329. }
  40330. };
  40331. return FontTexture;
  40332. }(BABYLON.Texture));
  40333. BABYLON.FontTexture = FontTexture;
  40334. })(BABYLON || (BABYLON = {}));
  40335. //# sourceMappingURL=babylon.fontTexture.js.map
  40336. var BABYLON;
  40337. (function (BABYLON) {
  40338. var MapTexture = (function (_super) {
  40339. __extends(MapTexture, _super);
  40340. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40342. if (useMipMap === void 0) { useMipMap = false; }
  40343. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  40344. this.name = name;
  40345. this._size = size;
  40346. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40347. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40348. // Create the rectPackMap that will allocate portion of the texture
  40349. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40350. // Create the texture that will store the content
  40351. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40352. }
  40353. /**
  40354. * Allocate a rectangle of a given size in the texture map
  40355. * @param size the size of the rectangle to allocation
  40356. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40357. */
  40358. MapTexture.prototype.allocateRect = function (size) {
  40359. return this._rectPackingMap.addRect(size);
  40360. };
  40361. /**
  40362. * Free a given rectangle from the texture map
  40363. * @param rectInfo the instance corresponding to the rect to free.
  40364. */
  40365. MapTexture.prototype.freeRect = function (rectInfo) {
  40366. if (rectInfo) {
  40367. rectInfo.freeContent();
  40368. }
  40369. };
  40370. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40371. /**
  40372. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40373. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40374. * @returns {}
  40375. */
  40376. get: function () {
  40377. return this._rectPackingMap.freeSpace;
  40378. },
  40379. enumerable: true,
  40380. configurable: true
  40381. });
  40382. /**
  40383. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40384. * 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.
  40385. * Don't forget to call unbindTexture when you're done rendering
  40386. * @param rect the zone to render to
  40387. * @param clear true to clear the portion's color/depth data
  40388. */
  40389. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40390. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40391. };
  40392. /**
  40393. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40394. * 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.
  40395. * Don't forget to call unbindTexture when you're done rendering
  40396. * @param pos the position into the texture
  40397. * @param size the portion to fit the clip space to
  40398. * @param clear true to clear the portion's color/depth data
  40399. */
  40400. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40401. var engine = this.getScene().getEngine();
  40402. engine.bindFramebuffer(this._texture);
  40403. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40404. if (clear) {
  40405. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40406. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40407. }
  40408. };
  40409. /**
  40410. * Unbind the texture map from the rendering engine.
  40411. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40412. * @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.
  40413. */
  40414. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40415. // Dump ?
  40416. if (dumpForDebug) {
  40417. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40418. }
  40419. var engine = this.getScene().getEngine();
  40420. if (this._replacedViewport) {
  40421. engine.setViewport(this._replacedViewport);
  40422. this._replacedViewport = null;
  40423. }
  40424. engine.unBindFramebuffer(this._texture);
  40425. };
  40426. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40427. get: function () {
  40428. return false;
  40429. },
  40430. enumerable: true,
  40431. configurable: true
  40432. });
  40433. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40434. // Anyway, there's not much point to use this method for this kind of texture I guess
  40435. MapTexture.prototype.clone = function () {
  40436. return null;
  40437. };
  40438. return MapTexture;
  40439. }(BABYLON.Texture));
  40440. BABYLON.MapTexture = MapTexture;
  40441. })(BABYLON || (BABYLON = {}));
  40442. //# sourceMappingURL=babylon.mapTexture.js.map
  40443. var BABYLON;
  40444. (function (BABYLON) {
  40445. var ShaderMaterial = (function (_super) {
  40446. __extends(ShaderMaterial, _super);
  40447. function ShaderMaterial(name, scene, shaderPath, options) {
  40448. _super.call(this, name, scene);
  40449. this._textures = {};
  40450. this._textureArrays = {};
  40451. this._floats = {};
  40452. this._floatsArrays = {};
  40453. this._colors3 = {};
  40454. this._colors4 = {};
  40455. this._vectors2 = {};
  40456. this._vectors3 = {};
  40457. this._vectors4 = {};
  40458. this._matrices = {};
  40459. this._matrices3x3 = {};
  40460. this._matrices2x2 = {};
  40461. this._vectors3Arrays = {};
  40462. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40463. this._shaderPath = shaderPath;
  40464. options.needAlphaBlending = options.needAlphaBlending || false;
  40465. options.needAlphaTesting = options.needAlphaTesting || false;
  40466. options.attributes = options.attributes || ["position", "normal", "uv"];
  40467. options.uniforms = options.uniforms || ["worldViewProjection"];
  40468. options.samplers = options.samplers || [];
  40469. options.defines = options.defines || [];
  40470. this._options = options;
  40471. }
  40472. ShaderMaterial.prototype.getClassName = function () {
  40473. return "ShaderMaterial";
  40474. };
  40475. ShaderMaterial.prototype.needAlphaBlending = function () {
  40476. return this._options.needAlphaBlending;
  40477. };
  40478. ShaderMaterial.prototype.needAlphaTesting = function () {
  40479. return this._options.needAlphaTesting;
  40480. };
  40481. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40482. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40483. this._options.uniforms.push(uniformName);
  40484. }
  40485. };
  40486. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40487. if (this._options.samplers.indexOf(name) === -1) {
  40488. this._options.samplers.push(name);
  40489. }
  40490. this._textures[name] = texture;
  40491. return this;
  40492. };
  40493. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40494. if (this._options.samplers.indexOf(name) === -1) {
  40495. this._options.samplers.push(name);
  40496. }
  40497. this._checkUniform(name);
  40498. this._textureArrays[name] = textures;
  40499. return this;
  40500. };
  40501. ShaderMaterial.prototype.setFloat = function (name, value) {
  40502. this._checkUniform(name);
  40503. this._floats[name] = value;
  40504. return this;
  40505. };
  40506. ShaderMaterial.prototype.setFloats = function (name, value) {
  40507. this._checkUniform(name);
  40508. this._floatsArrays[name] = value;
  40509. return this;
  40510. };
  40511. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40512. this._checkUniform(name);
  40513. this._colors3[name] = value;
  40514. return this;
  40515. };
  40516. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40517. this._checkUniform(name);
  40518. this._colors4[name] = value;
  40519. return this;
  40520. };
  40521. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40522. this._checkUniform(name);
  40523. this._vectors2[name] = value;
  40524. return this;
  40525. };
  40526. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40527. this._checkUniform(name);
  40528. this._vectors3[name] = value;
  40529. return this;
  40530. };
  40531. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40532. this._checkUniform(name);
  40533. this._vectors4[name] = value;
  40534. return this;
  40535. };
  40536. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40537. this._checkUniform(name);
  40538. this._matrices[name] = value;
  40539. return this;
  40540. };
  40541. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40542. this._checkUniform(name);
  40543. this._matrices3x3[name] = value;
  40544. return this;
  40545. };
  40546. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40547. this._checkUniform(name);
  40548. this._matrices2x2[name] = value;
  40549. return this;
  40550. };
  40551. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40552. this._checkUniform(name);
  40553. this._vectors3Arrays[name] = value;
  40554. return this;
  40555. };
  40556. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40557. if (!mesh) {
  40558. return true;
  40559. }
  40560. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40561. return false;
  40562. }
  40563. return false;
  40564. };
  40565. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40566. var scene = this.getScene();
  40567. var engine = scene.getEngine();
  40568. if (!this.checkReadyOnEveryCall) {
  40569. if (this._renderId === scene.getRenderId()) {
  40570. if (this._checkCache(scene, mesh, useInstances)) {
  40571. return true;
  40572. }
  40573. }
  40574. }
  40575. // Instances
  40576. var defines = [];
  40577. var fallbacks = new BABYLON.EffectFallbacks();
  40578. if (useInstances) {
  40579. defines.push("#define INSTANCES");
  40580. }
  40581. for (var index = 0; index < this._options.defines.length; index++) {
  40582. defines.push(this._options.defines[index]);
  40583. }
  40584. // Bones
  40585. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40586. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40587. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40588. fallbacks.addCPUSkinningFallback(0, mesh);
  40589. }
  40590. // Alpha test
  40591. if (engine.getAlphaTesting()) {
  40592. defines.push("#define ALPHATEST");
  40593. }
  40594. var previousEffect = this._effect;
  40595. var join = defines.join("\n");
  40596. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40597. if (!this._effect.isReady()) {
  40598. return false;
  40599. }
  40600. if (previousEffect !== this._effect) {
  40601. scene.resetCachedMaterial();
  40602. }
  40603. this._renderId = scene.getRenderId();
  40604. return true;
  40605. };
  40606. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40607. var scene = this.getScene();
  40608. if (this._options.uniforms.indexOf("world") !== -1) {
  40609. this._effect.setMatrix("world", world);
  40610. }
  40611. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40612. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40613. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40614. }
  40615. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40616. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40617. }
  40618. };
  40619. ShaderMaterial.prototype.bind = function (world, mesh) {
  40620. // Std values
  40621. this.bindOnlyWorldMatrix(world);
  40622. if (this.getScene().getCachedMaterial() !== this) {
  40623. if (this._options.uniforms.indexOf("view") !== -1) {
  40624. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40625. }
  40626. if (this._options.uniforms.indexOf("projection") !== -1) {
  40627. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40628. }
  40629. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40630. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40631. }
  40632. // Bones
  40633. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40634. var name;
  40635. // Texture
  40636. for (name in this._textures) {
  40637. this._effect.setTexture(name, this._textures[name]);
  40638. }
  40639. // Texture arrays
  40640. for (name in this._textureArrays) {
  40641. this._effect.setTextureArray(name, this._textureArrays[name]);
  40642. }
  40643. // Float
  40644. for (name in this._floats) {
  40645. this._effect.setFloat(name, this._floats[name]);
  40646. }
  40647. // Float s
  40648. for (name in this._floatsArrays) {
  40649. this._effect.setArray(name, this._floatsArrays[name]);
  40650. }
  40651. // Color3
  40652. for (name in this._colors3) {
  40653. this._effect.setColor3(name, this._colors3[name]);
  40654. }
  40655. // Color4
  40656. for (name in this._colors4) {
  40657. var color = this._colors4[name];
  40658. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40659. }
  40660. // Vector2
  40661. for (name in this._vectors2) {
  40662. this._effect.setVector2(name, this._vectors2[name]);
  40663. }
  40664. // Vector3
  40665. for (name in this._vectors3) {
  40666. this._effect.setVector3(name, this._vectors3[name]);
  40667. }
  40668. // Vector4
  40669. for (name in this._vectors4) {
  40670. this._effect.setVector4(name, this._vectors4[name]);
  40671. }
  40672. // Matrix
  40673. for (name in this._matrices) {
  40674. this._effect.setMatrix(name, this._matrices[name]);
  40675. }
  40676. // Matrix 3x3
  40677. for (name in this._matrices3x3) {
  40678. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40679. }
  40680. // Matrix 2x2
  40681. for (name in this._matrices2x2) {
  40682. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40683. }
  40684. // Vector3Array
  40685. for (name in this._vectors3Arrays) {
  40686. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40687. }
  40688. }
  40689. _super.prototype.bind.call(this, world, mesh);
  40690. };
  40691. ShaderMaterial.prototype.clone = function (name) {
  40692. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40693. return newShaderMaterial;
  40694. };
  40695. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40696. if (forceDisposeTextures) {
  40697. var name;
  40698. for (name in this._textures) {
  40699. this._textures[name].dispose();
  40700. }
  40701. for (name in this._textureArrays) {
  40702. var array = this._textureArrays[name];
  40703. for (var index = 0; index < array.length; index++) {
  40704. array[index].dispose();
  40705. }
  40706. }
  40707. }
  40708. this._textures = {};
  40709. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40710. };
  40711. ShaderMaterial.prototype.serialize = function () {
  40712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40713. serializationObject.customType = "BABYLON.ShaderMaterial";
  40714. serializationObject.options = this._options;
  40715. serializationObject.shaderPath = this._shaderPath;
  40716. var name;
  40717. // Texture
  40718. serializationObject.textures = {};
  40719. for (name in this._textures) {
  40720. serializationObject.textures[name] = this._textures[name].serialize();
  40721. }
  40722. // Texture arrays
  40723. serializationObject.textureArrays = {};
  40724. for (name in this._textureArrays) {
  40725. serializationObject.textureArrays[name] = [];
  40726. var array = this._textureArrays[name];
  40727. for (var index = 0; index < array.length; index++) {
  40728. serializationObject.textureArrays[name].push(array[index].serialize());
  40729. }
  40730. }
  40731. // Float
  40732. serializationObject.floats = {};
  40733. for (name in this._floats) {
  40734. serializationObject.floats[name] = this._floats[name];
  40735. }
  40736. // Float s
  40737. serializationObject.floatArrays = {};
  40738. for (name in this._floatsArrays) {
  40739. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40740. }
  40741. // Color3
  40742. serializationObject.colors3 = {};
  40743. for (name in this._colors3) {
  40744. serializationObject.colors3[name] = this._colors3[name].asArray();
  40745. }
  40746. // Color4
  40747. serializationObject.colors4 = {};
  40748. for (name in this._colors4) {
  40749. serializationObject.colors4[name] = this._colors4[name].asArray();
  40750. }
  40751. // Vector2
  40752. serializationObject.vectors2 = {};
  40753. for (name in this._vectors2) {
  40754. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40755. }
  40756. // Vector3
  40757. serializationObject.vectors3 = {};
  40758. for (name in this._vectors3) {
  40759. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40760. }
  40761. // Vector4
  40762. serializationObject.vectors4 = {};
  40763. for (name in this._vectors4) {
  40764. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40765. }
  40766. // Matrix
  40767. serializationObject.matrices = {};
  40768. for (name in this._matrices) {
  40769. serializationObject.matrices[name] = this._matrices[name].asArray();
  40770. }
  40771. // Matrix 3x3
  40772. serializationObject.matrices3x3 = {};
  40773. for (name in this._matrices3x3) {
  40774. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40775. }
  40776. // Matrix 2x2
  40777. serializationObject.matrices2x2 = {};
  40778. for (name in this._matrices2x2) {
  40779. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40780. }
  40781. // Vector3Array
  40782. serializationObject.vectors3Arrays = {};
  40783. for (name in this._vectors3Arrays) {
  40784. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40785. }
  40786. return serializationObject;
  40787. };
  40788. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40789. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40790. var name;
  40791. // Texture
  40792. for (name in source.textures) {
  40793. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40794. }
  40795. // Texture arrays
  40796. for (name in source.textureArrays) {
  40797. var array = source.textureArrays[name];
  40798. var textureArray = new Array();
  40799. for (var index = 0; index < array.length; index++) {
  40800. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40801. }
  40802. material.setTextureArray(name, textureArray);
  40803. }
  40804. // Float
  40805. for (name in source.floats) {
  40806. material.setFloat(name, source.floats[name]);
  40807. }
  40808. // Float s
  40809. for (name in source.floatsArrays) {
  40810. material.setFloats(name, source.floatsArrays[name]);
  40811. }
  40812. // Color3
  40813. for (name in source.colors3) {
  40814. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40815. }
  40816. // Color4
  40817. for (name in source.colors4) {
  40818. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40819. }
  40820. // Vector2
  40821. for (name in source.vectors2) {
  40822. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40823. }
  40824. // Vector3
  40825. for (name in source.vectors3) {
  40826. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40827. }
  40828. // Vector4
  40829. for (name in source.vectors4) {
  40830. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40831. }
  40832. // Matrix
  40833. for (name in source.matrices) {
  40834. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40835. }
  40836. // Matrix 3x3
  40837. for (name in source.matrices3x3) {
  40838. material.setMatrix3x3(name, source.matrices3x3[name]);
  40839. }
  40840. // Matrix 2x2
  40841. for (name in source.matrices2x2) {
  40842. material.setMatrix2x2(name, source.matrices2x2[name]);
  40843. }
  40844. // Vector3Array
  40845. for (name in source.vectors3Arrays) {
  40846. material.setArray3(name, source.vectors3Arrays[name]);
  40847. }
  40848. return material;
  40849. };
  40850. return ShaderMaterial;
  40851. }(BABYLON.Material));
  40852. BABYLON.ShaderMaterial = ShaderMaterial;
  40853. })(BABYLON || (BABYLON = {}));
  40854. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40855. var BABYLON;
  40856. (function (BABYLON) {
  40857. var Internals;
  40858. (function (Internals) {
  40859. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40860. // All values and structures referenced from:
  40861. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40862. var DDS_MAGIC = 0x20534444;
  40863. 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;
  40864. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40865. 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;
  40866. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40867. function FourCCToInt32(value) {
  40868. return value.charCodeAt(0) +
  40869. (value.charCodeAt(1) << 8) +
  40870. (value.charCodeAt(2) << 16) +
  40871. (value.charCodeAt(3) << 24);
  40872. }
  40873. function Int32ToFourCC(value) {
  40874. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40875. }
  40876. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40877. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40878. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40879. var headerLengthInt = 31; // The header length in 32 bit ints
  40880. // Offsets into the header array
  40881. var off_magic = 0;
  40882. var off_size = 1;
  40883. var off_flags = 2;
  40884. var off_height = 3;
  40885. var off_width = 4;
  40886. var off_mipmapCount = 7;
  40887. var off_pfFlags = 20;
  40888. var off_pfFourCC = 21;
  40889. var off_RGBbpp = 22;
  40890. var off_RMask = 23;
  40891. var off_GMask = 24;
  40892. var off_BMask = 25;
  40893. var off_AMask = 26;
  40894. var off_caps1 = 27;
  40895. var off_caps2 = 28;
  40896. ;
  40897. var DDSTools = (function () {
  40898. function DDSTools() {
  40899. }
  40900. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40901. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40902. var mipmapCount = 1;
  40903. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40904. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40905. }
  40906. return {
  40907. width: header[off_width],
  40908. height: header[off_height],
  40909. mipmapCount: mipmapCount,
  40910. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40911. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40912. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40913. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40914. };
  40915. };
  40916. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40917. var byteArray = new Uint8Array(dataLength);
  40918. var srcData = new Uint8Array(arrayBuffer);
  40919. var index = 0;
  40920. for (var y = height - 1; y >= 0; y--) {
  40921. for (var x = 0; x < width; x++) {
  40922. var srcPos = dataOffset + (x + y * width) * 4;
  40923. byteArray[index + 2] = srcData[srcPos];
  40924. byteArray[index + 1] = srcData[srcPos + 1];
  40925. byteArray[index] = srcData[srcPos + 2];
  40926. byteArray[index + 3] = srcData[srcPos + 3];
  40927. index += 4;
  40928. }
  40929. }
  40930. return byteArray;
  40931. };
  40932. DDSTools.GetRGBArrayBuffer = 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) * 3;
  40939. byteArray[index + 2] = srcData[srcPos];
  40940. byteArray[index + 1] = srcData[srcPos + 1];
  40941. byteArray[index] = srcData[srcPos + 2];
  40942. index += 3;
  40943. }
  40944. }
  40945. return byteArray;
  40946. };
  40947. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40948. var byteArray = new Uint8Array(dataLength);
  40949. var srcData = new Uint8Array(arrayBuffer);
  40950. var index = 0;
  40951. for (var y = height - 1; y >= 0; y--) {
  40952. for (var x = 0; x < width; x++) {
  40953. var srcPos = dataOffset + (x + y * width);
  40954. byteArray[index] = srcData[srcPos];
  40955. index++;
  40956. }
  40957. }
  40958. return byteArray;
  40959. };
  40960. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40961. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40962. if (header[off_magic] != DDS_MAGIC) {
  40963. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40964. return;
  40965. }
  40966. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40967. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40968. return;
  40969. }
  40970. if (info.isFourCC) {
  40971. fourCC = header[off_pfFourCC];
  40972. switch (fourCC) {
  40973. case FOURCC_DXT1:
  40974. blockBytes = 8;
  40975. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40976. break;
  40977. case FOURCC_DXT3:
  40978. blockBytes = 16;
  40979. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40980. break;
  40981. case FOURCC_DXT5:
  40982. blockBytes = 16;
  40983. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40984. break;
  40985. default:
  40986. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40987. return;
  40988. }
  40989. }
  40990. mipmapCount = 1;
  40991. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40992. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40993. }
  40994. var bpp = header[off_RGBbpp];
  40995. for (var face = 0; face < faces; face++) {
  40996. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40997. width = header[off_width];
  40998. height = header[off_height];
  40999. dataOffset = header[off_size] + 4;
  41000. for (i = 0; i < mipmapCount; ++i) {
  41001. if (info.isRGB) {
  41002. if (bpp === 24) {
  41003. dataLength = width * height * 3;
  41004. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41005. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41006. }
  41007. else {
  41008. dataLength = width * height * 4;
  41009. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41010. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41011. }
  41012. }
  41013. else if (info.isLuminance) {
  41014. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41015. var unpaddedRowSize = width;
  41016. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41017. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41018. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41019. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41020. }
  41021. else {
  41022. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41023. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41024. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41025. }
  41026. dataOffset += dataLength;
  41027. width *= 0.5;
  41028. height *= 0.5;
  41029. width = Math.max(1.0, width);
  41030. height = Math.max(1.0, height);
  41031. }
  41032. }
  41033. };
  41034. return DDSTools;
  41035. }());
  41036. Internals.DDSTools = DDSTools;
  41037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41038. })(BABYLON || (BABYLON = {}));
  41039. //# sourceMappingURL=babylon.tools.dds.js.map
  41040. var BABYLON;
  41041. (function (BABYLON) {
  41042. var CannonJSPlugin = (function () {
  41043. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41044. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41045. if (iterations === void 0) { iterations = 10; }
  41046. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41047. this.name = "CannonJSPlugin";
  41048. this._physicsMaterials = [];
  41049. this._fixedTimeStep = 1 / 60;
  41050. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41051. this._currentCollisionGroup = 2;
  41052. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41053. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41054. this._tmpPosition = BABYLON.Vector3.Zero();
  41055. this._tmpQuaternion = new BABYLON.Quaternion();
  41056. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41057. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41058. this._tmpUnityRotation = new BABYLON.Quaternion();
  41059. if (!this.isSupported()) {
  41060. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41061. return;
  41062. }
  41063. this.world = new CANNON.World();
  41064. this.world.broadphase = new CANNON.NaiveBroadphase();
  41065. this.world.solver.iterations = iterations;
  41066. }
  41067. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41068. this.world.gravity.copy(gravity);
  41069. };
  41070. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41071. this._fixedTimeStep = timeStep;
  41072. };
  41073. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41074. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41075. };
  41076. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41077. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41078. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41079. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41080. };
  41081. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41082. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41083. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41084. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41085. };
  41086. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41087. //parent-child relationship. Does this impostor has a parent impostor?
  41088. if (impostor.parent) {
  41089. if (impostor.physicsBody) {
  41090. this.removePhysicsBody(impostor);
  41091. //TODO is that needed?
  41092. impostor.forceUpdate();
  41093. }
  41094. return;
  41095. }
  41096. //should a new body be created for this impostor?
  41097. if (impostor.isBodyInitRequired()) {
  41098. var shape = this._createShape(impostor);
  41099. //unregister events, if body is being changed
  41100. var oldBody = impostor.physicsBody;
  41101. if (oldBody) {
  41102. this.removePhysicsBody(impostor);
  41103. }
  41104. //create the body and material
  41105. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41106. var bodyCreationObject = {
  41107. mass: impostor.getParam("mass"),
  41108. material: material
  41109. };
  41110. // A simple extend, in case native options were used.
  41111. var nativeOptions = impostor.getParam("nativeOptions");
  41112. for (var key in nativeOptions) {
  41113. if (nativeOptions.hasOwnProperty(key)) {
  41114. bodyCreationObject[key] = nativeOptions[key];
  41115. }
  41116. }
  41117. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41118. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41119. this.world.addEventListener("preStep", impostor.beforeStep);
  41120. this.world.addEventListener("postStep", impostor.afterStep);
  41121. impostor.physicsBody.addShape(shape);
  41122. this.world.add(impostor.physicsBody);
  41123. //try to keep the body moving in the right direction by taking old properties.
  41124. //Should be tested!
  41125. if (oldBody) {
  41126. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41127. impostor.physicsBody[param].copy(oldBody[param]);
  41128. });
  41129. }
  41130. this._processChildMeshes(impostor);
  41131. }
  41132. //now update the body's transformation
  41133. this._updatePhysicsBodyTransformation(impostor);
  41134. };
  41135. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41136. var _this = this;
  41137. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41138. if (meshChildren.length) {
  41139. var processMesh = function (localPosition, mesh) {
  41140. var childImpostor = mesh.getPhysicsImpostor();
  41141. if (childImpostor) {
  41142. var parent = childImpostor.parent;
  41143. if (parent !== mainImpostor) {
  41144. var localPosition = mesh.position;
  41145. if (childImpostor.physicsBody) {
  41146. _this.removePhysicsBody(childImpostor);
  41147. childImpostor.physicsBody = null;
  41148. }
  41149. childImpostor.parent = mainImpostor;
  41150. childImpostor.resetUpdateFlags();
  41151. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41152. //Add the mass of the children.
  41153. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41154. }
  41155. }
  41156. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41157. };
  41158. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41159. }
  41160. };
  41161. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41162. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41163. this.world.removeEventListener("preStep", impostor.beforeStep);
  41164. this.world.removeEventListener("postStep", impostor.afterStep);
  41165. this.world.remove(impostor.physicsBody);
  41166. };
  41167. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41168. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41169. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41170. if (!mainBody || !connectedBody) {
  41171. return;
  41172. }
  41173. var constraint;
  41174. var jointData = impostorJoint.joint.jointData;
  41175. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41176. var constraintData = {
  41177. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41178. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41179. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41180. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41181. maxForce: jointData.nativeParams.maxForce,
  41182. collideConnected: !!jointData.collision
  41183. };
  41184. //Not needed, Cannon has a collideConnected flag
  41185. /*if (!jointData.collision) {
  41186. //add 1st body to a collision group of its own, if it is not in 1
  41187. if (mainBody.collisionFilterGroup === 1) {
  41188. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41189. this._currentCollisionGroup <<= 1;
  41190. }
  41191. if (connectedBody.collisionFilterGroup === 1) {
  41192. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41193. this._currentCollisionGroup <<= 1;
  41194. }
  41195. //add their mask to the collisionFilterMask of each other:
  41196. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41197. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41198. }*/
  41199. switch (impostorJoint.joint.type) {
  41200. case BABYLON.PhysicsJoint.HingeJoint:
  41201. case BABYLON.PhysicsJoint.Hinge2Joint:
  41202. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41203. break;
  41204. case BABYLON.PhysicsJoint.DistanceJoint:
  41205. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41206. break;
  41207. case BABYLON.PhysicsJoint.SpringJoint:
  41208. var springData = jointData;
  41209. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41210. restLength: springData.length,
  41211. stiffness: springData.stiffness,
  41212. damping: springData.damping,
  41213. localAnchorA: constraintData.pivotA,
  41214. localAnchorB: constraintData.pivotB
  41215. });
  41216. break;
  41217. case BABYLON.PhysicsJoint.LockJoint:
  41218. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41219. break;
  41220. case BABYLON.PhysicsJoint.PointToPointJoint:
  41221. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41222. default:
  41223. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41224. break;
  41225. }
  41226. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41227. constraint.collideConnected = !!jointData.collision;
  41228. impostorJoint.joint.physicsJoint = constraint;
  41229. //don't add spring as constraint, as it is not one.
  41230. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41231. this.world.addConstraint(constraint);
  41232. }
  41233. else {
  41234. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41235. constraint.applyForce();
  41236. });
  41237. }
  41238. };
  41239. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41240. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41241. };
  41242. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41243. var index;
  41244. var mat;
  41245. for (index = 0; index < this._physicsMaterials.length; index++) {
  41246. mat = this._physicsMaterials[index];
  41247. if (mat.friction === friction && mat.restitution === restitution) {
  41248. return mat;
  41249. }
  41250. }
  41251. var currentMat = new CANNON.Material(name);
  41252. currentMat.friction = friction;
  41253. currentMat.restitution = restitution;
  41254. this._physicsMaterials.push(currentMat);
  41255. return currentMat;
  41256. };
  41257. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41258. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41259. };
  41260. CannonJSPlugin.prototype._createShape = function (impostor) {
  41261. var object = impostor.object;
  41262. var returnValue;
  41263. var extendSize = impostor.getObjectExtendSize();
  41264. switch (impostor.type) {
  41265. case BABYLON.PhysicsEngine.SphereImpostor:
  41266. var radiusX = extendSize.x;
  41267. var radiusY = extendSize.y;
  41268. var radiusZ = extendSize.z;
  41269. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41270. break;
  41271. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41272. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41273. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41274. break;
  41275. case BABYLON.PhysicsImpostor.BoxImpostor:
  41276. var box = extendSize.scale(0.5);
  41277. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41278. break;
  41279. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41280. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41281. returnValue = new CANNON.Plane();
  41282. break;
  41283. case BABYLON.PhysicsImpostor.MeshImpostor:
  41284. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41285. var rawFaces = object.getIndices ? object.getIndices() : [];
  41286. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41287. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41288. break;
  41289. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41290. returnValue = this._createHeightmap(object);
  41291. break;
  41292. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41293. returnValue = new CANNON.Particle();
  41294. break;
  41295. }
  41296. return returnValue;
  41297. };
  41298. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41299. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41300. var matrix = [];
  41301. //For now pointDepth will not be used and will be automatically calculated.
  41302. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41303. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41304. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41305. var elementSize = dim * 2 / arraySize;
  41306. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41307. for (var i = 0; i < pos.length; i = i + 3) {
  41308. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41309. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41310. var y = pos[i + 1] + minY;
  41311. if (!matrix[x]) {
  41312. matrix[x] = [];
  41313. }
  41314. if (!matrix[x][z]) {
  41315. matrix[x][z] = y;
  41316. }
  41317. matrix[x][z] = Math.max(y, matrix[x][z]);
  41318. }
  41319. for (var x = 0; x <= arraySize; ++x) {
  41320. if (!matrix[x]) {
  41321. var loc = 1;
  41322. while (!matrix[(x + loc) % arraySize]) {
  41323. loc++;
  41324. }
  41325. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41326. }
  41327. for (var z = 0; z <= arraySize; ++z) {
  41328. if (!matrix[x][z]) {
  41329. var loc = 1;
  41330. var newValue;
  41331. while (newValue === undefined) {
  41332. newValue = matrix[x][(z + loc++) % arraySize];
  41333. }
  41334. matrix[x][z] = newValue;
  41335. }
  41336. }
  41337. }
  41338. var shape = new CANNON.Heightfield(matrix, {
  41339. elementSize: elementSize
  41340. });
  41341. //For future reference, needed for body transformation
  41342. shape.minY = minY;
  41343. return shape;
  41344. };
  41345. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41346. var object = impostor.object;
  41347. //make sure it is updated...
  41348. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41349. // The delta between the mesh position and the mesh bounding box center
  41350. var center = impostor.getObjectCenter();
  41351. var extendSize = impostor.getObjectExtendSize();
  41352. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41353. this._tmpPosition.copyFrom(center);
  41354. var quaternion = object.rotationQuaternion;
  41355. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41356. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41357. //-90 DEG in X, precalculated
  41358. quaternion = quaternion.multiply(this._minus90X);
  41359. //Invert! (Precalculated, 90 deg in X)
  41360. //No need to clone. this will never change.
  41361. impostor.setDeltaRotation(this._plus90X);
  41362. }
  41363. //If it is a heightfield, if should be centered.
  41364. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41365. var mesh = object;
  41366. //calculate the correct body position:
  41367. var rotationQuaternion = mesh.rotationQuaternion;
  41368. mesh.rotationQuaternion = this._tmpUnityRotation;
  41369. mesh.computeWorldMatrix(true);
  41370. //get original center with no rotation
  41371. var c = center.clone();
  41372. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41373. //rotation is back
  41374. mesh.rotationQuaternion = rotationQuaternion;
  41375. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41376. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41377. mesh.setPivotMatrix(p);
  41378. mesh.computeWorldMatrix(true);
  41379. //calculate the translation
  41380. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41381. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41382. //add it inverted to the delta
  41383. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41384. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41385. mesh.setPivotMatrix(oldPivot);
  41386. mesh.computeWorldMatrix(true);
  41387. }
  41388. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41389. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41390. this._tmpPosition.copyFrom(object.position);
  41391. }
  41392. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41393. //Now update the impostor object
  41394. impostor.physicsBody.position.copy(this._tmpPosition);
  41395. impostor.physicsBody.quaternion.copy(quaternion);
  41396. };
  41397. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41398. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41399. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41400. };
  41401. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41402. impostor.physicsBody.position.copy(newPosition);
  41403. impostor.physicsBody.quaternion.copy(newRotation);
  41404. };
  41405. CannonJSPlugin.prototype.isSupported = function () {
  41406. return window.CANNON !== undefined;
  41407. };
  41408. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41409. impostor.physicsBody.velocity.copy(velocity);
  41410. };
  41411. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41412. impostor.physicsBody.angularVelocity.copy(velocity);
  41413. };
  41414. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41415. var v = impostor.physicsBody.velocity;
  41416. if (!v)
  41417. return null;
  41418. return new BABYLON.Vector3(v.x, v.y, v.z);
  41419. };
  41420. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41421. var v = impostor.physicsBody.angularVelocity;
  41422. if (!v)
  41423. return null;
  41424. return new BABYLON.Vector3(v.x, v.y, v.z);
  41425. };
  41426. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41427. impostor.physicsBody.mass = mass;
  41428. impostor.physicsBody.updateMassProperties();
  41429. };
  41430. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41431. impostor.physicsBody.sleep();
  41432. };
  41433. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41434. impostor.physicsBody.wakeUp();
  41435. };
  41436. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41437. joint.physicsJoint.distance = maxDistance;
  41438. };
  41439. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41440. if (!motorIndex) {
  41441. joint.physicsJoint.enableMotor();
  41442. }
  41443. };
  41444. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41445. if (!motorIndex) {
  41446. joint.physicsJoint.disableMotor();
  41447. }
  41448. };
  41449. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41450. if (!motorIndex) {
  41451. joint.physicsJoint.enableMotor();
  41452. joint.physicsJoint.setMotorSpeed(speed);
  41453. if (maxForce) {
  41454. this.setLimit(joint, maxForce);
  41455. }
  41456. }
  41457. };
  41458. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41459. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41460. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41461. };
  41462. CannonJSPlugin.prototype.dispose = function () {
  41463. //nothing to do, actually.
  41464. };
  41465. return CannonJSPlugin;
  41466. }());
  41467. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41468. })(BABYLON || (BABYLON = {}));
  41469. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41470. var BABYLON;
  41471. (function (BABYLON) {
  41472. var OimoJSPlugin = (function () {
  41473. function OimoJSPlugin(iterations) {
  41474. this.name = "OimoJSPlugin";
  41475. this._tmpImpostorsArray = [];
  41476. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41477. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41478. this.world.worldscale(1);
  41479. this.world.clear();
  41480. //making sure no stats are calculated
  41481. this.world.isNoStat = true;
  41482. }
  41483. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41484. this.world.gravity.copy(gravity);
  41485. };
  41486. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41487. this.world.timeStep = timeStep;
  41488. };
  41489. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41490. var _this = this;
  41491. impostors.forEach(function (impostor) {
  41492. impostor.beforeStep();
  41493. });
  41494. this.world.step();
  41495. impostors.forEach(function (impostor) {
  41496. impostor.afterStep();
  41497. //update the ordered impostors array
  41498. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41499. });
  41500. //check for collisions
  41501. var contact = this.world.contacts;
  41502. while (contact !== null) {
  41503. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41504. contact = contact.next;
  41505. continue;
  41506. }
  41507. //is this body colliding with any other? get the impostor
  41508. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41509. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41510. if (!mainImpostor || !collidingImpostor) {
  41511. contact = contact.next;
  41512. continue;
  41513. }
  41514. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41515. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41516. contact = contact.next;
  41517. }
  41518. };
  41519. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41520. var mass = impostor.physicsBody.massInfo.mass;
  41521. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41522. };
  41523. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41524. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41525. this.applyImpulse(impostor, force, contactPoint);
  41526. };
  41527. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41528. var _this = this;
  41529. //parent-child relationship. Does this impostor has a parent impostor?
  41530. if (impostor.parent) {
  41531. if (impostor.physicsBody) {
  41532. this.removePhysicsBody(impostor);
  41533. //TODO is that needed?
  41534. impostor.forceUpdate();
  41535. }
  41536. return;
  41537. }
  41538. if (impostor.isBodyInitRequired()) {
  41539. var bodyConfig = {
  41540. name: impostor.uniqueId,
  41541. //Oimo must have mass, also for static objects.
  41542. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41543. size: [],
  41544. type: [],
  41545. pos: [],
  41546. rot: [],
  41547. move: impostor.getParam("mass") !== 0,
  41548. //Supporting older versions of Oimo
  41549. world: this.world
  41550. };
  41551. var impostors = [impostor];
  41552. var addToArray = function (parent) {
  41553. if (!parent.getChildMeshes)
  41554. return;
  41555. parent.getChildMeshes().forEach(function (m) {
  41556. if (m.physicsImpostor) {
  41557. impostors.push(m.physicsImpostor);
  41558. m.physicsImpostor._init();
  41559. }
  41560. });
  41561. };
  41562. addToArray(impostor.object);
  41563. var checkWithEpsilon_1 = function (value) {
  41564. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41565. };
  41566. impostors.forEach(function (i) {
  41567. //get the correct bounding box
  41568. var oldQuaternion = i.object.rotationQuaternion;
  41569. var rot = new OIMO.Euler().setFromQuaternion({
  41570. x: impostor.object.rotationQuaternion.x,
  41571. y: impostor.object.rotationQuaternion.y,
  41572. z: impostor.object.rotationQuaternion.z,
  41573. s: impostor.object.rotationQuaternion.w
  41574. });
  41575. var extendSize = i.getObjectExtendSize();
  41576. if (i === impostor) {
  41577. var center = impostor.getObjectCenter();
  41578. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41579. //Can also use Array.prototype.push.apply
  41580. bodyConfig.pos.push(center.x);
  41581. bodyConfig.pos.push(center.y);
  41582. bodyConfig.pos.push(center.z);
  41583. //tmp solution
  41584. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41585. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41586. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41587. }
  41588. else {
  41589. bodyConfig.pos.push(i.object.position.x);
  41590. bodyConfig.pos.push(i.object.position.y);
  41591. bodyConfig.pos.push(i.object.position.z);
  41592. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41593. bodyConfig.rot.push(0);
  41594. bodyConfig.rot.push(0);
  41595. bodyConfig.rot.push(0);
  41596. }
  41597. // register mesh
  41598. switch (i.type) {
  41599. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41600. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41601. case BABYLON.PhysicsImpostor.SphereImpostor:
  41602. var radiusX = extendSize.x;
  41603. var radiusY = extendSize.y;
  41604. var radiusZ = extendSize.z;
  41605. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41606. bodyConfig.type.push('sphere');
  41607. //due to the way oimo works with compounds, add 3 times
  41608. bodyConfig.size.push(size);
  41609. bodyConfig.size.push(size);
  41610. bodyConfig.size.push(size);
  41611. break;
  41612. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41613. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41614. var sizeY = checkWithEpsilon_1(extendSize.y);
  41615. bodyConfig.type.push('cylinder');
  41616. bodyConfig.size.push(sizeX);
  41617. bodyConfig.size.push(sizeY);
  41618. //due to the way oimo works with compounds, add one more value.
  41619. bodyConfig.size.push(sizeY);
  41620. break;
  41621. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41622. case BABYLON.PhysicsImpostor.BoxImpostor:
  41623. default:
  41624. var sizeX = checkWithEpsilon_1(extendSize.x);
  41625. var sizeY = checkWithEpsilon_1(extendSize.y);
  41626. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41627. bodyConfig.type.push('box');
  41628. bodyConfig.size.push(sizeX);
  41629. bodyConfig.size.push(sizeY);
  41630. bodyConfig.size.push(sizeZ);
  41631. break;
  41632. }
  41633. //actually not needed, but hey...
  41634. i.object.rotationQuaternion = oldQuaternion;
  41635. });
  41636. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41637. }
  41638. else {
  41639. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41640. }
  41641. impostor.setDeltaPosition(this._tmpPositionVector);
  41642. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41643. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41644. };
  41645. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41646. //impostor.physicsBody.dispose();
  41647. //Same as : (older oimo versions)
  41648. this.world.removeRigidBody(impostor.physicsBody);
  41649. };
  41650. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41651. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41652. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41653. if (!mainBody || !connectedBody) {
  41654. return;
  41655. }
  41656. var jointData = impostorJoint.joint.jointData;
  41657. var options = jointData.nativeParams || {};
  41658. var type;
  41659. var nativeJointData = {
  41660. body1: mainBody,
  41661. body2: connectedBody,
  41662. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41663. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41664. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41665. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41666. min: options.min,
  41667. max: options.max,
  41668. collision: options.collision || jointData.collision,
  41669. spring: options.spring,
  41670. //supporting older version of Oimo
  41671. world: this.world
  41672. };
  41673. switch (impostorJoint.joint.type) {
  41674. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41675. type = "jointBall";
  41676. break;
  41677. case BABYLON.PhysicsJoint.SpringJoint:
  41678. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41679. var springData = jointData;
  41680. nativeJointData.min = springData.length || nativeJointData.min;
  41681. //Max should also be set, just make sure it is at least min
  41682. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41683. case BABYLON.PhysicsJoint.DistanceJoint:
  41684. type = "jointDistance";
  41685. nativeJointData.max = jointData.maxDistance;
  41686. break;
  41687. case BABYLON.PhysicsJoint.PrismaticJoint:
  41688. type = "jointPrisme";
  41689. break;
  41690. case BABYLON.PhysicsJoint.SliderJoint:
  41691. type = "jointSlide";
  41692. break;
  41693. case BABYLON.PhysicsJoint.WheelJoint:
  41694. type = "jointWheel";
  41695. break;
  41696. case BABYLON.PhysicsJoint.HingeJoint:
  41697. default:
  41698. type = "jointHinge";
  41699. break;
  41700. }
  41701. nativeJointData.type = type;
  41702. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41703. };
  41704. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41705. //Bug in Oimo prevents us from disposing a joint in the playground
  41706. //joint.joint.physicsJoint.dispose();
  41707. //So we will bruteforce it!
  41708. try {
  41709. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41710. }
  41711. catch (e) {
  41712. BABYLON.Tools.Warn(e);
  41713. }
  41714. };
  41715. OimoJSPlugin.prototype.isSupported = function () {
  41716. return OIMO !== undefined;
  41717. };
  41718. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41719. if (!impostor.physicsBody.sleeping) {
  41720. //TODO check that
  41721. if (impostor.physicsBody.shapes.next) {
  41722. var parentShape = this._getLastShape(impostor.physicsBody);
  41723. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41724. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41725. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41726. }
  41727. else {
  41728. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41729. }
  41730. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41731. impostor.object.rotationQuaternion.normalize();
  41732. }
  41733. };
  41734. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41735. var body = impostor.physicsBody;
  41736. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41737. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41738. body.syncShapes();
  41739. body.awake();
  41740. };
  41741. OimoJSPlugin.prototype._getLastShape = function (body) {
  41742. var lastShape = body.shapes;
  41743. while (lastShape.next) {
  41744. lastShape = lastShape.next;
  41745. }
  41746. return lastShape;
  41747. };
  41748. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41749. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41750. };
  41751. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41752. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41753. };
  41754. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41755. var v = impostor.physicsBody.linearVelocity;
  41756. if (!v)
  41757. return null;
  41758. return new BABYLON.Vector3(v.x, v.y, v.z);
  41759. };
  41760. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41761. var v = impostor.physicsBody.angularVelocity;
  41762. if (!v)
  41763. return null;
  41764. return new BABYLON.Vector3(v.x, v.y, v.z);
  41765. };
  41766. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41767. var staticBody = mass === 0;
  41768. //this will actually set the body's density and not its mass.
  41769. //But this is how oimo treats the mass variable.
  41770. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41771. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41772. };
  41773. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41774. impostor.physicsBody.sleep();
  41775. };
  41776. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41777. impostor.physicsBody.awake();
  41778. };
  41779. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41780. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41781. if (minDistance !== void 0) {
  41782. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41783. }
  41784. };
  41785. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41786. //TODO separate rotational and transational motors.
  41787. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41788. if (motor) {
  41789. motor.setMotor(speed, maxForce);
  41790. }
  41791. };
  41792. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41793. //TODO separate rotational and transational motors.
  41794. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41795. if (motor) {
  41796. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41797. }
  41798. };
  41799. OimoJSPlugin.prototype.dispose = function () {
  41800. this.world.clear();
  41801. };
  41802. return OimoJSPlugin;
  41803. }());
  41804. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41805. })(BABYLON || (BABYLON = {}));
  41806. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41807. var BABYLON;
  41808. (function (BABYLON) {
  41809. var DisplayPassPostProcess = (function (_super) {
  41810. __extends(DisplayPassPostProcess, _super);
  41811. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41812. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  41813. }
  41814. return DisplayPassPostProcess;
  41815. }(BABYLON.PostProcess));
  41816. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41817. })(BABYLON || (BABYLON = {}));
  41818. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41819. var BABYLON;
  41820. (function (BABYLON) {
  41821. var SimplificationSettings = (function () {
  41822. function SimplificationSettings(quality, distance, optimizeMesh) {
  41823. this.quality = quality;
  41824. this.distance = distance;
  41825. this.optimizeMesh = optimizeMesh;
  41826. }
  41827. return SimplificationSettings;
  41828. }());
  41829. BABYLON.SimplificationSettings = SimplificationSettings;
  41830. var SimplificationQueue = (function () {
  41831. function SimplificationQueue() {
  41832. this.running = false;
  41833. this._simplificationArray = [];
  41834. }
  41835. SimplificationQueue.prototype.addTask = function (task) {
  41836. this._simplificationArray.push(task);
  41837. };
  41838. SimplificationQueue.prototype.executeNext = function () {
  41839. var task = this._simplificationArray.pop();
  41840. if (task) {
  41841. this.running = true;
  41842. this.runSimplification(task);
  41843. }
  41844. else {
  41845. this.running = false;
  41846. }
  41847. };
  41848. SimplificationQueue.prototype.runSimplification = function (task) {
  41849. var _this = this;
  41850. if (task.parallelProcessing) {
  41851. //parallel simplifier
  41852. task.settings.forEach(function (setting) {
  41853. var simplifier = _this.getSimplifier(task);
  41854. simplifier.simplify(setting, function (newMesh) {
  41855. task.mesh.addLODLevel(setting.distance, newMesh);
  41856. newMesh.isVisible = true;
  41857. //check if it is the last
  41858. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41859. //all done, run the success callback.
  41860. task.successCallback();
  41861. }
  41862. _this.executeNext();
  41863. });
  41864. });
  41865. }
  41866. else {
  41867. //single simplifier.
  41868. var simplifier = this.getSimplifier(task);
  41869. var runDecimation = function (setting, callback) {
  41870. simplifier.simplify(setting, function (newMesh) {
  41871. task.mesh.addLODLevel(setting.distance, newMesh);
  41872. newMesh.isVisible = true;
  41873. //run the next quality level
  41874. callback();
  41875. });
  41876. };
  41877. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41878. runDecimation(task.settings[loop.index], function () {
  41879. loop.executeNext();
  41880. });
  41881. }, function () {
  41882. //execution ended, run the success callback.
  41883. if (task.successCallback) {
  41884. task.successCallback();
  41885. }
  41886. _this.executeNext();
  41887. });
  41888. }
  41889. };
  41890. SimplificationQueue.prototype.getSimplifier = function (task) {
  41891. switch (task.simplificationType) {
  41892. case SimplificationType.QUADRATIC:
  41893. default:
  41894. return new QuadraticErrorSimplification(task.mesh);
  41895. }
  41896. };
  41897. return SimplificationQueue;
  41898. }());
  41899. BABYLON.SimplificationQueue = SimplificationQueue;
  41900. /**
  41901. * The implemented types of simplification.
  41902. * At the moment only Quadratic Error Decimation is implemented.
  41903. */
  41904. (function (SimplificationType) {
  41905. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41906. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41907. var SimplificationType = BABYLON.SimplificationType;
  41908. var DecimationTriangle = (function () {
  41909. function DecimationTriangle(vertices) {
  41910. this.vertices = vertices;
  41911. this.error = new Array(4);
  41912. this.deleted = false;
  41913. this.isDirty = false;
  41914. this.deletePending = false;
  41915. this.borderFactor = 0;
  41916. }
  41917. return DecimationTriangle;
  41918. }());
  41919. BABYLON.DecimationTriangle = DecimationTriangle;
  41920. var DecimationVertex = (function () {
  41921. function DecimationVertex(position, id) {
  41922. this.position = position;
  41923. this.id = id;
  41924. this.isBorder = true;
  41925. this.q = new QuadraticMatrix();
  41926. this.triangleCount = 0;
  41927. this.triangleStart = 0;
  41928. this.originalOffsets = [];
  41929. }
  41930. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41931. this.position.copyFrom(newPosition);
  41932. };
  41933. return DecimationVertex;
  41934. }());
  41935. BABYLON.DecimationVertex = DecimationVertex;
  41936. var QuadraticMatrix = (function () {
  41937. function QuadraticMatrix(data) {
  41938. this.data = new Array(10);
  41939. for (var i = 0; i < 10; ++i) {
  41940. if (data && data[i]) {
  41941. this.data[i] = data[i];
  41942. }
  41943. else {
  41944. this.data[i] = 0;
  41945. }
  41946. }
  41947. }
  41948. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41949. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41950. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41951. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41952. return det;
  41953. };
  41954. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41955. for (var i = 0; i < 10; ++i) {
  41956. this.data[i] += matrix.data[i];
  41957. }
  41958. };
  41959. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41960. for (var i = 0; i < 10; ++i) {
  41961. this.data[i] += data[i];
  41962. }
  41963. };
  41964. QuadraticMatrix.prototype.add = function (matrix) {
  41965. var m = new QuadraticMatrix();
  41966. for (var i = 0; i < 10; ++i) {
  41967. m.data[i] = this.data[i] + matrix.data[i];
  41968. }
  41969. return m;
  41970. };
  41971. QuadraticMatrix.FromData = function (a, b, c, d) {
  41972. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41973. };
  41974. //returning an array to avoid garbage collection
  41975. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41976. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41977. };
  41978. return QuadraticMatrix;
  41979. }());
  41980. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41981. var Reference = (function () {
  41982. function Reference(vertexId, triangleId) {
  41983. this.vertexId = vertexId;
  41984. this.triangleId = triangleId;
  41985. }
  41986. return Reference;
  41987. }());
  41988. BABYLON.Reference = Reference;
  41989. /**
  41990. * An implementation of the Quadratic Error simplification algorithm.
  41991. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41992. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41993. * @author RaananW
  41994. */
  41995. var QuadraticErrorSimplification = (function () {
  41996. function QuadraticErrorSimplification(_mesh) {
  41997. this._mesh = _mesh;
  41998. this.initialized = false;
  41999. this.syncIterations = 5000;
  42000. this.aggressiveness = 7;
  42001. this.decimationIterations = 100;
  42002. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42003. }
  42004. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42005. var _this = this;
  42006. this.initDecimatedMesh();
  42007. //iterating through the submeshes array, one after the other.
  42008. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42009. _this.initWithMesh(loop.index, function () {
  42010. _this.runDecimation(settings, loop.index, function () {
  42011. loop.executeNext();
  42012. });
  42013. }, settings.optimizeMesh);
  42014. }, function () {
  42015. setTimeout(function () {
  42016. successCallback(_this._reconstructedMesh);
  42017. }, 0);
  42018. });
  42019. };
  42020. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42021. var _this = this;
  42022. var gCount = 0;
  42023. triangle.vertices.forEach(function (vertex) {
  42024. var count = 0;
  42025. var vPos = vertex.position;
  42026. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42027. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42028. ++count;
  42029. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42030. ++count;
  42031. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42032. ++count;
  42033. if (count > 1) {
  42034. ++gCount;
  42035. }
  42036. ;
  42037. });
  42038. if (gCount > 1) {
  42039. console.log(triangle, gCount);
  42040. }
  42041. return gCount > 1;
  42042. };
  42043. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42044. var _this = this;
  42045. var targetCount = ~~(this.triangles.length * settings.quality);
  42046. var deletedTriangles = 0;
  42047. var triangleCount = this.triangles.length;
  42048. var iterationFunction = function (iteration, callback) {
  42049. setTimeout(function () {
  42050. if (iteration % 5 === 0) {
  42051. _this.updateMesh(iteration === 0);
  42052. }
  42053. for (var i = 0; i < _this.triangles.length; ++i) {
  42054. _this.triangles[i].isDirty = false;
  42055. }
  42056. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42057. var trianglesIterator = function (i) {
  42058. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42059. var t = _this.triangles[tIdx];
  42060. if (!t)
  42061. return;
  42062. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42063. return;
  42064. }
  42065. for (var j = 0; j < 3; ++j) {
  42066. if (t.error[j] < threshold) {
  42067. var deleted0 = [];
  42068. var deleted1 = [];
  42069. var v0 = t.vertices[j];
  42070. var v1 = t.vertices[(j + 1) % 3];
  42071. if (v0.isBorder || v1.isBorder)
  42072. continue;
  42073. var p = BABYLON.Vector3.Zero();
  42074. var n = BABYLON.Vector3.Zero();
  42075. var uv = BABYLON.Vector2.Zero();
  42076. var color = new BABYLON.Color4(0, 0, 0, 1);
  42077. _this.calculateError(v0, v1, p, n, uv, color);
  42078. var delTr = [];
  42079. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42080. continue;
  42081. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42082. continue;
  42083. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42084. continue;
  42085. var uniqueArray = [];
  42086. delTr.forEach(function (deletedT) {
  42087. if (uniqueArray.indexOf(deletedT) === -1) {
  42088. deletedT.deletePending = true;
  42089. uniqueArray.push(deletedT);
  42090. }
  42091. });
  42092. if (uniqueArray.length % 2 !== 0) {
  42093. continue;
  42094. }
  42095. v0.q = v1.q.add(v0.q);
  42096. v0.updatePosition(p);
  42097. var tStart = _this.references.length;
  42098. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42099. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42100. var tCount = _this.references.length - tStart;
  42101. if (tCount <= v0.triangleCount) {
  42102. if (tCount) {
  42103. for (var c = 0; c < tCount; c++) {
  42104. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42105. }
  42106. }
  42107. }
  42108. else {
  42109. v0.triangleStart = tStart;
  42110. }
  42111. v0.triangleCount = tCount;
  42112. break;
  42113. }
  42114. }
  42115. };
  42116. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42117. }, 0);
  42118. };
  42119. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42120. if (triangleCount - deletedTriangles <= targetCount)
  42121. loop.breakLoop();
  42122. else {
  42123. iterationFunction(loop.index, function () {
  42124. loop.executeNext();
  42125. });
  42126. }
  42127. }, function () {
  42128. setTimeout(function () {
  42129. //reconstruct this part of the mesh
  42130. _this.reconstructMesh(submeshIndex);
  42131. successCallback();
  42132. }, 0);
  42133. });
  42134. };
  42135. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42136. var _this = this;
  42137. this.vertices = [];
  42138. this.triangles = [];
  42139. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42140. var indices = this._mesh.getIndices();
  42141. var submesh = this._mesh.subMeshes[submeshIndex];
  42142. var findInVertices = function (positionToSearch) {
  42143. if (optimizeMesh) {
  42144. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42145. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42146. return _this.vertices[ii];
  42147. }
  42148. }
  42149. }
  42150. return null;
  42151. };
  42152. var vertexReferences = [];
  42153. var vertexInit = function (i) {
  42154. var offset = i + submesh.verticesStart;
  42155. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42156. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42157. vertex.originalOffsets.push(offset);
  42158. if (vertex.id === _this.vertices.length) {
  42159. _this.vertices.push(vertex);
  42160. }
  42161. vertexReferences.push(vertex.id);
  42162. };
  42163. //var totalVertices = mesh.getTotalVertices();
  42164. var totalVertices = submesh.verticesCount;
  42165. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42166. var indicesInit = function (i) {
  42167. var offset = (submesh.indexStart / 3) + i;
  42168. var pos = (offset * 3);
  42169. var i0 = indices[pos + 0];
  42170. var i1 = indices[pos + 1];
  42171. var i2 = indices[pos + 2];
  42172. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42173. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42174. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42175. var triangle = new DecimationTriangle([v0, v1, v2]);
  42176. triangle.originalOffset = pos;
  42177. _this.triangles.push(triangle);
  42178. };
  42179. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42180. _this.init(callback);
  42181. });
  42182. });
  42183. };
  42184. QuadraticErrorSimplification.prototype.init = function (callback) {
  42185. var _this = this;
  42186. var triangleInit1 = function (i) {
  42187. var t = _this.triangles[i];
  42188. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42189. for (var j = 0; j < 3; j++) {
  42190. 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))));
  42191. }
  42192. };
  42193. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42194. var triangleInit2 = function (i) {
  42195. var t = _this.triangles[i];
  42196. for (var j = 0; j < 3; ++j) {
  42197. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42198. }
  42199. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42200. };
  42201. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42202. _this.initialized = true;
  42203. callback();
  42204. });
  42205. });
  42206. };
  42207. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42208. var newTriangles = [];
  42209. var i;
  42210. for (i = 0; i < this.vertices.length; ++i) {
  42211. this.vertices[i].triangleCount = 0;
  42212. }
  42213. var t;
  42214. var j;
  42215. for (i = 0; i < this.triangles.length; ++i) {
  42216. if (!this.triangles[i].deleted) {
  42217. t = this.triangles[i];
  42218. for (j = 0; j < 3; ++j) {
  42219. t.vertices[j].triangleCount = 1;
  42220. }
  42221. newTriangles.push(t);
  42222. }
  42223. }
  42224. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42225. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42226. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42227. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42228. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42229. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42230. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42231. var vertexCount = 0;
  42232. for (i = 0; i < this.vertices.length; ++i) {
  42233. var vertex = this.vertices[i];
  42234. vertex.id = vertexCount;
  42235. if (vertex.triangleCount) {
  42236. vertex.originalOffsets.forEach(function (originalOffset) {
  42237. newPositionData.push(vertex.position.x);
  42238. newPositionData.push(vertex.position.y);
  42239. newPositionData.push(vertex.position.z);
  42240. newNormalData.push(normalData[originalOffset * 3]);
  42241. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42242. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42243. if (uvs && uvs.length) {
  42244. newUVsData.push(uvs[(originalOffset * 2)]);
  42245. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42246. }
  42247. else if (colorsData && colorsData.length) {
  42248. newColorsData.push(colorsData[(originalOffset * 4)]);
  42249. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42250. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42251. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42252. }
  42253. ++vertexCount;
  42254. });
  42255. }
  42256. }
  42257. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42258. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42259. var submeshesArray = this._reconstructedMesh.subMeshes;
  42260. this._reconstructedMesh.subMeshes = [];
  42261. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42262. var originalIndices = this._mesh.getIndices();
  42263. for (i = 0; i < newTriangles.length; ++i) {
  42264. t = newTriangles[i]; //now get the new referencing point for each vertex
  42265. [0, 1, 2].forEach(function (idx) {
  42266. var id = originalIndices[t.originalOffset + idx];
  42267. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42268. if (offset < 0)
  42269. offset = 0;
  42270. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42271. });
  42272. }
  42273. //overwriting the old vertex buffers and indices.
  42274. this._reconstructedMesh.setIndices(newIndicesArray);
  42275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42276. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42277. if (newUVsData.length > 0)
  42278. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42279. if (newColorsData.length > 0)
  42280. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42281. //create submesh
  42282. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42283. if (submeshIndex > 0) {
  42284. this._reconstructedMesh.subMeshes = [];
  42285. submeshesArray.forEach(function (submesh) {
  42286. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42287. });
  42288. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42289. }
  42290. };
  42291. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42292. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42293. this._reconstructedMesh.material = this._mesh.material;
  42294. this._reconstructedMesh.parent = this._mesh.parent;
  42295. this._reconstructedMesh.isVisible = false;
  42296. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42297. };
  42298. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42299. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42300. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42301. if (t.deleted)
  42302. continue;
  42303. var s = this.references[vertex1.triangleStart + i].vertexId;
  42304. var v1 = t.vertices[(s + 1) % 3];
  42305. var v2 = t.vertices[(s + 2) % 3];
  42306. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42307. deletedArray[i] = true;
  42308. delTr.push(t);
  42309. continue;
  42310. }
  42311. var d1 = v1.position.subtract(point);
  42312. d1 = d1.normalize();
  42313. var d2 = v2.position.subtract(point);
  42314. d2 = d2.normalize();
  42315. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42316. return true;
  42317. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42318. deletedArray[i] = false;
  42319. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42320. return true;
  42321. }
  42322. return false;
  42323. };
  42324. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42325. var newDeleted = deletedTriangles;
  42326. for (var i = 0; i < vertex.triangleCount; ++i) {
  42327. var ref = this.references[vertex.triangleStart + i];
  42328. var t = this.triangles[ref.triangleId];
  42329. if (t.deleted)
  42330. continue;
  42331. if (deletedArray[i] && t.deletePending) {
  42332. t.deleted = true;
  42333. newDeleted++;
  42334. continue;
  42335. }
  42336. t.vertices[ref.vertexId] = origVertex;
  42337. t.isDirty = true;
  42338. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42339. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42340. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42341. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42342. this.references.push(ref);
  42343. }
  42344. return newDeleted;
  42345. };
  42346. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42347. for (var i = 0; i < this.vertices.length; ++i) {
  42348. var vCount = [];
  42349. var vId = [];
  42350. var v = this.vertices[i];
  42351. var j;
  42352. for (j = 0; j < v.triangleCount; ++j) {
  42353. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42354. for (var ii = 0; ii < 3; ii++) {
  42355. var ofs = 0;
  42356. var vv = triangle.vertices[ii];
  42357. while (ofs < vCount.length) {
  42358. if (vId[ofs] === vv.id)
  42359. break;
  42360. ++ofs;
  42361. }
  42362. if (ofs === vCount.length) {
  42363. vCount.push(1);
  42364. vId.push(vv.id);
  42365. }
  42366. else {
  42367. vCount[ofs]++;
  42368. }
  42369. }
  42370. }
  42371. for (j = 0; j < vCount.length; ++j) {
  42372. if (vCount[j] === 1) {
  42373. this.vertices[vId[j]].isBorder = true;
  42374. }
  42375. else {
  42376. this.vertices[vId[j]].isBorder = false;
  42377. }
  42378. }
  42379. }
  42380. };
  42381. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42382. if (identifyBorders === void 0) { identifyBorders = false; }
  42383. var i;
  42384. if (!identifyBorders) {
  42385. var newTrianglesVector = [];
  42386. for (i = 0; i < this.triangles.length; ++i) {
  42387. if (!this.triangles[i].deleted) {
  42388. newTrianglesVector.push(this.triangles[i]);
  42389. }
  42390. }
  42391. this.triangles = newTrianglesVector;
  42392. }
  42393. for (i = 0; i < this.vertices.length; ++i) {
  42394. this.vertices[i].triangleCount = 0;
  42395. this.vertices[i].triangleStart = 0;
  42396. }
  42397. var t;
  42398. var j;
  42399. var v;
  42400. for (i = 0; i < this.triangles.length; ++i) {
  42401. t = this.triangles[i];
  42402. for (j = 0; j < 3; ++j) {
  42403. v = t.vertices[j];
  42404. v.triangleCount++;
  42405. }
  42406. }
  42407. var tStart = 0;
  42408. for (i = 0; i < this.vertices.length; ++i) {
  42409. this.vertices[i].triangleStart = tStart;
  42410. tStart += this.vertices[i].triangleCount;
  42411. this.vertices[i].triangleCount = 0;
  42412. }
  42413. var newReferences = new Array(this.triangles.length * 3);
  42414. for (i = 0; i < this.triangles.length; ++i) {
  42415. t = this.triangles[i];
  42416. for (j = 0; j < 3; ++j) {
  42417. v = t.vertices[j];
  42418. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42419. v.triangleCount++;
  42420. }
  42421. }
  42422. this.references = newReferences;
  42423. if (identifyBorders) {
  42424. this.identifyBorder();
  42425. }
  42426. };
  42427. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42428. var x = point.x;
  42429. var y = point.y;
  42430. var z = point.z;
  42431. 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
  42432. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42433. };
  42434. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42435. var q = vertex1.q.add(vertex2.q);
  42436. var border = vertex1.isBorder && vertex2.isBorder;
  42437. var error = 0;
  42438. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42439. if (qDet !== 0 && !border) {
  42440. if (!pointResult) {
  42441. pointResult = BABYLON.Vector3.Zero();
  42442. }
  42443. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42444. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42445. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42446. error = this.vertexError(q, pointResult);
  42447. }
  42448. else {
  42449. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42450. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42451. var error1 = this.vertexError(q, vertex1.position);
  42452. var error2 = this.vertexError(q, vertex2.position);
  42453. var error3 = this.vertexError(q, p3);
  42454. error = Math.min(error1, error2, error3);
  42455. if (error === error1) {
  42456. if (pointResult) {
  42457. pointResult.copyFrom(vertex1.position);
  42458. }
  42459. }
  42460. else if (error === error2) {
  42461. if (pointResult) {
  42462. pointResult.copyFrom(vertex2.position);
  42463. }
  42464. }
  42465. else {
  42466. if (pointResult) {
  42467. pointResult.copyFrom(p3);
  42468. }
  42469. }
  42470. }
  42471. return error;
  42472. };
  42473. return QuadraticErrorSimplification;
  42474. }());
  42475. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42476. })(BABYLON || (BABYLON = {}));
  42477. //# sourceMappingURL=babylon.meshSimplification.js.map
  42478. var BABYLON;
  42479. (function (BABYLON) {
  42480. var serializedGeometries = [];
  42481. var serializeGeometry = function (geometry, serializationGeometries) {
  42482. if (serializedGeometries[geometry.id]) {
  42483. return;
  42484. }
  42485. if (geometry.doNotSerialize) {
  42486. return;
  42487. }
  42488. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42489. serializationGeometries.boxes.push(geometry.serialize());
  42490. }
  42491. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42492. serializationGeometries.spheres.push(geometry.serialize());
  42493. }
  42494. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42495. serializationGeometries.cylinders.push(geometry.serialize());
  42496. }
  42497. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42498. serializationGeometries.toruses.push(geometry.serialize());
  42499. }
  42500. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42501. serializationGeometries.grounds.push(geometry.serialize());
  42502. }
  42503. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42504. serializationGeometries.planes.push(geometry.serialize());
  42505. }
  42506. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42507. serializationGeometries.torusKnots.push(geometry.serialize());
  42508. }
  42509. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42510. throw new Error("Unknown primitive type");
  42511. }
  42512. else {
  42513. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42514. }
  42515. serializedGeometries[geometry.id] = true;
  42516. };
  42517. var serializeMesh = function (mesh, serializationScene) {
  42518. var serializationObject = {};
  42519. serializationObject.name = mesh.name;
  42520. serializationObject.id = mesh.id;
  42521. if (BABYLON.Tags.HasTags(mesh)) {
  42522. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42523. }
  42524. serializationObject.position = mesh.position.asArray();
  42525. if (mesh.rotationQuaternion) {
  42526. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42527. }
  42528. else if (mesh.rotation) {
  42529. serializationObject.rotation = mesh.rotation.asArray();
  42530. }
  42531. serializationObject.scaling = mesh.scaling.asArray();
  42532. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42533. serializationObject.isEnabled = mesh.isEnabled();
  42534. serializationObject.isVisible = mesh.isVisible;
  42535. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42536. serializationObject.pickable = mesh.isPickable;
  42537. serializationObject.receiveShadows = mesh.receiveShadows;
  42538. serializationObject.billboardMode = mesh.billboardMode;
  42539. serializationObject.visibility = mesh.visibility;
  42540. serializationObject.checkCollisions = mesh.checkCollisions;
  42541. serializationObject.isBlocker = mesh.isBlocker;
  42542. // Parent
  42543. if (mesh.parent) {
  42544. serializationObject.parentId = mesh.parent.id;
  42545. }
  42546. // Geometry
  42547. var geometry = mesh._geometry;
  42548. if (geometry) {
  42549. var geometryId = geometry.id;
  42550. serializationObject.geometryId = geometryId;
  42551. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42552. // 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
  42553. serializeGeometry(geometry, serializationScene.geometries);
  42554. }
  42555. // SubMeshes
  42556. serializationObject.subMeshes = [];
  42557. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42558. var subMesh = mesh.subMeshes[subIndex];
  42559. serializationObject.subMeshes.push({
  42560. materialIndex: subMesh.materialIndex,
  42561. verticesStart: subMesh.verticesStart,
  42562. verticesCount: subMesh.verticesCount,
  42563. indexStart: subMesh.indexStart,
  42564. indexCount: subMesh.indexCount
  42565. });
  42566. }
  42567. }
  42568. // Material
  42569. if (mesh.material) {
  42570. serializationObject.materialId = mesh.material.id;
  42571. }
  42572. else {
  42573. mesh.material = null;
  42574. }
  42575. // Skeleton
  42576. if (mesh.skeleton) {
  42577. serializationObject.skeletonId = mesh.skeleton.id;
  42578. }
  42579. // Physics
  42580. //TODO implement correct serialization for physics impostors.
  42581. if (mesh.getPhysicsImpostor()) {
  42582. serializationObject.physicsMass = mesh.getPhysicsMass();
  42583. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42584. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42585. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42586. }
  42587. // Metadata
  42588. if (mesh.metadata) {
  42589. serializationObject.metadata = mesh.metadata;
  42590. }
  42591. // Instances
  42592. serializationObject.instances = [];
  42593. for (var index = 0; index < mesh.instances.length; index++) {
  42594. var instance = mesh.instances[index];
  42595. var serializationInstance = {
  42596. name: instance.name,
  42597. position: instance.position.asArray(),
  42598. scaling: instance.scaling.asArray()
  42599. };
  42600. if (instance.rotationQuaternion) {
  42601. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42602. }
  42603. else if (instance.rotation) {
  42604. serializationInstance.rotation = instance.rotation.asArray();
  42605. }
  42606. serializationObject.instances.push(serializationInstance);
  42607. // Animations
  42608. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42609. serializationInstance.ranges = instance.serializeAnimationRanges();
  42610. }
  42611. // Animations
  42612. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42613. serializationObject.ranges = mesh.serializeAnimationRanges();
  42614. // Layer mask
  42615. serializationObject.layerMask = mesh.layerMask;
  42616. // Alpha
  42617. serializationObject.alphaIndex = mesh.alphaIndex;
  42618. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42619. // Overlay
  42620. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42621. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42622. serializationObject.renderOverlay = mesh.renderOverlay;
  42623. // Fog
  42624. serializationObject.applyFog = mesh.applyFog;
  42625. // Action Manager
  42626. if (mesh.actionManager) {
  42627. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42628. }
  42629. return serializationObject;
  42630. };
  42631. var finalizeSingleMesh = function (mesh, serializationObject) {
  42632. //only works if the mesh is already loaded
  42633. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42634. //serialize material
  42635. if (mesh.material) {
  42636. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42637. serializationObject.materials = serializationObject.materials || [];
  42638. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42639. serializationObject.materials.push(mesh.material.serialize());
  42640. }
  42641. }
  42642. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42643. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42644. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42645. serializationObject.multiMaterials.push(mesh.material.serialize());
  42646. }
  42647. }
  42648. }
  42649. //serialize geometry
  42650. var geometry = mesh._geometry;
  42651. if (geometry) {
  42652. if (!serializationObject.geometries) {
  42653. serializationObject.geometries = {};
  42654. serializationObject.geometries.boxes = [];
  42655. serializationObject.geometries.spheres = [];
  42656. serializationObject.geometries.cylinders = [];
  42657. serializationObject.geometries.toruses = [];
  42658. serializationObject.geometries.grounds = [];
  42659. serializationObject.geometries.planes = [];
  42660. serializationObject.geometries.torusKnots = [];
  42661. serializationObject.geometries.vertexData = [];
  42662. }
  42663. serializeGeometry(geometry, serializationObject.geometries);
  42664. }
  42665. // Skeletons
  42666. if (mesh.skeleton) {
  42667. serializationObject.skeletons = serializationObject.skeletons || [];
  42668. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42669. }
  42670. //serialize the actual mesh
  42671. serializationObject.meshes = serializationObject.meshes || [];
  42672. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42673. }
  42674. };
  42675. var SceneSerializer = (function () {
  42676. function SceneSerializer() {
  42677. }
  42678. SceneSerializer.ClearCache = function () {
  42679. serializedGeometries = [];
  42680. };
  42681. SceneSerializer.Serialize = function (scene) {
  42682. var serializationObject = {};
  42683. // Scene
  42684. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42685. serializationObject.autoClear = scene.autoClear;
  42686. serializationObject.clearColor = scene.clearColor.asArray();
  42687. serializationObject.ambientColor = scene.ambientColor.asArray();
  42688. serializationObject.gravity = scene.gravity.asArray();
  42689. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42690. serializationObject.workerCollisions = scene.workerCollisions;
  42691. // Fog
  42692. if (scene.fogMode && scene.fogMode !== 0) {
  42693. serializationObject.fogMode = scene.fogMode;
  42694. serializationObject.fogColor = scene.fogColor.asArray();
  42695. serializationObject.fogStart = scene.fogStart;
  42696. serializationObject.fogEnd = scene.fogEnd;
  42697. serializationObject.fogDensity = scene.fogDensity;
  42698. }
  42699. //Physics
  42700. if (scene.isPhysicsEnabled()) {
  42701. serializationObject.physicsEnabled = true;
  42702. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42703. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42704. }
  42705. // Metadata
  42706. if (scene.metadata) {
  42707. serializationObject.metadata = scene.metadata;
  42708. }
  42709. // Lights
  42710. serializationObject.lights = [];
  42711. var index;
  42712. var light;
  42713. for (index = 0; index < scene.lights.length; index++) {
  42714. light = scene.lights[index];
  42715. if (!light.doNotSerialize) {
  42716. serializationObject.lights.push(light.serialize());
  42717. }
  42718. }
  42719. // Cameras
  42720. serializationObject.cameras = [];
  42721. for (index = 0; index < scene.cameras.length; index++) {
  42722. var camera = scene.cameras[index];
  42723. if (!camera.doNotSerialize) {
  42724. serializationObject.cameras.push(camera.serialize());
  42725. }
  42726. }
  42727. if (scene.activeCamera) {
  42728. serializationObject.activeCameraID = scene.activeCamera.id;
  42729. }
  42730. // Animations
  42731. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42732. // Materials
  42733. serializationObject.materials = [];
  42734. serializationObject.multiMaterials = [];
  42735. var material;
  42736. for (index = 0; index < scene.materials.length; index++) {
  42737. material = scene.materials[index];
  42738. if (!material.doNotSerialize) {
  42739. serializationObject.materials.push(material.serialize());
  42740. }
  42741. }
  42742. // MultiMaterials
  42743. serializationObject.multiMaterials = [];
  42744. for (index = 0; index < scene.multiMaterials.length; index++) {
  42745. var multiMaterial = scene.multiMaterials[index];
  42746. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42747. }
  42748. // Skeletons
  42749. serializationObject.skeletons = [];
  42750. for (index = 0; index < scene.skeletons.length; index++) {
  42751. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42752. }
  42753. // Geometries
  42754. serializationObject.geometries = {};
  42755. serializationObject.geometries.boxes = [];
  42756. serializationObject.geometries.spheres = [];
  42757. serializationObject.geometries.cylinders = [];
  42758. serializationObject.geometries.toruses = [];
  42759. serializationObject.geometries.grounds = [];
  42760. serializationObject.geometries.planes = [];
  42761. serializationObject.geometries.torusKnots = [];
  42762. serializationObject.geometries.vertexData = [];
  42763. serializedGeometries = [];
  42764. var geometries = scene.getGeometries();
  42765. for (index = 0; index < geometries.length; index++) {
  42766. var geometry = geometries[index];
  42767. if (geometry.isReady()) {
  42768. serializeGeometry(geometry, serializationObject.geometries);
  42769. }
  42770. }
  42771. // Meshes
  42772. serializationObject.meshes = [];
  42773. for (index = 0; index < scene.meshes.length; index++) {
  42774. var abstractMesh = scene.meshes[index];
  42775. if (abstractMesh instanceof BABYLON.Mesh) {
  42776. var mesh = abstractMesh;
  42777. if (!mesh.doNotSerialize) {
  42778. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42779. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42780. }
  42781. }
  42782. }
  42783. }
  42784. // Particles Systems
  42785. serializationObject.particleSystems = [];
  42786. for (index = 0; index < scene.particleSystems.length; index++) {
  42787. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42788. }
  42789. // Lens flares
  42790. serializationObject.lensFlareSystems = [];
  42791. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42792. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42793. }
  42794. // Shadows
  42795. serializationObject.shadowGenerators = [];
  42796. for (index = 0; index < scene.lights.length; index++) {
  42797. light = scene.lights[index];
  42798. var shadowGenerator = light.getShadowGenerator();
  42799. // Only support serialization for official generator so far.
  42800. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42801. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42802. }
  42803. }
  42804. // Action Manager
  42805. if (scene.actionManager) {
  42806. serializationObject.actions = scene.actionManager.serialize("scene");
  42807. }
  42808. // Audio
  42809. serializationObject.sounds = [];
  42810. for (index = 0; index < scene.soundTracks.length; index++) {
  42811. var soundtrack = scene.soundTracks[index];
  42812. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42813. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42814. }
  42815. }
  42816. return serializationObject;
  42817. };
  42818. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42819. if (withParents === void 0) { withParents = false; }
  42820. if (withChildren === void 0) { withChildren = false; }
  42821. var serializationObject = {};
  42822. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42823. if (withParents || withChildren) {
  42824. //deliberate for loop! not for each, appended should be processed as well.
  42825. for (var i = 0; i < toSerialize.length; ++i) {
  42826. if (withChildren) {
  42827. toSerialize[i].getDescendants().forEach(function (node) {
  42828. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42829. toSerialize.push(node);
  42830. }
  42831. });
  42832. }
  42833. //make sure the array doesn't contain the object already
  42834. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42835. toSerialize.push(toSerialize[i].parent);
  42836. }
  42837. }
  42838. }
  42839. toSerialize.forEach(function (mesh) {
  42840. finalizeSingleMesh(mesh, serializationObject);
  42841. });
  42842. return serializationObject;
  42843. };
  42844. return SceneSerializer;
  42845. }());
  42846. BABYLON.SceneSerializer = SceneSerializer;
  42847. })(BABYLON || (BABYLON = {}));
  42848. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42849. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42850. // Huge respect for a such great lib.
  42851. // Earcut license:
  42852. // Copyright (c) 2016, Mapbox
  42853. //
  42854. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42855. // with or without fee is hereby granted, provided that the above copyright notice
  42856. // and this permission notice appear in all copies.
  42857. //
  42858. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42859. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42860. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42861. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42862. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42863. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42864. // THIS SOFTWARE.
  42865. var Earcut;
  42866. (function (Earcut) {
  42867. /**
  42868. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42869. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42870. * @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).
  42871. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42872. */
  42873. function earcut(data, holeIndices, dim) {
  42874. dim = dim || 2;
  42875. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42876. if (!outerNode)
  42877. return triangles;
  42878. var minX, minY, maxX, maxY, x, y, size;
  42879. if (hasHoles)
  42880. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42881. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42882. if (data.length > 80 * dim) {
  42883. minX = maxX = data[0];
  42884. minY = maxY = data[1];
  42885. for (var i = dim; i < outerLen; i += dim) {
  42886. x = data[i];
  42887. y = data[i + 1];
  42888. if (x < minX)
  42889. minX = x;
  42890. if (y < minY)
  42891. minY = y;
  42892. if (x > maxX)
  42893. maxX = x;
  42894. if (y > maxY)
  42895. maxY = y;
  42896. }
  42897. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42898. size = Math.max(maxX - minX, maxY - minY);
  42899. }
  42900. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42901. return triangles;
  42902. }
  42903. Earcut.earcut = earcut;
  42904. // create a circular doubly linked list from polygon points in the specified winding order
  42905. function linkedList(data, start, end, dim, clockwise) {
  42906. var i, last;
  42907. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42908. for (i = start; i < end; i += dim)
  42909. last = insertNode(i, data[i], data[i + 1], last);
  42910. }
  42911. else {
  42912. for (i = end - dim; i >= start; i -= dim)
  42913. last = insertNode(i, data[i], data[i + 1], last);
  42914. }
  42915. if (last && equals(last, last.next)) {
  42916. removeNode(last);
  42917. last = last.next;
  42918. }
  42919. return last;
  42920. }
  42921. // eliminate colinear or duplicate points
  42922. function filterPoints(start, end) {
  42923. if (!start)
  42924. return start;
  42925. if (!end)
  42926. end = start;
  42927. var p = start, again;
  42928. do {
  42929. again = false;
  42930. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42931. removeNode(p);
  42932. p = end = p.prev;
  42933. if (p === p.next)
  42934. return null;
  42935. again = true;
  42936. }
  42937. else {
  42938. p = p.next;
  42939. }
  42940. } while (again || p !== end);
  42941. return end;
  42942. }
  42943. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42944. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42945. if (!ear)
  42946. return;
  42947. // interlink polygon nodes in z-order
  42948. if (!pass && size)
  42949. indexCurve(ear, minX, minY, size);
  42950. var stop = ear, prev, next;
  42951. // iterate through ears, slicing them one by one
  42952. while (ear.prev !== ear.next) {
  42953. prev = ear.prev;
  42954. next = ear.next;
  42955. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42956. // cut off the triangle
  42957. triangles.push(prev.i / dim);
  42958. triangles.push(ear.i / dim);
  42959. triangles.push(next.i / dim);
  42960. removeNode(ear);
  42961. // skipping the next vertice leads to less sliver triangles
  42962. ear = next.next;
  42963. stop = next.next;
  42964. continue;
  42965. }
  42966. ear = next;
  42967. // if we looped through the whole remaining polygon and can't find any more ears
  42968. if (ear === stop) {
  42969. // try filtering points and slicing again
  42970. if (!pass) {
  42971. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  42972. }
  42973. else if (pass === 1) {
  42974. ear = cureLocalIntersections(ear, triangles, dim);
  42975. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  42976. }
  42977. else if (pass === 2) {
  42978. splitEarcut(ear, triangles, dim, minX, minY, size);
  42979. }
  42980. break;
  42981. }
  42982. }
  42983. }
  42984. // check whether a polygon node forms a valid ear with adjacent nodes
  42985. function isEar(ear) {
  42986. var a = ear.prev, b = ear, c = ear.next;
  42987. if (area(a, b, c) >= 0)
  42988. return false; // reflex, can't be an ear
  42989. // now make sure we don't have other points inside the potential ear
  42990. var p = ear.next.next;
  42991. while (p !== ear.prev) {
  42992. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42993. area(p.prev, p, p.next) >= 0)
  42994. return false;
  42995. p = p.next;
  42996. }
  42997. return true;
  42998. }
  42999. function isEarHashed(ear, minX, minY, size) {
  43000. var a = ear.prev, b = ear, c = ear.next;
  43001. if (area(a, b, c) >= 0)
  43002. return false; // reflex, can't be an ear
  43003. // triangle bbox; min & max are calculated like this for speed
  43004. 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);
  43005. // z-order range for the current triangle bbox;
  43006. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43007. // first look for points inside the triangle in increasing z-order
  43008. var p = ear.nextZ;
  43009. while (p && p.z <= maxZ) {
  43010. if (p !== ear.prev &&
  43011. p !== ear.next &&
  43012. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43013. area(p.prev, p, p.next) >= 0)
  43014. return false;
  43015. p = p.nextZ;
  43016. }
  43017. // then look for points in decreasing z-order
  43018. p = ear.prevZ;
  43019. while (p && p.z >= minZ) {
  43020. if (p !== ear.prev &&
  43021. p !== ear.next &&
  43022. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43023. area(p.prev, p, p.next) >= 0)
  43024. return false;
  43025. p = p.prevZ;
  43026. }
  43027. return true;
  43028. }
  43029. // go through all polygon nodes and cure small local self-intersections
  43030. function cureLocalIntersections(start, triangles, dim) {
  43031. var p = start;
  43032. do {
  43033. var a = p.prev, b = p.next.next;
  43034. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43035. triangles.push(a.i / dim);
  43036. triangles.push(p.i / dim);
  43037. triangles.push(b.i / dim);
  43038. // remove two nodes involved
  43039. removeNode(p);
  43040. removeNode(p.next);
  43041. p = start = b;
  43042. }
  43043. p = p.next;
  43044. } while (p !== start);
  43045. return p;
  43046. }
  43047. // try splitting polygon into two and triangulate them independently
  43048. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43049. // look for a valid diagonal that divides the polygon into two
  43050. var a = start;
  43051. do {
  43052. var b = a.next.next;
  43053. while (b !== a.prev) {
  43054. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43055. // split the polygon in two by the diagonal
  43056. var c = splitPolygon(a, b);
  43057. // filter colinear points around the cuts
  43058. a = filterPoints(a, a.next);
  43059. c = filterPoints(c, c.next);
  43060. // run earcut on each half
  43061. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43062. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43063. return;
  43064. }
  43065. b = b.next;
  43066. }
  43067. a = a.next;
  43068. } while (a !== start);
  43069. }
  43070. // link every hole into the outer loop, producing a single-ring polygon without holes
  43071. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43072. var queue = [], i, len, start, end, list;
  43073. for (i = 0, len = holeIndices.length; i < len; i++) {
  43074. start = holeIndices[i] * dim;
  43075. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43076. list = linkedList(data, start, end, dim, false);
  43077. if (list === list.next)
  43078. list.steiner = true;
  43079. queue.push(getLeftmost(list));
  43080. }
  43081. queue.sort(compareX);
  43082. // process holes from left to right
  43083. for (i = 0; i < queue.length; i++) {
  43084. eliminateHole(queue[i], outerNode);
  43085. outerNode = filterPoints(outerNode, outerNode.next);
  43086. }
  43087. return outerNode;
  43088. }
  43089. function compareX(a, b) {
  43090. return a.x - b.x;
  43091. }
  43092. // find a bridge between vertices that connects hole with an outer ring and and link it
  43093. function eliminateHole(hole, outerNode) {
  43094. outerNode = findHoleBridge(hole, outerNode);
  43095. if (outerNode) {
  43096. var b = splitPolygon(outerNode, hole);
  43097. filterPoints(b, b.next);
  43098. }
  43099. }
  43100. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43101. function findHoleBridge(hole, outerNode) {
  43102. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43103. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43104. // segment's endpoint with lesser x will be potential connection point
  43105. do {
  43106. if (hy <= p.y && hy >= p.next.y) {
  43107. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43108. if (x <= hx && x > qx) {
  43109. qx = x;
  43110. if (x === hx) {
  43111. if (hy === p.y)
  43112. return p;
  43113. if (hy === p.next.y)
  43114. return p.next;
  43115. }
  43116. m = p.x < p.next.x ? p : p.next;
  43117. }
  43118. }
  43119. p = p.next;
  43120. } while (p !== outerNode);
  43121. if (!m)
  43122. return null;
  43123. if (hx === qx)
  43124. return m.prev; // hole touches outer segment; pick lower endpoint
  43125. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43126. // if there are no points found, we have a valid connection;
  43127. // otherwise choose the point of the minimum angle with the ray as connection point
  43128. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43129. p = m.next;
  43130. while (p !== stop) {
  43131. if (hx >= p.x &&
  43132. p.x >= mx &&
  43133. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43134. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43135. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43136. m = p;
  43137. tanMin = tan;
  43138. }
  43139. }
  43140. p = p.next;
  43141. }
  43142. return m;
  43143. }
  43144. // interlink polygon nodes in z-order
  43145. function indexCurve(start, minX, minY, size) {
  43146. var p = start;
  43147. do {
  43148. if (p.z === null)
  43149. p.z = zOrder(p.x, p.y, minX, minY, size);
  43150. p.prevZ = p.prev;
  43151. p.nextZ = p.next;
  43152. p = p.next;
  43153. } while (p !== start);
  43154. p.prevZ.nextZ = null;
  43155. p.prevZ = null;
  43156. sortLinked(p);
  43157. }
  43158. // Simon Tatham's linked list merge sort algorithm
  43159. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43160. function sortLinked(list) {
  43161. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43162. do {
  43163. p = list;
  43164. list = null;
  43165. tail = null;
  43166. numMerges = 0;
  43167. while (p) {
  43168. numMerges++;
  43169. q = p;
  43170. pSize = 0;
  43171. for (i = 0; i < inSize; i++) {
  43172. pSize++;
  43173. q = q.nextZ;
  43174. if (!q)
  43175. break;
  43176. }
  43177. qSize = inSize;
  43178. while (pSize > 0 || (qSize > 0 && q)) {
  43179. if (pSize === 0) {
  43180. e = q;
  43181. q = q.nextZ;
  43182. qSize--;
  43183. }
  43184. else if (qSize === 0 || !q) {
  43185. e = p;
  43186. p = p.nextZ;
  43187. pSize--;
  43188. }
  43189. else if (p.z <= q.z) {
  43190. e = p;
  43191. p = p.nextZ;
  43192. pSize--;
  43193. }
  43194. else {
  43195. e = q;
  43196. q = q.nextZ;
  43197. qSize--;
  43198. }
  43199. if (tail)
  43200. tail.nextZ = e;
  43201. else
  43202. list = e;
  43203. e.prevZ = tail;
  43204. tail = e;
  43205. }
  43206. p = q;
  43207. }
  43208. tail.nextZ = null;
  43209. inSize *= 2;
  43210. } while (numMerges > 1);
  43211. return list;
  43212. }
  43213. // z-order of a point given coords and size of the data bounding box
  43214. function zOrder(x, y, minX, minY, size) {
  43215. // coords are transformed into non-negative 15-bit integer range
  43216. x = 32767 * (x - minX) / size;
  43217. y = 32767 * (y - minY) / size;
  43218. x = (x | (x << 8)) & 0x00FF00FF;
  43219. x = (x | (x << 4)) & 0x0F0F0F0F;
  43220. x = (x | (x << 2)) & 0x33333333;
  43221. x = (x | (x << 1)) & 0x55555555;
  43222. y = (y | (y << 8)) & 0x00FF00FF;
  43223. y = (y | (y << 4)) & 0x0F0F0F0F;
  43224. y = (y | (y << 2)) & 0x33333333;
  43225. y = (y | (y << 1)) & 0x55555555;
  43226. return x | (y << 1);
  43227. }
  43228. // find the leftmost node of a polygon ring
  43229. function getLeftmost(start) {
  43230. var p = start, leftmost = start;
  43231. do {
  43232. if (p.x < leftmost.x)
  43233. leftmost = p;
  43234. p = p.next;
  43235. } while (p !== start);
  43236. return leftmost;
  43237. }
  43238. // check if a point lies within a convex triangle
  43239. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43240. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43241. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43242. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43243. }
  43244. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43245. function isValidDiagonal(a, b) {
  43246. return a.next.i !== b.i &&
  43247. a.prev.i !== b.i &&
  43248. !intersectsPolygon(a, b) &&
  43249. locallyInside(a, b) &&
  43250. locallyInside(b, a) &&
  43251. middleInside(a, b);
  43252. }
  43253. // signed area of a triangle
  43254. function area(p, q, r) {
  43255. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43256. }
  43257. // check if two points are equal
  43258. function equals(p1, p2) {
  43259. return p1.x === p2.x && p1.y === p2.y;
  43260. }
  43261. // check if two segments intersect
  43262. function intersects(p1, q1, p2, q2) {
  43263. if ((equals(p1, q1) && equals(p2, q2)) ||
  43264. (equals(p1, q2) && equals(p2, q1)))
  43265. return true;
  43266. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43267. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43268. }
  43269. // check if a polygon diagonal intersects any polygon segments
  43270. function intersectsPolygon(a, b) {
  43271. var p = a;
  43272. do {
  43273. if (p.i !== a.i &&
  43274. p.next.i !== a.i &&
  43275. p.i !== b.i &&
  43276. p.next.i !== b.i &&
  43277. intersects(p, p.next, a, b))
  43278. return true;
  43279. p = p.next;
  43280. } while (p !== a);
  43281. return false;
  43282. }
  43283. // check if a polygon diagonal is locally inside the polygon
  43284. function locallyInside(a, b) {
  43285. return area(a.prev, a, a.next) < 0
  43286. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43287. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43288. }
  43289. // check if the middle point of a polygon diagonal is inside the polygon
  43290. function middleInside(a, b) {
  43291. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43292. do {
  43293. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43294. inside = !inside;
  43295. p = p.next;
  43296. } while (p !== a);
  43297. return inside;
  43298. }
  43299. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43300. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43301. function splitPolygon(a, b) {
  43302. 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;
  43303. a.next = b;
  43304. b.prev = a;
  43305. a2.next = an;
  43306. an.prev = a2;
  43307. b2.next = a2;
  43308. a2.prev = b2;
  43309. bp.next = b2;
  43310. b2.prev = bp;
  43311. return b2;
  43312. }
  43313. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43314. function insertNode(i, x, y, last) {
  43315. var p = new Node(i, x, y);
  43316. if (!last) {
  43317. p.prev = p;
  43318. p.next = p;
  43319. }
  43320. else {
  43321. p.next = last.next;
  43322. p.prev = last;
  43323. last.next.prev = p;
  43324. last.next = p;
  43325. }
  43326. return p;
  43327. }
  43328. function removeNode(p) {
  43329. p.next.prev = p.prev;
  43330. p.prev.next = p.next;
  43331. if (p.prevZ)
  43332. p.prevZ.nextZ = p.nextZ;
  43333. if (p.nextZ)
  43334. p.nextZ.prevZ = p.prevZ;
  43335. }
  43336. function Node(i, x, y) {
  43337. // vertice index in coordinates array
  43338. this.i = i;
  43339. // vertex coordinates
  43340. this.x = x;
  43341. this.y = y;
  43342. // previous and next vertice nodes in a polygon ring
  43343. this.prev = null;
  43344. this.next = null;
  43345. // z-order curve value
  43346. this.z = null;
  43347. // previous and next nodes in z-order
  43348. this.prevZ = null;
  43349. this.nextZ = null;
  43350. // indicates whether this is a steiner point
  43351. this.steiner = false;
  43352. }
  43353. /**
  43354. * return a percentage difference between the polygon area and its triangulation area;
  43355. * used to verify correctness of triangulation
  43356. */
  43357. function deviation(data, holeIndices, dim, triangles) {
  43358. var hasHoles = holeIndices && holeIndices.length;
  43359. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43360. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43361. if (hasHoles) {
  43362. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43363. var start = holeIndices[i] * dim;
  43364. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43365. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43366. }
  43367. }
  43368. var trianglesArea = 0;
  43369. for (i = 0; i < triangles.length; i += 3) {
  43370. var a = triangles[i] * dim;
  43371. var b = triangles[i + 1] * dim;
  43372. var c = triangles[i + 2] * dim;
  43373. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43374. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43375. }
  43376. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43377. }
  43378. Earcut.deviation = deviation;
  43379. ;
  43380. function signedArea(data, start, end, dim) {
  43381. var sum = 0;
  43382. for (var i = start, j = end - dim; i < end; i += dim) {
  43383. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43384. j = i;
  43385. }
  43386. return sum;
  43387. }
  43388. /**
  43389. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43390. */
  43391. function flatten(data) {
  43392. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43393. for (var i = 0; i < data.length; i++) {
  43394. for (var j = 0; j < data[i].length; j++) {
  43395. for (var d = 0; d < dim; d++)
  43396. result.vertices.push(data[i][j][d]);
  43397. }
  43398. if (i > 0) {
  43399. holeIndex += data[i - 1].length;
  43400. result.holes.push(holeIndex);
  43401. }
  43402. }
  43403. return result;
  43404. }
  43405. Earcut.flatten = flatten;
  43406. ;
  43407. })(Earcut || (Earcut = {}));
  43408. //# sourceMappingURL=babylon.earcut.js.map
  43409. var BABYLON;
  43410. (function (BABYLON) {
  43411. // Unique ID when we import meshes from Babylon to CSG
  43412. var currentCSGMeshId = 0;
  43413. // # class Vertex
  43414. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43415. // one to provide additional features like texture coordinates and vertex
  43416. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43417. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43418. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43419. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43420. // is not used anywhere else.
  43421. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43422. var Vertex = (function () {
  43423. function Vertex(pos, normal, uv) {
  43424. this.pos = pos;
  43425. this.normal = normal;
  43426. this.uv = uv;
  43427. }
  43428. Vertex.prototype.clone = function () {
  43429. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43430. };
  43431. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43432. // orientation of a polygon is flipped.
  43433. Vertex.prototype.flip = function () {
  43434. this.normal = this.normal.scale(-1);
  43435. };
  43436. // Create a new vertex between this vertex and `other` by linearly
  43437. // interpolating all properties using a parameter of `t`. Subclasses should
  43438. // override this to interpolate additional properties.
  43439. Vertex.prototype.interpolate = function (other, t) {
  43440. 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));
  43441. };
  43442. return Vertex;
  43443. }());
  43444. // # class Plane
  43445. // Represents a plane in 3D space.
  43446. var Plane = (function () {
  43447. function Plane(normal, w) {
  43448. this.normal = normal;
  43449. this.w = w;
  43450. }
  43451. Plane.FromPoints = function (a, b, c) {
  43452. var v0 = c.subtract(a);
  43453. var v1 = b.subtract(a);
  43454. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43455. return null;
  43456. }
  43457. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43458. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43459. };
  43460. Plane.prototype.clone = function () {
  43461. return new Plane(this.normal.clone(), this.w);
  43462. };
  43463. Plane.prototype.flip = function () {
  43464. this.normal.scaleInPlace(-1);
  43465. this.w = -this.w;
  43466. };
  43467. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43468. // fragments in the appropriate lists. Coplanar polygons go into either
  43469. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43470. // respect to this plane. Polygons in front or in back of this plane go into
  43471. // either `front` or `back`.
  43472. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43473. var COPLANAR = 0;
  43474. var FRONT = 1;
  43475. var BACK = 2;
  43476. var SPANNING = 3;
  43477. // Classify each point as well as the entire polygon into one of the above
  43478. // four classes.
  43479. var polygonType = 0;
  43480. var types = [];
  43481. var i;
  43482. var t;
  43483. for (i = 0; i < polygon.vertices.length; i++) {
  43484. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43485. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43486. polygonType |= type;
  43487. types.push(type);
  43488. }
  43489. // Put the polygon in the correct list, splitting it when necessary.
  43490. switch (polygonType) {
  43491. case COPLANAR:
  43492. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43493. break;
  43494. case FRONT:
  43495. front.push(polygon);
  43496. break;
  43497. case BACK:
  43498. back.push(polygon);
  43499. break;
  43500. case SPANNING:
  43501. var f = [], b = [];
  43502. for (i = 0; i < polygon.vertices.length; i++) {
  43503. var j = (i + 1) % polygon.vertices.length;
  43504. var ti = types[i], tj = types[j];
  43505. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43506. if (ti !== BACK)
  43507. f.push(vi);
  43508. if (ti !== FRONT)
  43509. b.push(ti !== BACK ? vi.clone() : vi);
  43510. if ((ti | tj) === SPANNING) {
  43511. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43512. var v = vi.interpolate(vj, t);
  43513. f.push(v);
  43514. b.push(v.clone());
  43515. }
  43516. }
  43517. var poly;
  43518. if (f.length >= 3) {
  43519. poly = new Polygon(f, polygon.shared);
  43520. if (poly.plane)
  43521. front.push(poly);
  43522. }
  43523. if (b.length >= 3) {
  43524. poly = new Polygon(b, polygon.shared);
  43525. if (poly.plane)
  43526. back.push(poly);
  43527. }
  43528. break;
  43529. }
  43530. };
  43531. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43532. // point is on the plane.
  43533. Plane.EPSILON = 1e-5;
  43534. return Plane;
  43535. }());
  43536. // # class Polygon
  43537. // Represents a convex polygon. The vertices used to initialize a polygon must
  43538. // be coplanar and form a convex loop.
  43539. //
  43540. // Each convex polygon has a `shared` property, which is shared between all
  43541. // polygons that are clones of each other or were split from the same polygon.
  43542. // This can be used to define per-polygon properties (such as surface color).
  43543. var Polygon = (function () {
  43544. function Polygon(vertices, shared) {
  43545. this.vertices = vertices;
  43546. this.shared = shared;
  43547. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43548. }
  43549. Polygon.prototype.clone = function () {
  43550. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43551. return new Polygon(vertices, this.shared);
  43552. };
  43553. Polygon.prototype.flip = function () {
  43554. this.vertices.reverse().map(function (v) { v.flip(); });
  43555. this.plane.flip();
  43556. };
  43557. return Polygon;
  43558. }());
  43559. // # class Node
  43560. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43561. // by picking a polygon to split along. That polygon (and all other coplanar
  43562. // polygons) are added directly to that node and the other polygons are added to
  43563. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43564. // no distinction between internal and leaf nodes.
  43565. var Node = (function () {
  43566. function Node(polygons) {
  43567. this.plane = null;
  43568. this.front = null;
  43569. this.back = null;
  43570. this.polygons = [];
  43571. if (polygons) {
  43572. this.build(polygons);
  43573. }
  43574. }
  43575. Node.prototype.clone = function () {
  43576. var node = new Node();
  43577. node.plane = this.plane && this.plane.clone();
  43578. node.front = this.front && this.front.clone();
  43579. node.back = this.back && this.back.clone();
  43580. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43581. return node;
  43582. };
  43583. // Convert solid space to empty space and empty space to solid space.
  43584. Node.prototype.invert = function () {
  43585. for (var i = 0; i < this.polygons.length; i++) {
  43586. this.polygons[i].flip();
  43587. }
  43588. if (this.plane) {
  43589. this.plane.flip();
  43590. }
  43591. if (this.front) {
  43592. this.front.invert();
  43593. }
  43594. if (this.back) {
  43595. this.back.invert();
  43596. }
  43597. var temp = this.front;
  43598. this.front = this.back;
  43599. this.back = temp;
  43600. };
  43601. // Recursively remove all polygons in `polygons` that are inside this BSP
  43602. // tree.
  43603. Node.prototype.clipPolygons = function (polygons) {
  43604. if (!this.plane)
  43605. return polygons.slice();
  43606. var front = [], back = [];
  43607. for (var i = 0; i < polygons.length; i++) {
  43608. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43609. }
  43610. if (this.front) {
  43611. front = this.front.clipPolygons(front);
  43612. }
  43613. if (this.back) {
  43614. back = this.back.clipPolygons(back);
  43615. }
  43616. else {
  43617. back = [];
  43618. }
  43619. return front.concat(back);
  43620. };
  43621. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43622. // `bsp`.
  43623. Node.prototype.clipTo = function (bsp) {
  43624. this.polygons = bsp.clipPolygons(this.polygons);
  43625. if (this.front)
  43626. this.front.clipTo(bsp);
  43627. if (this.back)
  43628. this.back.clipTo(bsp);
  43629. };
  43630. // Return a list of all polygons in this BSP tree.
  43631. Node.prototype.allPolygons = function () {
  43632. var polygons = this.polygons.slice();
  43633. if (this.front)
  43634. polygons = polygons.concat(this.front.allPolygons());
  43635. if (this.back)
  43636. polygons = polygons.concat(this.back.allPolygons());
  43637. return polygons;
  43638. };
  43639. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43640. // new polygons are filtered down to the bottom of the tree and become new
  43641. // nodes there. Each set of polygons is partitioned using the first polygon
  43642. // (no heuristic is used to pick a good split).
  43643. Node.prototype.build = function (polygons) {
  43644. if (!polygons.length)
  43645. return;
  43646. if (!this.plane)
  43647. this.plane = polygons[0].plane.clone();
  43648. var front = [], back = [];
  43649. for (var i = 0; i < polygons.length; i++) {
  43650. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43651. }
  43652. if (front.length) {
  43653. if (!this.front)
  43654. this.front = new Node();
  43655. this.front.build(front);
  43656. }
  43657. if (back.length) {
  43658. if (!this.back)
  43659. this.back = new Node();
  43660. this.back.build(back);
  43661. }
  43662. };
  43663. return Node;
  43664. }());
  43665. var CSG = (function () {
  43666. function CSG() {
  43667. this.polygons = new Array();
  43668. }
  43669. // Convert BABYLON.Mesh to BABYLON.CSG
  43670. CSG.FromMesh = function (mesh) {
  43671. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43672. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43673. if (mesh instanceof BABYLON.Mesh) {
  43674. mesh.computeWorldMatrix(true);
  43675. matrix = mesh.getWorldMatrix();
  43676. meshPosition = mesh.position.clone();
  43677. meshRotation = mesh.rotation.clone();
  43678. if (mesh.rotationQuaternion) {
  43679. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43680. }
  43681. meshScaling = mesh.scaling.clone();
  43682. }
  43683. else {
  43684. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43685. }
  43686. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43687. var subMeshes = mesh.subMeshes;
  43688. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43689. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43690. vertices = [];
  43691. for (var j = 0; j < 3; j++) {
  43692. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43693. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43694. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43695. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43696. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43697. vertex = new Vertex(position, normal, uv);
  43698. vertices.push(vertex);
  43699. }
  43700. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43701. // To handle the case of degenerated triangle
  43702. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43703. if (polygon.plane)
  43704. polygons.push(polygon);
  43705. }
  43706. }
  43707. var csg = CSG.FromPolygons(polygons);
  43708. csg.matrix = matrix;
  43709. csg.position = meshPosition;
  43710. csg.rotation = meshRotation;
  43711. csg.scaling = meshScaling;
  43712. csg.rotationQuaternion = meshRotationQuaternion;
  43713. currentCSGMeshId++;
  43714. return csg;
  43715. };
  43716. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43717. CSG.FromPolygons = function (polygons) {
  43718. var csg = new CSG();
  43719. csg.polygons = polygons;
  43720. return csg;
  43721. };
  43722. CSG.prototype.clone = function () {
  43723. var csg = new CSG();
  43724. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43725. csg.copyTransformAttributes(this);
  43726. return csg;
  43727. };
  43728. CSG.prototype.toPolygons = function () {
  43729. return this.polygons;
  43730. };
  43731. CSG.prototype.union = function (csg) {
  43732. var a = new Node(this.clone().polygons);
  43733. var b = new Node(csg.clone().polygons);
  43734. a.clipTo(b);
  43735. b.clipTo(a);
  43736. b.invert();
  43737. b.clipTo(a);
  43738. b.invert();
  43739. a.build(b.allPolygons());
  43740. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43741. };
  43742. CSG.prototype.unionInPlace = function (csg) {
  43743. var a = new Node(this.polygons);
  43744. var b = new Node(csg.polygons);
  43745. a.clipTo(b);
  43746. b.clipTo(a);
  43747. b.invert();
  43748. b.clipTo(a);
  43749. b.invert();
  43750. a.build(b.allPolygons());
  43751. this.polygons = a.allPolygons();
  43752. };
  43753. CSG.prototype.subtract = function (csg) {
  43754. var a = new Node(this.clone().polygons);
  43755. var b = new Node(csg.clone().polygons);
  43756. a.invert();
  43757. a.clipTo(b);
  43758. b.clipTo(a);
  43759. b.invert();
  43760. b.clipTo(a);
  43761. b.invert();
  43762. a.build(b.allPolygons());
  43763. a.invert();
  43764. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43765. };
  43766. CSG.prototype.subtractInPlace = function (csg) {
  43767. var a = new Node(this.polygons);
  43768. var b = new Node(csg.polygons);
  43769. a.invert();
  43770. a.clipTo(b);
  43771. b.clipTo(a);
  43772. b.invert();
  43773. b.clipTo(a);
  43774. b.invert();
  43775. a.build(b.allPolygons());
  43776. a.invert();
  43777. this.polygons = a.allPolygons();
  43778. };
  43779. CSG.prototype.intersect = function (csg) {
  43780. var a = new Node(this.clone().polygons);
  43781. var b = new Node(csg.clone().polygons);
  43782. a.invert();
  43783. b.clipTo(a);
  43784. b.invert();
  43785. a.clipTo(b);
  43786. b.clipTo(a);
  43787. a.build(b.allPolygons());
  43788. a.invert();
  43789. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43790. };
  43791. CSG.prototype.intersectInPlace = function (csg) {
  43792. var a = new Node(this.polygons);
  43793. var b = new Node(csg.polygons);
  43794. a.invert();
  43795. b.clipTo(a);
  43796. b.invert();
  43797. a.clipTo(b);
  43798. b.clipTo(a);
  43799. a.build(b.allPolygons());
  43800. a.invert();
  43801. this.polygons = a.allPolygons();
  43802. };
  43803. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43804. // not modified.
  43805. CSG.prototype.inverse = function () {
  43806. var csg = this.clone();
  43807. csg.inverseInPlace();
  43808. return csg;
  43809. };
  43810. CSG.prototype.inverseInPlace = function () {
  43811. this.polygons.map(function (p) { p.flip(); });
  43812. };
  43813. // This is used to keep meshes transformations so they can be restored
  43814. // when we build back a Babylon Mesh
  43815. // NB : All CSG operations are performed in world coordinates
  43816. CSG.prototype.copyTransformAttributes = function (csg) {
  43817. this.matrix = csg.matrix;
  43818. this.position = csg.position;
  43819. this.rotation = csg.rotation;
  43820. this.scaling = csg.scaling;
  43821. this.rotationQuaternion = csg.rotationQuaternion;
  43822. return this;
  43823. };
  43824. // Build Raw mesh from CSG
  43825. // Coordinates here are in world space
  43826. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43827. var matrix = this.matrix.clone();
  43828. matrix.invert();
  43829. 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;
  43830. if (keepSubMeshes) {
  43831. // Sort Polygons, since subMeshes are indices range
  43832. polygons.sort(function (a, b) {
  43833. if (a.shared.meshId === b.shared.meshId) {
  43834. return a.shared.subMeshId - b.shared.subMeshId;
  43835. }
  43836. else {
  43837. return a.shared.meshId - b.shared.meshId;
  43838. }
  43839. });
  43840. }
  43841. for (var i = 0, il = polygons.length; i < il; i++) {
  43842. polygon = polygons[i];
  43843. // Building SubMeshes
  43844. if (!subMesh_dict[polygon.shared.meshId]) {
  43845. subMesh_dict[polygon.shared.meshId] = {};
  43846. }
  43847. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43848. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43849. indexStart: +Infinity,
  43850. indexEnd: -Infinity,
  43851. materialIndex: polygon.shared.materialIndex
  43852. };
  43853. }
  43854. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43855. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43856. polygonIndices[0] = 0;
  43857. polygonIndices[1] = j - 1;
  43858. polygonIndices[2] = j;
  43859. for (var k = 0; k < 3; k++) {
  43860. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43861. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43862. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43863. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43864. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43865. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43866. // Check if 2 points can be merged
  43867. if (!(typeof vertex_idx !== 'undefined' &&
  43868. normals[vertex_idx * 3] === localNormal.x &&
  43869. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43870. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43871. uvs[vertex_idx * 2] === uv.x &&
  43872. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43873. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43874. uvs.push(uv.x, uv.y);
  43875. normals.push(normal.x, normal.y, normal.z);
  43876. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43877. }
  43878. indices.push(vertex_idx);
  43879. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43880. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43881. currentIndex++;
  43882. }
  43883. }
  43884. }
  43885. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43886. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43887. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43888. mesh.setIndices(indices);
  43889. if (keepSubMeshes) {
  43890. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43891. var materialIndexOffset = 0, materialMaxIndex;
  43892. mesh.subMeshes = new Array();
  43893. for (var m in subMesh_dict) {
  43894. materialMaxIndex = -1;
  43895. for (var sm in subMesh_dict[m]) {
  43896. subMesh_obj = subMesh_dict[m][sm];
  43897. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43898. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43899. }
  43900. materialIndexOffset += ++materialMaxIndex;
  43901. }
  43902. }
  43903. return mesh;
  43904. };
  43905. // Build Mesh from CSG taking material and transforms into account
  43906. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  43907. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43908. mesh.material = material;
  43909. mesh.position.copyFrom(this.position);
  43910. mesh.rotation.copyFrom(this.rotation);
  43911. if (this.rotationQuaternion) {
  43912. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43913. }
  43914. mesh.scaling.copyFrom(this.scaling);
  43915. mesh.computeWorldMatrix(true);
  43916. return mesh;
  43917. };
  43918. return CSG;
  43919. }());
  43920. BABYLON.CSG = CSG;
  43921. })(BABYLON || (BABYLON = {}));
  43922. //# sourceMappingURL=babylon.csg.js.map
  43923. var BABYLON;
  43924. (function (BABYLON) {
  43925. var VRDistortionCorrectionPostProcess = (function (_super) {
  43926. __extends(VRDistortionCorrectionPostProcess, _super);
  43927. //ANY
  43928. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43929. var _this = this;
  43930. _super.call(this, name, "vrDistortionCorrection", [
  43931. 'LensCenter',
  43932. 'Scale',
  43933. 'ScaleIn',
  43934. 'HmdWarpParam'
  43935. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43936. this._isRightEye = isRightEye;
  43937. this._distortionFactors = vrMetrics.distortionK;
  43938. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43939. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43940. this.onSizeChangedObservable.add(function () {
  43941. _this.aspectRatio = _this.width * .5 / _this.height;
  43942. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43943. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43944. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43945. });
  43946. this.onApplyObservable.add(function (effect) {
  43947. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43948. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43949. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43950. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43951. });
  43952. }
  43953. return VRDistortionCorrectionPostProcess;
  43954. }(BABYLON.PostProcess));
  43955. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43956. })(BABYLON || (BABYLON = {}));
  43957. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  43958. // Mainly based on these 2 articles :
  43959. // 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
  43960. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43961. var BABYLON;
  43962. (function (BABYLON) {
  43963. (function (JoystickAxis) {
  43964. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43965. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43966. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  43967. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  43968. var JoystickAxis = BABYLON.JoystickAxis;
  43969. var VirtualJoystick = (function () {
  43970. function VirtualJoystick(leftJoystick) {
  43971. var _this = this;
  43972. if (leftJoystick) {
  43973. this._leftJoystick = true;
  43974. }
  43975. else {
  43976. this._leftJoystick = false;
  43977. }
  43978. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  43979. VirtualJoystick._globalJoystickIndex++;
  43980. // By default left & right arrow keys are moving the X
  43981. // and up & down keys are moving the Y
  43982. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43983. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43984. this.reverseLeftRight = false;
  43985. this.reverseUpDown = false;
  43986. // collections of pointers
  43987. this._touches = new BABYLON.StringDictionary();
  43988. this.deltaPosition = BABYLON.Vector3.Zero();
  43989. this._joystickSensibility = 25;
  43990. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43991. this._rotationSpeed = 25;
  43992. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  43993. this._rotateOnAxisRelativeToMesh = false;
  43994. this._onResize = function (evt) {
  43995. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43996. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43997. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  43998. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  43999. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44000. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44001. };
  44002. // injecting a canvas element on top of the canvas 3D game
  44003. if (!VirtualJoystick.vjCanvas) {
  44004. window.addEventListener("resize", this._onResize, false);
  44005. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44006. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44007. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44008. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44009. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44010. VirtualJoystick.vjCanvas.style.width = "100%";
  44011. VirtualJoystick.vjCanvas.style.height = "100%";
  44012. VirtualJoystick.vjCanvas.style.position = "absolute";
  44013. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44014. VirtualJoystick.vjCanvas.style.top = "0px";
  44015. VirtualJoystick.vjCanvas.style.left = "0px";
  44016. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44017. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44018. // Support for jQuery PEP polyfill
  44019. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44020. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44021. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44022. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44023. document.body.appendChild(VirtualJoystick.vjCanvas);
  44024. }
  44025. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44026. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44027. this.pressed = false;
  44028. // default joystick color
  44029. this._joystickColor = "cyan";
  44030. this._joystickPointerID = -1;
  44031. // current joystick position
  44032. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44033. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44034. // origin joystick position
  44035. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44036. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44037. this._onPointerDownHandlerRef = function (evt) {
  44038. _this._onPointerDown(evt);
  44039. };
  44040. this._onPointerMoveHandlerRef = function (evt) {
  44041. _this._onPointerMove(evt);
  44042. };
  44043. this._onPointerOutHandlerRef = function (evt) {
  44044. _this._onPointerUp(evt);
  44045. };
  44046. this._onPointerUpHandlerRef = function (evt) {
  44047. _this._onPointerUp(evt);
  44048. };
  44049. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44050. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44051. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44052. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44053. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44054. evt.preventDefault(); // Disables system menu
  44055. }, false);
  44056. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44057. }
  44058. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44059. this._joystickSensibility = newJoystickSensibility;
  44060. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44061. };
  44062. VirtualJoystick.prototype._onPointerDown = function (e) {
  44063. var positionOnScreenCondition;
  44064. e.preventDefault();
  44065. if (this._leftJoystick === true) {
  44066. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44067. }
  44068. else {
  44069. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44070. }
  44071. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44072. // First contact will be dedicated to the virtual joystick
  44073. this._joystickPointerID = e.pointerId;
  44074. this._joystickPointerStartPos.x = e.clientX;
  44075. this._joystickPointerStartPos.y = e.clientY;
  44076. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44077. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44078. this._deltaJoystickVector.x = 0;
  44079. this._deltaJoystickVector.y = 0;
  44080. this.pressed = true;
  44081. this._touches.add(e.pointerId.toString(), e);
  44082. }
  44083. else {
  44084. // You can only trigger the action buttons with a joystick declared
  44085. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44086. this._action();
  44087. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44088. }
  44089. }
  44090. };
  44091. VirtualJoystick.prototype._onPointerMove = function (e) {
  44092. // If the current pointer is the one associated to the joystick (first touch contact)
  44093. if (this._joystickPointerID == e.pointerId) {
  44094. this._joystickPointerPos.x = e.clientX;
  44095. this._joystickPointerPos.y = e.clientY;
  44096. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44097. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44098. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44099. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44100. switch (this._axisTargetedByLeftAndRight) {
  44101. case JoystickAxis.X:
  44102. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44103. break;
  44104. case JoystickAxis.Y:
  44105. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44106. break;
  44107. case JoystickAxis.Z:
  44108. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44109. break;
  44110. }
  44111. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44112. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44113. switch (this._axisTargetedByUpAndDown) {
  44114. case JoystickAxis.X:
  44115. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44116. break;
  44117. case JoystickAxis.Y:
  44118. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44119. break;
  44120. case JoystickAxis.Z:
  44121. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44122. break;
  44123. }
  44124. }
  44125. else {
  44126. var data = this._touches.get(e.pointerId.toString());
  44127. if (data) {
  44128. data.x = e.clientX;
  44129. data.y = e.clientY;
  44130. }
  44131. }
  44132. };
  44133. VirtualJoystick.prototype._onPointerUp = function (e) {
  44134. if (this._joystickPointerID == e.pointerId) {
  44135. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44136. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44137. this._joystickPointerID = -1;
  44138. this.pressed = false;
  44139. }
  44140. else {
  44141. var touch = this._touches.get(e.pointerId.toString());
  44142. if (touch) {
  44143. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44144. }
  44145. }
  44146. this._deltaJoystickVector.x = 0;
  44147. this._deltaJoystickVector.y = 0;
  44148. this._touches.remove(e.pointerId.toString());
  44149. };
  44150. /**
  44151. * Change the color of the virtual joystick
  44152. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44153. */
  44154. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44155. this._joystickColor = newColor;
  44156. };
  44157. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44158. this._action = action;
  44159. };
  44160. // Define which axis you'd like to control for left & right
  44161. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44162. switch (axis) {
  44163. case JoystickAxis.X:
  44164. case JoystickAxis.Y:
  44165. case JoystickAxis.Z:
  44166. this._axisTargetedByLeftAndRight = axis;
  44167. break;
  44168. default:
  44169. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44170. break;
  44171. }
  44172. };
  44173. // Define which axis you'd like to control for up & down
  44174. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44175. switch (axis) {
  44176. case JoystickAxis.X:
  44177. case JoystickAxis.Y:
  44178. case JoystickAxis.Z:
  44179. this._axisTargetedByUpAndDown = axis;
  44180. break;
  44181. default:
  44182. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44183. break;
  44184. }
  44185. };
  44186. VirtualJoystick.prototype._clearCanvas = function () {
  44187. if (this._leftJoystick) {
  44188. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44189. }
  44190. else {
  44191. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44192. }
  44193. };
  44194. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44195. var _this = this;
  44196. if (this.pressed) {
  44197. this._touches.forEach(function (touch) {
  44198. if (touch.pointerId === _this._joystickPointerID) {
  44199. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44200. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44201. VirtualJoystick.vjCanvasContext.beginPath();
  44202. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44203. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44204. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44205. VirtualJoystick.vjCanvasContext.stroke();
  44206. VirtualJoystick.vjCanvasContext.closePath();
  44207. VirtualJoystick.vjCanvasContext.beginPath();
  44208. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44209. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44210. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44211. VirtualJoystick.vjCanvasContext.stroke();
  44212. VirtualJoystick.vjCanvasContext.closePath();
  44213. VirtualJoystick.vjCanvasContext.beginPath();
  44214. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44215. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44216. VirtualJoystick.vjCanvasContext.stroke();
  44217. VirtualJoystick.vjCanvasContext.closePath();
  44218. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44219. }
  44220. else {
  44221. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44222. VirtualJoystick.vjCanvasContext.beginPath();
  44223. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44224. VirtualJoystick.vjCanvasContext.beginPath();
  44225. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44226. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44227. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44228. VirtualJoystick.vjCanvasContext.stroke();
  44229. VirtualJoystick.vjCanvasContext.closePath();
  44230. touch.prevX = touch.x;
  44231. touch.prevY = touch.y;
  44232. }
  44233. ;
  44234. });
  44235. }
  44236. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44237. };
  44238. VirtualJoystick.prototype.releaseCanvas = function () {
  44239. if (VirtualJoystick.vjCanvas) {
  44240. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44241. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44242. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44243. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44244. window.removeEventListener("resize", this._onResize);
  44245. document.body.removeChild(VirtualJoystick.vjCanvas);
  44246. VirtualJoystick.vjCanvas = null;
  44247. }
  44248. };
  44249. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44250. VirtualJoystick._globalJoystickIndex = 0;
  44251. return VirtualJoystick;
  44252. }());
  44253. BABYLON.VirtualJoystick = VirtualJoystick;
  44254. })(BABYLON || (BABYLON = {}));
  44255. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44256. var BABYLON;
  44257. (function (BABYLON) {
  44258. // We're mainly based on the logic defined into the FreeCamera code
  44259. var VirtualJoysticksCamera = (function (_super) {
  44260. __extends(VirtualJoysticksCamera, _super);
  44261. function VirtualJoysticksCamera(name, position, scene) {
  44262. _super.call(this, name, position, scene);
  44263. this.inputs.addVirtualJoystick();
  44264. }
  44265. VirtualJoysticksCamera.prototype.getClassName = function () {
  44266. return "VirtualJoysticksCamera";
  44267. };
  44268. return VirtualJoysticksCamera;
  44269. }(BABYLON.FreeCamera));
  44270. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44271. })(BABYLON || (BABYLON = {}));
  44272. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44273. var BABYLON;
  44274. (function (BABYLON) {
  44275. var FreeCameraVirtualJoystickInput = (function () {
  44276. function FreeCameraVirtualJoystickInput() {
  44277. }
  44278. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44279. return this._leftjoystick;
  44280. };
  44281. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44282. return this._rightjoystick;
  44283. };
  44284. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44285. if (this._leftjoystick) {
  44286. var camera = this.camera;
  44287. var speed = camera._computeLocalCameraSpeed() * 50;
  44288. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44289. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44290. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44291. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44292. if (!this._leftjoystick.pressed) {
  44293. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44294. }
  44295. if (!this._rightjoystick.pressed) {
  44296. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44297. }
  44298. }
  44299. };
  44300. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44301. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44302. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44303. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44304. this._leftjoystick.setJoystickSensibility(0.15);
  44305. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44306. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44307. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44308. this._rightjoystick.reverseUpDown = true;
  44309. this._rightjoystick.setJoystickSensibility(0.05);
  44310. this._rightjoystick.setJoystickColor("yellow");
  44311. };
  44312. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44313. this._leftjoystick.releaseCanvas();
  44314. this._rightjoystick.releaseCanvas();
  44315. };
  44316. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44317. return "FreeCameraVirtualJoystickInput";
  44318. };
  44319. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44320. return "virtualJoystick";
  44321. };
  44322. return FreeCameraVirtualJoystickInput;
  44323. }());
  44324. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44325. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44326. })(BABYLON || (BABYLON = {}));
  44327. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44328. var BABYLON;
  44329. (function (BABYLON) {
  44330. var AnaglyphPostProcess = (function (_super) {
  44331. __extends(AnaglyphPostProcess, _super);
  44332. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44333. var _this = this;
  44334. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  44335. this._passedProcess = rigCameras[0]._rigPostProcess;
  44336. this.onApplyObservable.add(function (effect) {
  44337. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44338. });
  44339. }
  44340. return AnaglyphPostProcess;
  44341. }(BABYLON.PostProcess));
  44342. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44343. })(BABYLON || (BABYLON = {}));
  44344. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44345. var BABYLON;
  44346. (function (BABYLON) {
  44347. var OutlineRenderer = (function () {
  44348. function OutlineRenderer(scene) {
  44349. this._scene = scene;
  44350. }
  44351. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44352. var _this = this;
  44353. if (useOverlay === void 0) { useOverlay = false; }
  44354. var scene = this._scene;
  44355. var engine = this._scene.getEngine();
  44356. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44357. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44358. return;
  44359. }
  44360. var mesh = subMesh.getRenderingMesh();
  44361. var material = subMesh.getMaterial();
  44362. engine.enableEffect(this._effect);
  44363. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44364. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44365. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44366. // Bones
  44367. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44368. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44369. }
  44370. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44371. // Alpha test
  44372. if (material && material.needAlphaTesting()) {
  44373. var alphaTexture = material.getAlphaTestTexture();
  44374. this._effect.setTexture("diffuseSampler", alphaTexture);
  44375. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44376. }
  44377. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44378. };
  44379. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44380. var defines = [];
  44381. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44382. var mesh = subMesh.getMesh();
  44383. var material = subMesh.getMaterial();
  44384. // Alpha test
  44385. if (material && material.needAlphaTesting()) {
  44386. defines.push("#define ALPHATEST");
  44387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44388. attribs.push(BABYLON.VertexBuffer.UVKind);
  44389. defines.push("#define UV1");
  44390. }
  44391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44392. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44393. defines.push("#define UV2");
  44394. }
  44395. }
  44396. // Bones
  44397. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44398. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44399. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44400. if (mesh.numBoneInfluencers > 4) {
  44401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44403. }
  44404. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44405. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44406. }
  44407. else {
  44408. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44409. }
  44410. // Instances
  44411. if (useInstances) {
  44412. defines.push("#define INSTANCES");
  44413. attribs.push("world0");
  44414. attribs.push("world1");
  44415. attribs.push("world2");
  44416. attribs.push("world3");
  44417. }
  44418. // Get correct effect
  44419. var join = defines.join("\n");
  44420. if (this._cachedDefines !== join) {
  44421. this._cachedDefines = join;
  44422. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44423. }
  44424. return this._effect.isReady();
  44425. };
  44426. return OutlineRenderer;
  44427. }());
  44428. BABYLON.OutlineRenderer = OutlineRenderer;
  44429. })(BABYLON || (BABYLON = {}));
  44430. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44431. var BABYLON;
  44432. (function (BABYLON) {
  44433. var MeshAssetTask = (function () {
  44434. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44435. this.name = name;
  44436. this.meshesNames = meshesNames;
  44437. this.rootUrl = rootUrl;
  44438. this.sceneFilename = sceneFilename;
  44439. this.isCompleted = false;
  44440. }
  44441. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44442. var _this = this;
  44443. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44444. _this.loadedMeshes = meshes;
  44445. _this.loadedParticleSystems = particleSystems;
  44446. _this.loadedSkeletons = skeletons;
  44447. _this.isCompleted = true;
  44448. if (_this.onSuccess) {
  44449. _this.onSuccess(_this);
  44450. }
  44451. onSuccess();
  44452. }, null, function () {
  44453. if (_this.onError) {
  44454. _this.onError(_this);
  44455. }
  44456. onError();
  44457. });
  44458. };
  44459. return MeshAssetTask;
  44460. }());
  44461. BABYLON.MeshAssetTask = MeshAssetTask;
  44462. var TextFileAssetTask = (function () {
  44463. function TextFileAssetTask(name, url) {
  44464. this.name = name;
  44465. this.url = url;
  44466. this.isCompleted = false;
  44467. }
  44468. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44469. var _this = this;
  44470. BABYLON.Tools.LoadFile(this.url, function (data) {
  44471. _this.text = data;
  44472. _this.isCompleted = true;
  44473. if (_this.onSuccess) {
  44474. _this.onSuccess(_this);
  44475. }
  44476. onSuccess();
  44477. }, null, scene.database, false, function () {
  44478. if (_this.onError) {
  44479. _this.onError(_this);
  44480. }
  44481. onError();
  44482. });
  44483. };
  44484. return TextFileAssetTask;
  44485. }());
  44486. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44487. var BinaryFileAssetTask = (function () {
  44488. function BinaryFileAssetTask(name, url) {
  44489. this.name = name;
  44490. this.url = url;
  44491. this.isCompleted = false;
  44492. }
  44493. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44494. var _this = this;
  44495. BABYLON.Tools.LoadFile(this.url, function (data) {
  44496. _this.data = data;
  44497. _this.isCompleted = true;
  44498. if (_this.onSuccess) {
  44499. _this.onSuccess(_this);
  44500. }
  44501. onSuccess();
  44502. }, null, scene.database, true, function () {
  44503. if (_this.onError) {
  44504. _this.onError(_this);
  44505. }
  44506. onError();
  44507. });
  44508. };
  44509. return BinaryFileAssetTask;
  44510. }());
  44511. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44512. var ImageAssetTask = (function () {
  44513. function ImageAssetTask(name, url) {
  44514. this.name = name;
  44515. this.url = url;
  44516. this.isCompleted = false;
  44517. }
  44518. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44519. var _this = this;
  44520. var img = new Image();
  44521. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44522. img.onload = function () {
  44523. _this.image = img;
  44524. _this.isCompleted = true;
  44525. if (_this.onSuccess) {
  44526. _this.onSuccess(_this);
  44527. }
  44528. onSuccess();
  44529. };
  44530. img.onerror = function () {
  44531. if (_this.onError) {
  44532. _this.onError(_this);
  44533. }
  44534. onError();
  44535. };
  44536. img.src = this.url;
  44537. };
  44538. return ImageAssetTask;
  44539. }());
  44540. BABYLON.ImageAssetTask = ImageAssetTask;
  44541. var TextureAssetTask = (function () {
  44542. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44543. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44544. this.name = name;
  44545. this.url = url;
  44546. this.noMipmap = noMipmap;
  44547. this.invertY = invertY;
  44548. this.samplingMode = samplingMode;
  44549. this.isCompleted = false;
  44550. }
  44551. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44552. var _this = this;
  44553. var onload = function () {
  44554. _this.isCompleted = true;
  44555. if (_this.onSuccess) {
  44556. _this.onSuccess(_this);
  44557. }
  44558. onSuccess();
  44559. };
  44560. var onerror = function () {
  44561. if (_this.onError) {
  44562. _this.onError(_this);
  44563. }
  44564. onError();
  44565. };
  44566. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44567. };
  44568. return TextureAssetTask;
  44569. }());
  44570. BABYLON.TextureAssetTask = TextureAssetTask;
  44571. var CubeTextureAssetTask = (function () {
  44572. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44573. this.name = name;
  44574. this.url = url;
  44575. this.extensions = extensions;
  44576. this.noMipmap = noMipmap;
  44577. this.files = files;
  44578. this.isCompleted = false;
  44579. }
  44580. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44581. var _this = this;
  44582. var onload = function () {
  44583. _this.isCompleted = true;
  44584. if (_this.onSuccess) {
  44585. _this.onSuccess(_this);
  44586. }
  44587. onSuccess();
  44588. };
  44589. var onerror = function () {
  44590. if (_this.onError) {
  44591. _this.onError(_this);
  44592. }
  44593. onError();
  44594. };
  44595. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44596. };
  44597. return CubeTextureAssetTask;
  44598. }());
  44599. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44600. var AssetsManager = (function () {
  44601. function AssetsManager(scene) {
  44602. this.tasks = new Array();
  44603. this.waitingTasksCount = 0;
  44604. this.useDefaultLoadingScreen = true;
  44605. this._scene = scene;
  44606. }
  44607. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44608. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44609. this.tasks.push(task);
  44610. return task;
  44611. };
  44612. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44613. var task = new TextFileAssetTask(taskName, url);
  44614. this.tasks.push(task);
  44615. return task;
  44616. };
  44617. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44618. var task = new BinaryFileAssetTask(taskName, url);
  44619. this.tasks.push(task);
  44620. return task;
  44621. };
  44622. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44623. var task = new ImageAssetTask(taskName, url);
  44624. this.tasks.push(task);
  44625. return task;
  44626. };
  44627. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44629. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44630. this.tasks.push(task);
  44631. return task;
  44632. };
  44633. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44634. this.waitingTasksCount--;
  44635. if (this.waitingTasksCount === 0) {
  44636. if (this.onFinish) {
  44637. this.onFinish(this.tasks);
  44638. }
  44639. this._scene.getEngine().hideLoadingUI();
  44640. }
  44641. };
  44642. AssetsManager.prototype._runTask = function (task) {
  44643. var _this = this;
  44644. task.run(this._scene, function () {
  44645. if (_this.onTaskSuccess) {
  44646. _this.onTaskSuccess(task);
  44647. }
  44648. _this._decreaseWaitingTasksCount();
  44649. }, function () {
  44650. if (_this.onTaskError) {
  44651. _this.onTaskError(task);
  44652. }
  44653. _this._decreaseWaitingTasksCount();
  44654. });
  44655. };
  44656. AssetsManager.prototype.reset = function () {
  44657. this.tasks = new Array();
  44658. return this;
  44659. };
  44660. AssetsManager.prototype.load = function () {
  44661. this.waitingTasksCount = this.tasks.length;
  44662. if (this.waitingTasksCount === 0) {
  44663. if (this.onFinish) {
  44664. this.onFinish(this.tasks);
  44665. }
  44666. return this;
  44667. }
  44668. if (this.useDefaultLoadingScreen) {
  44669. this._scene.getEngine().displayLoadingUI();
  44670. }
  44671. for (var index = 0; index < this.tasks.length; index++) {
  44672. var task = this.tasks[index];
  44673. this._runTask(task);
  44674. }
  44675. return this;
  44676. };
  44677. return AssetsManager;
  44678. }());
  44679. BABYLON.AssetsManager = AssetsManager;
  44680. })(BABYLON || (BABYLON = {}));
  44681. //# sourceMappingURL=babylon.assetsManager.js.map
  44682. var BABYLON;
  44683. (function (BABYLON) {
  44684. var VRCameraMetrics = (function () {
  44685. function VRCameraMetrics() {
  44686. this.compensateDistortion = true;
  44687. }
  44688. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44689. get: function () {
  44690. return this.hResolution / (2 * this.vResolution);
  44691. },
  44692. enumerable: true,
  44693. configurable: true
  44694. });
  44695. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44696. get: function () {
  44697. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44698. },
  44699. enumerable: true,
  44700. configurable: true
  44701. });
  44702. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44703. get: function () {
  44704. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44705. var h = (4 * meters) / this.hScreenSize;
  44706. return BABYLON.Matrix.Translation(h, 0, 0);
  44707. },
  44708. enumerable: true,
  44709. configurable: true
  44710. });
  44711. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44712. get: function () {
  44713. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44714. var h = (4 * meters) / this.hScreenSize;
  44715. return BABYLON.Matrix.Translation(-h, 0, 0);
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44721. get: function () {
  44722. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44723. },
  44724. enumerable: true,
  44725. configurable: true
  44726. });
  44727. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44728. get: function () {
  44729. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44730. },
  44731. enumerable: true,
  44732. configurable: true
  44733. });
  44734. VRCameraMetrics.GetDefault = function () {
  44735. var result = new VRCameraMetrics();
  44736. result.hResolution = 1280;
  44737. result.vResolution = 800;
  44738. result.hScreenSize = 0.149759993;
  44739. result.vScreenSize = 0.0935999975;
  44740. result.vScreenCenter = 0.0467999987,
  44741. result.eyeToScreenDistance = 0.0410000011;
  44742. result.lensSeparationDistance = 0.0635000020;
  44743. result.interpupillaryDistance = 0.0640000030;
  44744. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44745. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44746. result.postProcessScaleFactor = 1.714605507808412;
  44747. result.lensCenterOffset = 0.151976421;
  44748. return result;
  44749. };
  44750. return VRCameraMetrics;
  44751. }());
  44752. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44753. })(BABYLON || (BABYLON = {}));
  44754. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44755. var BABYLON;
  44756. (function (BABYLON) {
  44757. var WebVRFreeCamera = (function (_super) {
  44758. __extends(WebVRFreeCamera, _super);
  44759. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44760. var _this = this;
  44761. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44762. if (webVROptions === void 0) { webVROptions = {}; }
  44763. _super.call(this, name, position, scene);
  44764. this.webVROptions = webVROptions;
  44765. this._vrDevice = null;
  44766. this._cacheState = null;
  44767. this._vrEnabled = false;
  44768. this._attached = false;
  44769. //using the position provided as the current position offset
  44770. this._positionOffset = position;
  44771. //enable VR
  44772. this.getEngine().initWebVR();
  44773. if (!this.getEngine().vrDisplaysPromise) {
  44774. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44775. }
  44776. else {
  44777. //TODO get the metrics updated using the device's eye parameters!
  44778. //TODO also check that the device has the right capabilities!
  44779. this._frameData = new VRFrameData();
  44780. this.getEngine().vrDisplaysPromise.then(function (devices) {
  44781. if (devices.length > 0) {
  44782. _this._vrEnabled = true;
  44783. if (_this.webVROptions.displayName) {
  44784. var found = devices.some(function (device) {
  44785. if (device.displayName === _this.webVROptions.displayName) {
  44786. _this._vrDevice = device;
  44787. return true;
  44788. }
  44789. else {
  44790. return false;
  44791. }
  44792. });
  44793. if (!found) {
  44794. _this._vrDevice = devices[0];
  44795. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44796. }
  44797. }
  44798. else {
  44799. //choose the first one
  44800. _this._vrDevice = devices[0];
  44801. }
  44802. //reset the rig parameters.
  44803. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44804. if (_this._attached) {
  44805. _this.getEngine().enableVR(_this._vrDevice);
  44806. }
  44807. }
  44808. else {
  44809. BABYLON.Tools.Error("No WebVR devices found!");
  44810. }
  44811. });
  44812. }
  44813. this.rotationQuaternion = new BABYLON.Quaternion();
  44814. this._quaternionCache = new BABYLON.Quaternion();
  44815. }
  44816. WebVRFreeCamera.prototype._checkInputs = function () {
  44817. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44818. var currentPost = this._frameData.pose;
  44819. //make sure we have data
  44820. if (currentPost && currentPost.orientation) {
  44821. this._cacheState = currentPost;
  44822. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44823. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44824. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44825. //scale the position accordingly
  44826. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44827. //add the position offset
  44828. this.position.addInPlace(this._positionOffset);
  44829. }
  44830. }
  44831. }
  44832. _super.prototype._checkInputs.call(this);
  44833. };
  44834. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44835. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44836. this._attached = true;
  44837. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44838. if (this._vrEnabled) {
  44839. this.getEngine().enableVR(this._vrDevice);
  44840. }
  44841. };
  44842. WebVRFreeCamera.prototype.detachControl = function (element) {
  44843. _super.prototype.detachControl.call(this, element);
  44844. this._vrEnabled = false;
  44845. this._attached = false;
  44846. this.getEngine().disableVR();
  44847. };
  44848. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44849. //Backwards comp.
  44850. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44851. //this.getEngine().switchFullscreen(requestPointerlock);
  44852. };
  44853. WebVRFreeCamera.prototype.getClassName = function () {
  44854. return "WebVRFreeCamera";
  44855. };
  44856. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44857. //uses the vrDisplay's "resetPose()".
  44858. //pitch and roll won't be affected.
  44859. this._vrDevice.resetPose();
  44860. };
  44861. /**
  44862. *
  44863. * Set the position offset of the VR camera
  44864. * The offset will be added to the WebVR pose, after scaling it (if set).
  44865. *
  44866. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44867. *
  44868. * @memberOf WebVRFreeCamera
  44869. */
  44870. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44871. if (newPosition) {
  44872. this._positionOffset = newPosition;
  44873. }
  44874. else {
  44875. this._positionOffset.copyFrom(this.position);
  44876. }
  44877. };
  44878. return WebVRFreeCamera;
  44879. }(BABYLON.FreeCamera));
  44880. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44881. })(BABYLON || (BABYLON = {}));
  44882. //# sourceMappingURL=babylon.webVRCamera.js.map
  44883. var BABYLON;
  44884. (function (BABYLON) {
  44885. // Standard optimizations
  44886. var SceneOptimization = (function () {
  44887. function SceneOptimization(priority) {
  44888. if (priority === void 0) { priority = 0; }
  44889. this.priority = priority;
  44890. this.apply = function (scene) {
  44891. return true; // Return true if everything that can be done was applied
  44892. };
  44893. }
  44894. return SceneOptimization;
  44895. }());
  44896. BABYLON.SceneOptimization = SceneOptimization;
  44897. var TextureOptimization = (function (_super) {
  44898. __extends(TextureOptimization, _super);
  44899. function TextureOptimization(priority, maximumSize) {
  44900. var _this = this;
  44901. if (priority === void 0) { priority = 0; }
  44902. if (maximumSize === void 0) { maximumSize = 1024; }
  44903. _super.call(this, priority);
  44904. this.priority = priority;
  44905. this.maximumSize = maximumSize;
  44906. this.apply = function (scene) {
  44907. var allDone = true;
  44908. for (var index = 0; index < scene.textures.length; index++) {
  44909. var texture = scene.textures[index];
  44910. if (!texture.canRescale) {
  44911. continue;
  44912. }
  44913. var currentSize = texture.getSize();
  44914. var maxDimension = Math.max(currentSize.width, currentSize.height);
  44915. if (maxDimension > _this.maximumSize) {
  44916. texture.scale(0.5);
  44917. allDone = false;
  44918. }
  44919. }
  44920. return allDone;
  44921. };
  44922. }
  44923. return TextureOptimization;
  44924. }(SceneOptimization));
  44925. BABYLON.TextureOptimization = TextureOptimization;
  44926. var HardwareScalingOptimization = (function (_super) {
  44927. __extends(HardwareScalingOptimization, _super);
  44928. function HardwareScalingOptimization(priority, maximumScale) {
  44929. var _this = this;
  44930. if (priority === void 0) { priority = 0; }
  44931. if (maximumScale === void 0) { maximumScale = 2; }
  44932. _super.call(this, priority);
  44933. this.priority = priority;
  44934. this.maximumScale = maximumScale;
  44935. this._currentScale = 1;
  44936. this.apply = function (scene) {
  44937. _this._currentScale++;
  44938. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  44939. return _this._currentScale >= _this.maximumScale;
  44940. };
  44941. }
  44942. return HardwareScalingOptimization;
  44943. }(SceneOptimization));
  44944. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44945. var ShadowsOptimization = (function (_super) {
  44946. __extends(ShadowsOptimization, _super);
  44947. function ShadowsOptimization() {
  44948. _super.apply(this, arguments);
  44949. this.apply = function (scene) {
  44950. scene.shadowsEnabled = false;
  44951. return true;
  44952. };
  44953. }
  44954. return ShadowsOptimization;
  44955. }(SceneOptimization));
  44956. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44957. var PostProcessesOptimization = (function (_super) {
  44958. __extends(PostProcessesOptimization, _super);
  44959. function PostProcessesOptimization() {
  44960. _super.apply(this, arguments);
  44961. this.apply = function (scene) {
  44962. scene.postProcessesEnabled = false;
  44963. return true;
  44964. };
  44965. }
  44966. return PostProcessesOptimization;
  44967. }(SceneOptimization));
  44968. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  44969. var LensFlaresOptimization = (function (_super) {
  44970. __extends(LensFlaresOptimization, _super);
  44971. function LensFlaresOptimization() {
  44972. _super.apply(this, arguments);
  44973. this.apply = function (scene) {
  44974. scene.lensFlaresEnabled = false;
  44975. return true;
  44976. };
  44977. }
  44978. return LensFlaresOptimization;
  44979. }(SceneOptimization));
  44980. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  44981. var ParticlesOptimization = (function (_super) {
  44982. __extends(ParticlesOptimization, _super);
  44983. function ParticlesOptimization() {
  44984. _super.apply(this, arguments);
  44985. this.apply = function (scene) {
  44986. scene.particlesEnabled = false;
  44987. return true;
  44988. };
  44989. }
  44990. return ParticlesOptimization;
  44991. }(SceneOptimization));
  44992. BABYLON.ParticlesOptimization = ParticlesOptimization;
  44993. var RenderTargetsOptimization = (function (_super) {
  44994. __extends(RenderTargetsOptimization, _super);
  44995. function RenderTargetsOptimization() {
  44996. _super.apply(this, arguments);
  44997. this.apply = function (scene) {
  44998. scene.renderTargetsEnabled = false;
  44999. return true;
  45000. };
  45001. }
  45002. return RenderTargetsOptimization;
  45003. }(SceneOptimization));
  45004. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45005. var MergeMeshesOptimization = (function (_super) {
  45006. __extends(MergeMeshesOptimization, _super);
  45007. function MergeMeshesOptimization() {
  45008. var _this = this;
  45009. _super.apply(this, arguments);
  45010. this._canBeMerged = function (abstractMesh) {
  45011. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45012. return false;
  45013. }
  45014. var mesh = abstractMesh;
  45015. if (!mesh.isVisible || !mesh.isEnabled()) {
  45016. return false;
  45017. }
  45018. if (mesh.instances.length > 0) {
  45019. return false;
  45020. }
  45021. if (mesh.skeleton || mesh.hasLODLevels) {
  45022. return false;
  45023. }
  45024. if (mesh.parent) {
  45025. return false;
  45026. }
  45027. return true;
  45028. };
  45029. this.apply = function (scene, updateSelectionTree) {
  45030. var globalPool = scene.meshes.slice(0);
  45031. var globalLength = globalPool.length;
  45032. for (var index = 0; index < globalLength; index++) {
  45033. var currentPool = new Array();
  45034. var current = globalPool[index];
  45035. // Checks
  45036. if (!_this._canBeMerged(current)) {
  45037. continue;
  45038. }
  45039. currentPool.push(current);
  45040. // Find compatible meshes
  45041. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45042. var otherMesh = globalPool[subIndex];
  45043. if (!_this._canBeMerged(otherMesh)) {
  45044. continue;
  45045. }
  45046. if (otherMesh.material !== current.material) {
  45047. continue;
  45048. }
  45049. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45050. continue;
  45051. }
  45052. currentPool.push(otherMesh);
  45053. globalLength--;
  45054. globalPool.splice(subIndex, 1);
  45055. subIndex--;
  45056. }
  45057. if (currentPool.length < 2) {
  45058. continue;
  45059. }
  45060. // Merge meshes
  45061. BABYLON.Mesh.MergeMeshes(currentPool);
  45062. }
  45063. if (updateSelectionTree != undefined) {
  45064. if (updateSelectionTree) {
  45065. scene.createOrUpdateSelectionOctree();
  45066. }
  45067. }
  45068. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45069. scene.createOrUpdateSelectionOctree();
  45070. }
  45071. return true;
  45072. };
  45073. }
  45074. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45075. get: function () {
  45076. return MergeMeshesOptimization._UpdateSelectionTree;
  45077. },
  45078. set: function (value) {
  45079. MergeMeshesOptimization._UpdateSelectionTree = value;
  45080. },
  45081. enumerable: true,
  45082. configurable: true
  45083. });
  45084. MergeMeshesOptimization._UpdateSelectionTree = false;
  45085. return MergeMeshesOptimization;
  45086. }(SceneOptimization));
  45087. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45088. // Options
  45089. var SceneOptimizerOptions = (function () {
  45090. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45091. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45092. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45093. this.targetFrameRate = targetFrameRate;
  45094. this.trackerDuration = trackerDuration;
  45095. this.optimizations = new Array();
  45096. }
  45097. SceneOptimizerOptions.LowDegradationAllowed = 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, 1024));
  45110. return result;
  45111. };
  45112. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45113. var result = new SceneOptimizerOptions(targetFrameRate);
  45114. var priority = 0;
  45115. result.optimizations.push(new MergeMeshesOptimization(priority));
  45116. result.optimizations.push(new ShadowsOptimization(priority));
  45117. result.optimizations.push(new LensFlaresOptimization(priority));
  45118. // Next priority
  45119. priority++;
  45120. result.optimizations.push(new PostProcessesOptimization(priority));
  45121. result.optimizations.push(new ParticlesOptimization(priority));
  45122. // Next priority
  45123. priority++;
  45124. result.optimizations.push(new TextureOptimization(priority, 512));
  45125. // Next priority
  45126. priority++;
  45127. result.optimizations.push(new RenderTargetsOptimization(priority));
  45128. // Next priority
  45129. priority++;
  45130. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45131. return result;
  45132. };
  45133. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45134. var result = new SceneOptimizerOptions(targetFrameRate);
  45135. var priority = 0;
  45136. result.optimizations.push(new MergeMeshesOptimization(priority));
  45137. result.optimizations.push(new ShadowsOptimization(priority));
  45138. result.optimizations.push(new LensFlaresOptimization(priority));
  45139. // Next priority
  45140. priority++;
  45141. result.optimizations.push(new PostProcessesOptimization(priority));
  45142. result.optimizations.push(new ParticlesOptimization(priority));
  45143. // Next priority
  45144. priority++;
  45145. result.optimizations.push(new TextureOptimization(priority, 256));
  45146. // Next priority
  45147. priority++;
  45148. result.optimizations.push(new RenderTargetsOptimization(priority));
  45149. // Next priority
  45150. priority++;
  45151. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45152. return result;
  45153. };
  45154. return SceneOptimizerOptions;
  45155. }());
  45156. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45157. // Scene optimizer tool
  45158. var SceneOptimizer = (function () {
  45159. function SceneOptimizer() {
  45160. }
  45161. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45162. // TODO: add an epsilon
  45163. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45164. if (onSuccess) {
  45165. onSuccess();
  45166. }
  45167. return;
  45168. }
  45169. // Apply current level of optimizations
  45170. var allDone = true;
  45171. var noOptimizationApplied = true;
  45172. for (var index = 0; index < options.optimizations.length; index++) {
  45173. var optimization = options.optimizations[index];
  45174. if (optimization.priority === currentPriorityLevel) {
  45175. noOptimizationApplied = false;
  45176. allDone = allDone && optimization.apply(scene);
  45177. }
  45178. }
  45179. // If no optimization was applied, this is a failure :(
  45180. if (noOptimizationApplied) {
  45181. if (onFailure) {
  45182. onFailure();
  45183. }
  45184. return;
  45185. }
  45186. // If all optimizations were done, move to next level
  45187. if (allDone) {
  45188. currentPriorityLevel++;
  45189. }
  45190. // Let's the system running for a specific amount of time before checking FPS
  45191. scene.executeWhenReady(function () {
  45192. setTimeout(function () {
  45193. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45194. }, options.trackerDuration);
  45195. });
  45196. };
  45197. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45198. if (!options) {
  45199. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45200. }
  45201. // Let's the system running for a specific amount of time before checking FPS
  45202. scene.executeWhenReady(function () {
  45203. setTimeout(function () {
  45204. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45205. }, options.trackerDuration);
  45206. });
  45207. };
  45208. return SceneOptimizer;
  45209. }());
  45210. BABYLON.SceneOptimizer = SceneOptimizer;
  45211. })(BABYLON || (BABYLON = {}));
  45212. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45213. var BABYLON;
  45214. (function (BABYLON) {
  45215. var Internals;
  45216. (function (Internals) {
  45217. var MeshLODLevel = (function () {
  45218. function MeshLODLevel(distance, mesh) {
  45219. this.distance = distance;
  45220. this.mesh = mesh;
  45221. }
  45222. return MeshLODLevel;
  45223. }());
  45224. Internals.MeshLODLevel = MeshLODLevel;
  45225. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45226. })(BABYLON || (BABYLON = {}));
  45227. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45228. var BABYLON;
  45229. (function (BABYLON) {
  45230. var RawTexture = (function (_super) {
  45231. __extends(RawTexture, _super);
  45232. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45233. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45234. if (invertY === void 0) { invertY = false; }
  45235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45236. _super.call(this, null, scene, !generateMipMaps, invertY);
  45237. this.format = format;
  45238. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45239. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45240. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45241. }
  45242. RawTexture.prototype.update = function (data) {
  45243. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45244. };
  45245. // Statics
  45246. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45247. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45248. if (invertY === void 0) { invertY = false; }
  45249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45250. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45251. };
  45252. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45253. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45254. if (invertY === void 0) { invertY = false; }
  45255. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45256. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45257. };
  45258. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45259. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45260. if (invertY === void 0) { invertY = false; }
  45261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45262. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45263. };
  45264. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45265. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45266. if (invertY === void 0) { invertY = false; }
  45267. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45268. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45269. };
  45270. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45271. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45272. if (invertY === void 0) { invertY = false; }
  45273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45274. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45275. };
  45276. return RawTexture;
  45277. }(BABYLON.Texture));
  45278. BABYLON.RawTexture = RawTexture;
  45279. })(BABYLON || (BABYLON = {}));
  45280. //# sourceMappingURL=babylon.rawTexture.js.map
  45281. var BABYLON;
  45282. (function (BABYLON) {
  45283. var IndexedVector2 = (function (_super) {
  45284. __extends(IndexedVector2, _super);
  45285. function IndexedVector2(original, index) {
  45286. _super.call(this, original.x, original.y);
  45287. this.index = index;
  45288. }
  45289. return IndexedVector2;
  45290. }(BABYLON.Vector2));
  45291. var PolygonPoints = (function () {
  45292. function PolygonPoints() {
  45293. this.elements = new Array();
  45294. }
  45295. PolygonPoints.prototype.add = function (originalPoints) {
  45296. var _this = this;
  45297. var result = new Array();
  45298. originalPoints.forEach(function (point) {
  45299. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45300. var newPoint = new IndexedVector2(point, _this.elements.length);
  45301. result.push(newPoint);
  45302. _this.elements.push(newPoint);
  45303. }
  45304. });
  45305. return result;
  45306. };
  45307. PolygonPoints.prototype.computeBounds = function () {
  45308. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45309. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45310. this.elements.forEach(function (point) {
  45311. // x
  45312. if (point.x < lmin.x) {
  45313. lmin.x = point.x;
  45314. }
  45315. else if (point.x > lmax.x) {
  45316. lmax.x = point.x;
  45317. }
  45318. // y
  45319. if (point.y < lmin.y) {
  45320. lmin.y = point.y;
  45321. }
  45322. else if (point.y > lmax.y) {
  45323. lmax.y = point.y;
  45324. }
  45325. });
  45326. return {
  45327. min: lmin,
  45328. max: lmax,
  45329. width: lmax.x - lmin.x,
  45330. height: lmax.y - lmin.y
  45331. };
  45332. };
  45333. return PolygonPoints;
  45334. }());
  45335. var Polygon = (function () {
  45336. function Polygon() {
  45337. }
  45338. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45339. return [
  45340. new BABYLON.Vector2(xmin, ymin),
  45341. new BABYLON.Vector2(xmax, ymin),
  45342. new BABYLON.Vector2(xmax, ymax),
  45343. new BABYLON.Vector2(xmin, ymax)
  45344. ];
  45345. };
  45346. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45347. if (cx === void 0) { cx = 0; }
  45348. if (cy === void 0) { cy = 0; }
  45349. if (numberOfSides === void 0) { numberOfSides = 32; }
  45350. var result = new Array();
  45351. var angle = 0;
  45352. var increment = (Math.PI * 2) / numberOfSides;
  45353. for (var i = 0; i < numberOfSides; i++) {
  45354. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45355. angle -= increment;
  45356. }
  45357. return result;
  45358. };
  45359. Polygon.Parse = function (input) {
  45360. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45361. var i, result = [];
  45362. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45363. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45364. }
  45365. return result;
  45366. };
  45367. Polygon.StartingAt = function (x, y) {
  45368. return BABYLON.Path2.StartingAt(x, y);
  45369. };
  45370. return Polygon;
  45371. }());
  45372. BABYLON.Polygon = Polygon;
  45373. var PolygonMeshBuilder = (function () {
  45374. function PolygonMeshBuilder(name, contours, scene) {
  45375. this._points = new PolygonPoints();
  45376. this._outlinepoints = new PolygonPoints();
  45377. this._holes = [];
  45378. this._epoints = new Array();
  45379. this._eholes = new Array();
  45380. this._name = name;
  45381. this._scene = scene;
  45382. var points;
  45383. if (contours instanceof BABYLON.Path2) {
  45384. points = contours.getPoints();
  45385. }
  45386. else {
  45387. points = contours;
  45388. }
  45389. this._addToepoint(points);
  45390. this._points.add(points);
  45391. this._outlinepoints.add(points);
  45392. }
  45393. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45394. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45395. var p = points_1[_i];
  45396. this._epoints.push(p.x, p.y);
  45397. }
  45398. };
  45399. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45400. this._points.add(hole);
  45401. var holepoints = new PolygonPoints();
  45402. holepoints.add(hole);
  45403. this._holes.push(holepoints);
  45404. this._eholes.push(this._epoints.length / 2);
  45405. this._addToepoint(hole);
  45406. return this;
  45407. };
  45408. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45409. var _this = this;
  45410. if (updatable === void 0) { updatable = false; }
  45411. var result = new BABYLON.Mesh(this._name, this._scene);
  45412. var normals = [];
  45413. var positions = [];
  45414. var uvs = [];
  45415. var bounds = this._points.computeBounds();
  45416. this._points.elements.forEach(function (p) {
  45417. normals.push(0, 1.0, 0);
  45418. positions.push(p.x, 0, p.y);
  45419. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45420. });
  45421. var indices = [];
  45422. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45423. for (var i = 0; i < res.length; i++) {
  45424. indices.push(res[i]);
  45425. }
  45426. if (depth > 0) {
  45427. var positionscount = (positions.length / 3); //get the current pointcount
  45428. this._points.elements.forEach(function (p) {
  45429. normals.push(0, -1.0, 0);
  45430. positions.push(p.x, -depth, p.y);
  45431. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45432. });
  45433. var totalCount = indices.length;
  45434. for (var i = 0; i < totalCount; i += 3) {
  45435. var i0 = indices[i + 0];
  45436. var i1 = indices[i + 1];
  45437. var i2 = indices[i + 2];
  45438. indices.push(i2 + positionscount);
  45439. indices.push(i1 + positionscount);
  45440. indices.push(i0 + positionscount);
  45441. }
  45442. //Add the sides
  45443. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45444. this._holes.forEach(function (hole) {
  45445. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45446. });
  45447. }
  45448. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45449. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45450. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45451. result.setIndices(indices);
  45452. return result;
  45453. };
  45454. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45455. var StartIndex = positions.length / 3;
  45456. var ulength = 0;
  45457. for (var i = 0; i < points.elements.length; i++) {
  45458. var p = points.elements[i];
  45459. var p1;
  45460. if ((i + 1) > points.elements.length - 1) {
  45461. p1 = points.elements[0];
  45462. }
  45463. else {
  45464. p1 = points.elements[i + 1];
  45465. }
  45466. positions.push(p.x, 0, p.y);
  45467. positions.push(p.x, -depth, p.y);
  45468. positions.push(p1.x, 0, p1.y);
  45469. positions.push(p1.x, -depth, p1.y);
  45470. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45471. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45472. var v3 = v2.subtract(v1);
  45473. var v4 = new BABYLON.Vector3(0, 1, 0);
  45474. var vn = BABYLON.Vector3.Cross(v3, v4);
  45475. vn = vn.normalize();
  45476. uvs.push(ulength / bounds.width, 0);
  45477. uvs.push(ulength / bounds.width, 1);
  45478. ulength += v3.length();
  45479. uvs.push((ulength / bounds.width), 0);
  45480. uvs.push((ulength / bounds.width), 1);
  45481. if (!flip) {
  45482. normals.push(-vn.x, -vn.y, -vn.z);
  45483. normals.push(-vn.x, -vn.y, -vn.z);
  45484. normals.push(-vn.x, -vn.y, -vn.z);
  45485. normals.push(-vn.x, -vn.y, -vn.z);
  45486. indices.push(StartIndex);
  45487. indices.push(StartIndex + 1);
  45488. indices.push(StartIndex + 2);
  45489. indices.push(StartIndex + 1);
  45490. indices.push(StartIndex + 3);
  45491. indices.push(StartIndex + 2);
  45492. }
  45493. else {
  45494. normals.push(vn.x, vn.y, vn.z);
  45495. normals.push(vn.x, vn.y, vn.z);
  45496. normals.push(vn.x, vn.y, vn.z);
  45497. normals.push(vn.x, vn.y, vn.z);
  45498. indices.push(StartIndex);
  45499. indices.push(StartIndex + 2);
  45500. indices.push(StartIndex + 1);
  45501. indices.push(StartIndex + 1);
  45502. indices.push(StartIndex + 2);
  45503. indices.push(StartIndex + 3);
  45504. }
  45505. StartIndex += 4;
  45506. }
  45507. ;
  45508. };
  45509. return PolygonMeshBuilder;
  45510. }());
  45511. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45512. })(BABYLON || (BABYLON = {}));
  45513. //# sourceMappingURL=babylon.polygonMesh.js.map
  45514. var BABYLON;
  45515. (function (BABYLON) {
  45516. var Octree = (function () {
  45517. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45518. if (maxDepth === void 0) { maxDepth = 2; }
  45519. this.maxDepth = maxDepth;
  45520. this.dynamicContent = new Array();
  45521. this._maxBlockCapacity = maxBlockCapacity || 64;
  45522. this._selectionContent = new BABYLON.SmartArray(1024);
  45523. this._creationFunc = creationFunc;
  45524. }
  45525. // Methods
  45526. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45527. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45528. };
  45529. Octree.prototype.addMesh = function (entry) {
  45530. for (var index = 0; index < this.blocks.length; index++) {
  45531. var block = this.blocks[index];
  45532. block.addEntry(entry);
  45533. }
  45534. };
  45535. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45536. this._selectionContent.reset();
  45537. for (var index = 0; index < this.blocks.length; index++) {
  45538. var block = this.blocks[index];
  45539. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45540. }
  45541. if (allowDuplicate) {
  45542. this._selectionContent.concat(this.dynamicContent);
  45543. }
  45544. else {
  45545. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45546. }
  45547. return this._selectionContent;
  45548. };
  45549. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45550. this._selectionContent.reset();
  45551. for (var index = 0; index < this.blocks.length; index++) {
  45552. var block = this.blocks[index];
  45553. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45554. }
  45555. if (allowDuplicate) {
  45556. this._selectionContent.concat(this.dynamicContent);
  45557. }
  45558. else {
  45559. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45560. }
  45561. return this._selectionContent;
  45562. };
  45563. Octree.prototype.intersectsRay = function (ray) {
  45564. this._selectionContent.reset();
  45565. for (var index = 0; index < this.blocks.length; index++) {
  45566. var block = this.blocks[index];
  45567. block.intersectsRay(ray, this._selectionContent);
  45568. }
  45569. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45570. return this._selectionContent;
  45571. };
  45572. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45573. target.blocks = new Array();
  45574. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45575. // Segmenting space
  45576. for (var x = 0; x < 2; x++) {
  45577. for (var y = 0; y < 2; y++) {
  45578. for (var z = 0; z < 2; z++) {
  45579. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45580. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45581. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45582. block.addEntries(entries);
  45583. target.blocks.push(block);
  45584. }
  45585. }
  45586. }
  45587. };
  45588. Octree.CreationFuncForMeshes = function (entry, block) {
  45589. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45590. block.entries.push(entry);
  45591. }
  45592. };
  45593. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45594. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45595. block.entries.push(entry);
  45596. }
  45597. };
  45598. return Octree;
  45599. }());
  45600. BABYLON.Octree = Octree;
  45601. })(BABYLON || (BABYLON = {}));
  45602. //# sourceMappingURL=babylon.octree.js.map
  45603. var BABYLON;
  45604. (function (BABYLON) {
  45605. var OctreeBlock = (function () {
  45606. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45607. this.entries = new Array();
  45608. this._boundingVectors = new Array();
  45609. this._capacity = capacity;
  45610. this._depth = depth;
  45611. this._maxDepth = maxDepth;
  45612. this._creationFunc = creationFunc;
  45613. this._minPoint = minPoint;
  45614. this._maxPoint = maxPoint;
  45615. this._boundingVectors.push(minPoint.clone());
  45616. this._boundingVectors.push(maxPoint.clone());
  45617. this._boundingVectors.push(minPoint.clone());
  45618. this._boundingVectors[2].x = maxPoint.x;
  45619. this._boundingVectors.push(minPoint.clone());
  45620. this._boundingVectors[3].y = maxPoint.y;
  45621. this._boundingVectors.push(minPoint.clone());
  45622. this._boundingVectors[4].z = maxPoint.z;
  45623. this._boundingVectors.push(maxPoint.clone());
  45624. this._boundingVectors[5].z = minPoint.z;
  45625. this._boundingVectors.push(maxPoint.clone());
  45626. this._boundingVectors[6].x = minPoint.x;
  45627. this._boundingVectors.push(maxPoint.clone());
  45628. this._boundingVectors[7].y = minPoint.y;
  45629. }
  45630. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45631. // Property
  45632. get: function () {
  45633. return this._capacity;
  45634. },
  45635. enumerable: true,
  45636. configurable: true
  45637. });
  45638. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45639. get: function () {
  45640. return this._minPoint;
  45641. },
  45642. enumerable: true,
  45643. configurable: true
  45644. });
  45645. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45646. get: function () {
  45647. return this._maxPoint;
  45648. },
  45649. enumerable: true,
  45650. configurable: true
  45651. });
  45652. // Methods
  45653. OctreeBlock.prototype.addEntry = function (entry) {
  45654. if (this.blocks) {
  45655. for (var index = 0; index < this.blocks.length; index++) {
  45656. var block = this.blocks[index];
  45657. block.addEntry(entry);
  45658. }
  45659. return;
  45660. }
  45661. this._creationFunc(entry, this);
  45662. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45663. this.createInnerBlocks();
  45664. }
  45665. };
  45666. OctreeBlock.prototype.addEntries = function (entries) {
  45667. for (var index = 0; index < entries.length; index++) {
  45668. var mesh = entries[index];
  45669. this.addEntry(mesh);
  45670. }
  45671. };
  45672. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45673. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45674. if (this.blocks) {
  45675. for (var index = 0; index < this.blocks.length; index++) {
  45676. var block = this.blocks[index];
  45677. block.select(frustumPlanes, selection, allowDuplicate);
  45678. }
  45679. return;
  45680. }
  45681. if (allowDuplicate) {
  45682. selection.concat(this.entries);
  45683. }
  45684. else {
  45685. selection.concatWithNoDuplicate(this.entries);
  45686. }
  45687. }
  45688. };
  45689. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45690. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45691. if (this.blocks) {
  45692. for (var index = 0; index < this.blocks.length; index++) {
  45693. var block = this.blocks[index];
  45694. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45695. }
  45696. return;
  45697. }
  45698. if (allowDuplicate) {
  45699. selection.concat(this.entries);
  45700. }
  45701. else {
  45702. selection.concatWithNoDuplicate(this.entries);
  45703. }
  45704. }
  45705. };
  45706. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45707. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45708. if (this.blocks) {
  45709. for (var index = 0; index < this.blocks.length; index++) {
  45710. var block = this.blocks[index];
  45711. block.intersectsRay(ray, selection);
  45712. }
  45713. return;
  45714. }
  45715. selection.concatWithNoDuplicate(this.entries);
  45716. }
  45717. };
  45718. OctreeBlock.prototype.createInnerBlocks = function () {
  45719. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45720. };
  45721. return OctreeBlock;
  45722. }());
  45723. BABYLON.OctreeBlock = OctreeBlock;
  45724. })(BABYLON || (BABYLON = {}));
  45725. //# sourceMappingURL=babylon.octreeBlock.js.map
  45726. var BABYLON;
  45727. (function (BABYLON) {
  45728. var BlurPostProcess = (function (_super) {
  45729. __extends(BlurPostProcess, _super);
  45730. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45731. var _this = this;
  45732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45733. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  45734. this.direction = direction;
  45735. this.blurWidth = blurWidth;
  45736. this.onApplyObservable.add(function (effect) {
  45737. effect.setFloat2("screenSize", _this.width, _this.height);
  45738. effect.setVector2("direction", _this.direction);
  45739. effect.setFloat("blurWidth", _this.blurWidth);
  45740. });
  45741. }
  45742. return BlurPostProcess;
  45743. }(BABYLON.PostProcess));
  45744. BABYLON.BlurPostProcess = BlurPostProcess;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. var RefractionPostProcess = (function (_super) {
  45750. __extends(RefractionPostProcess, _super);
  45751. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45752. var _this = this;
  45753. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  45754. this.color = color;
  45755. this.depth = depth;
  45756. this.colorLevel = colorLevel;
  45757. this.onActivateObservable.add(function (cam) {
  45758. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45759. });
  45760. this.onApplyObservable.add(function (effect) {
  45761. effect.setColor3("baseColor", _this.color);
  45762. effect.setFloat("depth", _this.depth);
  45763. effect.setFloat("colorLevel", _this.colorLevel);
  45764. effect.setTexture("refractionSampler", _this._refRexture);
  45765. });
  45766. }
  45767. // Methods
  45768. RefractionPostProcess.prototype.dispose = function (camera) {
  45769. if (this._refRexture) {
  45770. this._refRexture.dispose();
  45771. }
  45772. _super.prototype.dispose.call(this, camera);
  45773. };
  45774. return RefractionPostProcess;
  45775. }(BABYLON.PostProcess));
  45776. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45777. })(BABYLON || (BABYLON = {}));
  45778. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45779. var BABYLON;
  45780. (function (BABYLON) {
  45781. var BlackAndWhitePostProcess = (function (_super) {
  45782. __extends(BlackAndWhitePostProcess, _super);
  45783. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45784. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  45785. }
  45786. return BlackAndWhitePostProcess;
  45787. }(BABYLON.PostProcess));
  45788. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45789. })(BABYLON || (BABYLON = {}));
  45790. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45791. var BABYLON;
  45792. (function (BABYLON) {
  45793. var ConvolutionPostProcess = (function (_super) {
  45794. __extends(ConvolutionPostProcess, _super);
  45795. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45796. var _this = this;
  45797. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  45798. this.kernel = kernel;
  45799. this.onApply = function (effect) {
  45800. effect.setFloat2("screenSize", _this.width, _this.height);
  45801. effect.setArray("kernel", _this.kernel);
  45802. };
  45803. }
  45804. // Statics
  45805. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45806. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45807. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45808. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45809. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45810. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45811. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45812. return ConvolutionPostProcess;
  45813. }(BABYLON.PostProcess));
  45814. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45815. })(BABYLON || (BABYLON = {}));
  45816. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45817. var BABYLON;
  45818. (function (BABYLON) {
  45819. var FilterPostProcess = (function (_super) {
  45820. __extends(FilterPostProcess, _super);
  45821. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45822. var _this = this;
  45823. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  45824. this.kernelMatrix = kernelMatrix;
  45825. this.onApply = function (effect) {
  45826. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45827. };
  45828. }
  45829. return FilterPostProcess;
  45830. }(BABYLON.PostProcess));
  45831. BABYLON.FilterPostProcess = FilterPostProcess;
  45832. })(BABYLON || (BABYLON = {}));
  45833. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45834. var BABYLON;
  45835. (function (BABYLON) {
  45836. var FxaaPostProcess = (function (_super) {
  45837. __extends(FxaaPostProcess, _super);
  45838. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45839. var _this = this;
  45840. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  45841. this.onSizeChangedObservable.add(function () {
  45842. _this.texelWidth = 1.0 / _this.width;
  45843. _this.texelHeight = 1.0 / _this.height;
  45844. });
  45845. this.onApplyObservable.add(function (effect) {
  45846. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45847. });
  45848. }
  45849. return FxaaPostProcess;
  45850. }(BABYLON.PostProcess));
  45851. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45852. })(BABYLON || (BABYLON = {}));
  45853. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45854. var BABYLON;
  45855. (function (BABYLON) {
  45856. var StereoscopicInterlacePostProcess = (function (_super) {
  45857. __extends(StereoscopicInterlacePostProcess, _super);
  45858. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45859. var _this = this;
  45860. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  45861. this._passedProcess = rigCameras[0]._rigPostProcess;
  45862. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  45863. this.onSizeChangedObservable.add(function () {
  45864. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45865. });
  45866. this.onApplyObservable.add(function (effect) {
  45867. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45868. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45869. });
  45870. }
  45871. return StereoscopicInterlacePostProcess;
  45872. }(BABYLON.PostProcess));
  45873. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45874. })(BABYLON || (BABYLON = {}));
  45875. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  45876. var BABYLON;
  45877. (function (BABYLON) {
  45878. var LensFlare = (function () {
  45879. function LensFlare(size, position, color, imgUrl, system) {
  45880. this.size = size;
  45881. this.position = position;
  45882. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45883. this.dispose = function () {
  45884. if (this.texture) {
  45885. this.texture.dispose();
  45886. }
  45887. // Remove from scene
  45888. var index = this._system.lensFlares.indexOf(this);
  45889. this._system.lensFlares.splice(index, 1);
  45890. };
  45891. this.color = color || new BABYLON.Color3(1, 1, 1);
  45892. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45893. this._system = system;
  45894. system.lensFlares.push(this);
  45895. }
  45896. return LensFlare;
  45897. }());
  45898. BABYLON.LensFlare = LensFlare;
  45899. })(BABYLON || (BABYLON = {}));
  45900. //# sourceMappingURL=babylon.lensFlare.js.map
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. var LensFlareSystem = (function () {
  45904. function LensFlareSystem(name, emitter, scene) {
  45905. this.name = name;
  45906. this.lensFlares = new Array();
  45907. this.borderLimit = 300;
  45908. this.viewportBorder = 0;
  45909. this.layerMask = 0x0FFFFFFF;
  45910. this._vertexBuffers = {};
  45911. this._isEnabled = true;
  45912. this._scene = scene;
  45913. this._emitter = emitter;
  45914. this.id = name;
  45915. scene.lensFlareSystems.push(this);
  45916. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  45917. var engine = scene.getEngine();
  45918. // VBO
  45919. var vertices = [];
  45920. vertices.push(1, 1);
  45921. vertices.push(-1, 1);
  45922. vertices.push(-1, -1);
  45923. vertices.push(1, -1);
  45924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  45925. // Indices
  45926. var indices = [];
  45927. indices.push(0);
  45928. indices.push(1);
  45929. indices.push(2);
  45930. indices.push(0);
  45931. indices.push(2);
  45932. indices.push(3);
  45933. this._indexBuffer = engine.createIndexBuffer(indices);
  45934. // Effects
  45935. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  45936. }
  45937. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  45938. get: function () {
  45939. return this._isEnabled;
  45940. },
  45941. set: function (value) {
  45942. this._isEnabled = value;
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. LensFlareSystem.prototype.getScene = function () {
  45948. return this._scene;
  45949. };
  45950. LensFlareSystem.prototype.getEmitter = function () {
  45951. return this._emitter;
  45952. };
  45953. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  45954. this._emitter = newEmitter;
  45955. };
  45956. LensFlareSystem.prototype.getEmitterPosition = function () {
  45957. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45958. };
  45959. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45960. var position = this.getEmitterPosition();
  45961. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45962. this._positionX = position.x;
  45963. this._positionY = position.y;
  45964. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45965. if (this.viewportBorder > 0) {
  45966. globalViewport.x -= this.viewportBorder;
  45967. globalViewport.y -= this.viewportBorder;
  45968. globalViewport.width += this.viewportBorder * 2;
  45969. globalViewport.height += this.viewportBorder * 2;
  45970. position.x += this.viewportBorder;
  45971. position.y += this.viewportBorder;
  45972. this._positionX += this.viewportBorder;
  45973. this._positionY += this.viewportBorder;
  45974. }
  45975. if (position.z > 0) {
  45976. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  45977. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  45978. return true;
  45979. }
  45980. return true;
  45981. }
  45982. return false;
  45983. };
  45984. LensFlareSystem.prototype._isVisible = function () {
  45985. if (!this._isEnabled) {
  45986. return false;
  45987. }
  45988. var emitterPosition = this.getEmitterPosition();
  45989. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  45990. var distance = direction.length();
  45991. direction.normalize();
  45992. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  45993. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  45994. return !pickInfo.hit || pickInfo.distance > distance;
  45995. };
  45996. LensFlareSystem.prototype.render = function () {
  45997. if (!this._effect.isReady())
  45998. return false;
  45999. var engine = this._scene.getEngine();
  46000. var viewport = this._scene.activeCamera.viewport;
  46001. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46002. // Position
  46003. if (!this.computeEffectivePosition(globalViewport)) {
  46004. return false;
  46005. }
  46006. // Visibility
  46007. if (!this._isVisible()) {
  46008. return false;
  46009. }
  46010. // Intensity
  46011. var awayX;
  46012. var awayY;
  46013. if (this._positionX < this.borderLimit + globalViewport.x) {
  46014. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46015. }
  46016. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46017. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46018. }
  46019. else {
  46020. awayX = 0;
  46021. }
  46022. if (this._positionY < this.borderLimit + globalViewport.y) {
  46023. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46024. }
  46025. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46026. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46027. }
  46028. else {
  46029. awayY = 0;
  46030. }
  46031. var away = (awayX > awayY) ? awayX : awayY;
  46032. away -= this.viewportBorder;
  46033. if (away > this.borderLimit) {
  46034. away = this.borderLimit;
  46035. }
  46036. var intensity = 1.0 - (away / this.borderLimit);
  46037. if (intensity < 0) {
  46038. return false;
  46039. }
  46040. if (intensity > 1.0) {
  46041. intensity = 1.0;
  46042. }
  46043. if (this.viewportBorder > 0) {
  46044. globalViewport.x += this.viewportBorder;
  46045. globalViewport.y += this.viewportBorder;
  46046. globalViewport.width -= this.viewportBorder * 2;
  46047. globalViewport.height -= this.viewportBorder * 2;
  46048. this._positionX -= this.viewportBorder;
  46049. this._positionY -= this.viewportBorder;
  46050. }
  46051. // Position
  46052. var centerX = globalViewport.x + globalViewport.width / 2;
  46053. var centerY = globalViewport.y + globalViewport.height / 2;
  46054. var distX = centerX - this._positionX;
  46055. var distY = centerY - this._positionY;
  46056. // Effects
  46057. engine.enableEffect(this._effect);
  46058. engine.setState(false);
  46059. engine.setDepthBuffer(false);
  46060. // VBOs
  46061. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46062. // Flares
  46063. for (var index = 0; index < this.lensFlares.length; index++) {
  46064. var flare = this.lensFlares[index];
  46065. engine.setAlphaMode(flare.alphaMode);
  46066. var x = centerX - (distX * flare.position);
  46067. var y = centerY - (distY * flare.position);
  46068. var cw = flare.size;
  46069. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46070. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46071. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46072. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46073. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46074. // Texture
  46075. this._effect.setTexture("textureSampler", flare.texture);
  46076. // Color
  46077. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46078. // Draw order
  46079. engine.draw(true, 0, 6);
  46080. }
  46081. engine.setDepthBuffer(true);
  46082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46083. return true;
  46084. };
  46085. LensFlareSystem.prototype.dispose = function () {
  46086. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46087. if (vertexBuffer) {
  46088. vertexBuffer.dispose();
  46089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46090. }
  46091. if (this._indexBuffer) {
  46092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46093. this._indexBuffer = null;
  46094. }
  46095. while (this.lensFlares.length) {
  46096. this.lensFlares[0].dispose();
  46097. }
  46098. // Remove from scene
  46099. var index = this._scene.lensFlareSystems.indexOf(this);
  46100. this._scene.lensFlareSystems.splice(index, 1);
  46101. };
  46102. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46103. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46104. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46105. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46106. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46107. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46108. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46109. var parsedFlare = parsedLensFlareSystem.flares[index];
  46110. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46111. }
  46112. return lensFlareSystem;
  46113. };
  46114. LensFlareSystem.prototype.serialize = function () {
  46115. var serializationObject = {};
  46116. serializationObject.id = this.id;
  46117. serializationObject.name = this.name;
  46118. serializationObject.emitterId = this.getEmitter().id;
  46119. serializationObject.borderLimit = this.borderLimit;
  46120. serializationObject.flares = [];
  46121. for (var index = 0; index < this.lensFlares.length; index++) {
  46122. var flare = this.lensFlares[index];
  46123. serializationObject.flares.push({
  46124. size: flare.size,
  46125. position: flare.position,
  46126. color: flare.color.asArray(),
  46127. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46128. });
  46129. }
  46130. return serializationObject;
  46131. };
  46132. return LensFlareSystem;
  46133. }());
  46134. BABYLON.LensFlareSystem = LensFlareSystem;
  46135. })(BABYLON || (BABYLON = {}));
  46136. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46137. var BABYLON;
  46138. (function (BABYLON) {
  46139. // We're mainly based on the logic defined into the FreeCamera code
  46140. var DeviceOrientationCamera = (function (_super) {
  46141. __extends(DeviceOrientationCamera, _super);
  46142. function DeviceOrientationCamera(name, position, scene) {
  46143. _super.call(this, name, position, scene);
  46144. this._quaternionCache = new BABYLON.Quaternion();
  46145. this.inputs.addDeviceOrientation();
  46146. }
  46147. DeviceOrientationCamera.prototype.getClassName = function () {
  46148. return "DeviceOrientationCamera";
  46149. };
  46150. DeviceOrientationCamera.prototype._checkInputs = function () {
  46151. _super.prototype._checkInputs.call(this);
  46152. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46153. if (this._initialQuaternion) {
  46154. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46155. }
  46156. };
  46157. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46158. var _this = this;
  46159. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46160. //can only work if this camera has a rotation quaternion already.
  46161. if (!this.rotationQuaternion)
  46162. return;
  46163. if (!this._initialQuaternion) {
  46164. this._initialQuaternion = new BABYLON.Quaternion();
  46165. }
  46166. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46167. ['x', 'y', 'z'].forEach(function (axisName) {
  46168. if (!axis[axisName]) {
  46169. _this._initialQuaternion[axisName] = 0;
  46170. }
  46171. else {
  46172. _this._initialQuaternion[axisName] *= -1;
  46173. }
  46174. });
  46175. this._initialQuaternion.normalize();
  46176. //force rotation update
  46177. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46178. };
  46179. return DeviceOrientationCamera;
  46180. }(BABYLON.FreeCamera));
  46181. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46182. })(BABYLON || (BABYLON = {}));
  46183. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46184. var BABYLON;
  46185. (function (BABYLON) {
  46186. var VRDeviceOrientationFreeCamera = (function (_super) {
  46187. __extends(VRDeviceOrientationFreeCamera, _super);
  46188. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46189. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46190. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46191. _super.call(this, name, position, scene);
  46192. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46193. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46194. }
  46195. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46196. return "VRDeviceOrientationFreeCamera";
  46197. };
  46198. return VRDeviceOrientationFreeCamera;
  46199. }(BABYLON.DeviceOrientationCamera));
  46200. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46201. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46202. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46203. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46205. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46206. _super.call(this, name, alpha, beta, radius, target, scene);
  46207. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46208. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46209. this.inputs.addVRDeviceOrientation();
  46210. }
  46211. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46212. return "VRDeviceOrientationArcRotateCamera";
  46213. };
  46214. return VRDeviceOrientationArcRotateCamera;
  46215. }(BABYLON.ArcRotateCamera));
  46216. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46217. })(BABYLON || (BABYLON = {}));
  46218. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46219. var BABYLON;
  46220. (function (BABYLON) {
  46221. // We're mainly based on the logic defined into the FreeCamera code
  46222. var UniversalCamera = (function (_super) {
  46223. __extends(UniversalCamera, _super);
  46224. //-- end properties for backward compatibility for inputs
  46225. function UniversalCamera(name, position, scene) {
  46226. _super.call(this, name, position, scene);
  46227. this.inputs.addGamepad();
  46228. }
  46229. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46230. //-- Begin properties for backward compatibility for inputs
  46231. get: function () {
  46232. var gamepad = this.inputs.attached["gamepad"];
  46233. if (gamepad)
  46234. return gamepad.gamepadAngularSensibility;
  46235. },
  46236. set: function (value) {
  46237. var gamepad = this.inputs.attached["gamepad"];
  46238. if (gamepad)
  46239. gamepad.gamepadAngularSensibility = value;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46245. get: function () {
  46246. var gamepad = this.inputs.attached["gamepad"];
  46247. if (gamepad)
  46248. return gamepad.gamepadMoveSensibility;
  46249. },
  46250. set: function (value) {
  46251. var gamepad = this.inputs.attached["gamepad"];
  46252. if (gamepad)
  46253. gamepad.gamepadMoveSensibility = value;
  46254. },
  46255. enumerable: true,
  46256. configurable: true
  46257. });
  46258. UniversalCamera.prototype.getClassName = function () {
  46259. return "UniversalCamera";
  46260. };
  46261. return UniversalCamera;
  46262. }(BABYLON.TouchCamera));
  46263. BABYLON.UniversalCamera = UniversalCamera;
  46264. })(BABYLON || (BABYLON = {}));
  46265. //# sourceMappingURL=babylon.universalCamera.js.map
  46266. var BABYLON;
  46267. (function (BABYLON) {
  46268. var Gamepads = (function () {
  46269. function Gamepads(ongamedpadconnected) {
  46270. var _this = this;
  46271. this.babylonGamepads = [];
  46272. this.oneGamepadConnected = false;
  46273. this.isMonitoring = false;
  46274. this.gamepadEventSupported = 'GamepadEvent' in window;
  46275. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46276. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46277. this._callbackGamepadConnected = ongamedpadconnected;
  46278. if (this.gamepadSupportAvailable) {
  46279. // Checking if the gamepad connected event is supported (like in Firefox)
  46280. if (this.gamepadEventSupported) {
  46281. this._onGamepadConnectedEvent = function (evt) {
  46282. _this._onGamepadConnected(evt);
  46283. };
  46284. this._onGamepadDisonnectedEvent = function (evt) {
  46285. _this._onGamepadDisconnected(evt);
  46286. };
  46287. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46288. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46289. }
  46290. else {
  46291. this._startMonitoringGamepads();
  46292. }
  46293. }
  46294. }
  46295. Gamepads.prototype.dispose = function () {
  46296. if (Gamepads.gamepadDOMInfo) {
  46297. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46298. }
  46299. if (this._onGamepadConnectedEvent) {
  46300. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46301. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46302. this._onGamepadConnectedEvent = null;
  46303. this._onGamepadDisonnectedEvent = null;
  46304. }
  46305. };
  46306. Gamepads.prototype._onGamepadConnected = function (evt) {
  46307. var newGamepad = this._addNewGamepad(evt.gamepad);
  46308. if (this._callbackGamepadConnected)
  46309. this._callbackGamepadConnected(newGamepad);
  46310. this._startMonitoringGamepads();
  46311. };
  46312. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46313. if (!this.oneGamepadConnected) {
  46314. this.oneGamepadConnected = true;
  46315. if (Gamepads.gamepadDOMInfo) {
  46316. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46317. Gamepads.gamepadDOMInfo = null;
  46318. }
  46319. }
  46320. var newGamepad;
  46321. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46322. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46323. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46324. }
  46325. else {
  46326. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46327. }
  46328. this.babylonGamepads.push(newGamepad);
  46329. return newGamepad;
  46330. };
  46331. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46332. // Remove the gamepad from the list of gamepads to monitor.
  46333. for (var i in this.babylonGamepads) {
  46334. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46335. this.babylonGamepads.splice(+i, 1);
  46336. break;
  46337. }
  46338. }
  46339. // If no gamepads are left, stop the polling loop.
  46340. if (this.babylonGamepads.length == 0) {
  46341. this._stopMonitoringGamepads();
  46342. }
  46343. };
  46344. Gamepads.prototype._startMonitoringGamepads = function () {
  46345. if (!this.isMonitoring) {
  46346. this.isMonitoring = true;
  46347. this._checkGamepadsStatus();
  46348. }
  46349. };
  46350. Gamepads.prototype._stopMonitoringGamepads = function () {
  46351. this.isMonitoring = false;
  46352. };
  46353. Gamepads.prototype._checkGamepadsStatus = function () {
  46354. var _this = this;
  46355. // updating gamepad objects
  46356. this._updateGamepadObjects();
  46357. for (var i in this.babylonGamepads) {
  46358. this.babylonGamepads[i].update();
  46359. }
  46360. if (this.isMonitoring) {
  46361. if (window.requestAnimationFrame) {
  46362. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46363. }
  46364. else if (window.mozRequestAnimationFrame) {
  46365. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46366. }
  46367. else if (window.webkitRequestAnimationFrame) {
  46368. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46369. }
  46370. }
  46371. };
  46372. // This function is called only on Chrome, which does not yet support
  46373. // connection/disconnection events, but requires you to monitor
  46374. // an array for changes.
  46375. Gamepads.prototype._updateGamepadObjects = function () {
  46376. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46377. for (var i = 0; i < gamepads.length; i++) {
  46378. if (gamepads[i]) {
  46379. if (!(gamepads[i].index in this.babylonGamepads)) {
  46380. var newGamepad = this._addNewGamepad(gamepads[i]);
  46381. if (this._callbackGamepadConnected) {
  46382. this._callbackGamepadConnected(newGamepad);
  46383. }
  46384. }
  46385. else {
  46386. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46387. }
  46388. }
  46389. }
  46390. };
  46391. return Gamepads;
  46392. }());
  46393. BABYLON.Gamepads = Gamepads;
  46394. var StickValues = (function () {
  46395. function StickValues(x, y) {
  46396. this.x = x;
  46397. this.y = y;
  46398. }
  46399. return StickValues;
  46400. }());
  46401. BABYLON.StickValues = StickValues;
  46402. var Gamepad = (function () {
  46403. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46404. if (leftStickX === void 0) { leftStickX = 0; }
  46405. if (leftStickY === void 0) { leftStickY = 1; }
  46406. if (rightStickX === void 0) { rightStickX = 2; }
  46407. if (rightStickY === void 0) { rightStickY = 3; }
  46408. this.id = id;
  46409. this.index = index;
  46410. this.browserGamepad = browserGamepad;
  46411. this._leftStickAxisX = leftStickX;
  46412. this._leftStickAxisY = leftStickY;
  46413. this._rightStickAxisX = rightStickX;
  46414. this._rightStickAxisY = rightStickY;
  46415. if (this.browserGamepad.axes.length >= 2) {
  46416. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46417. }
  46418. if (this.browserGamepad.axes.length >= 4) {
  46419. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46420. }
  46421. }
  46422. Gamepad.prototype.onleftstickchanged = function (callback) {
  46423. this._onleftstickchanged = callback;
  46424. };
  46425. Gamepad.prototype.onrightstickchanged = function (callback) {
  46426. this._onrightstickchanged = callback;
  46427. };
  46428. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46429. get: function () {
  46430. return this._leftStick;
  46431. },
  46432. set: function (newValues) {
  46433. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46434. this._onleftstickchanged(newValues);
  46435. }
  46436. this._leftStick = newValues;
  46437. },
  46438. enumerable: true,
  46439. configurable: true
  46440. });
  46441. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46442. get: function () {
  46443. return this._rightStick;
  46444. },
  46445. set: function (newValues) {
  46446. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46447. this._onrightstickchanged(newValues);
  46448. }
  46449. this._rightStick = newValues;
  46450. },
  46451. enumerable: true,
  46452. configurable: true
  46453. });
  46454. Gamepad.prototype.update = function () {
  46455. if (this._leftStick) {
  46456. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46457. }
  46458. if (this._rightStick) {
  46459. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46460. }
  46461. };
  46462. return Gamepad;
  46463. }());
  46464. BABYLON.Gamepad = Gamepad;
  46465. var GenericPad = (function (_super) {
  46466. __extends(GenericPad, _super);
  46467. function GenericPad(id, index, gamepad) {
  46468. _super.call(this, id, index, gamepad);
  46469. this.id = id;
  46470. this.index = index;
  46471. this.gamepad = gamepad;
  46472. this._buttons = new Array(gamepad.buttons.length);
  46473. }
  46474. GenericPad.prototype.onbuttondown = function (callback) {
  46475. this._onbuttondown = callback;
  46476. };
  46477. GenericPad.prototype.onbuttonup = function (callback) {
  46478. this._onbuttonup = callback;
  46479. };
  46480. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46481. if (newValue !== currentValue) {
  46482. if (this._onbuttondown && newValue === 1) {
  46483. this._onbuttondown(buttonIndex);
  46484. }
  46485. if (this._onbuttonup && newValue === 0) {
  46486. this._onbuttonup(buttonIndex);
  46487. }
  46488. }
  46489. return newValue;
  46490. };
  46491. GenericPad.prototype.update = function () {
  46492. _super.prototype.update.call(this);
  46493. for (var index = 0; index < this._buttons.length; index++) {
  46494. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46495. }
  46496. };
  46497. return GenericPad;
  46498. }(Gamepad));
  46499. BABYLON.GenericPad = GenericPad;
  46500. (function (Xbox360Button) {
  46501. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46502. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46503. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46504. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46505. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46506. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46507. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46508. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46509. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46510. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46511. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46512. var Xbox360Button = BABYLON.Xbox360Button;
  46513. (function (Xbox360Dpad) {
  46514. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46515. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46516. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46517. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46518. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46519. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46520. var Xbox360Pad = (function (_super) {
  46521. __extends(Xbox360Pad, _super);
  46522. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46523. if (xboxOne === void 0) { xboxOne = false; }
  46524. _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3));
  46525. this._leftTrigger = 0;
  46526. this._rightTrigger = 0;
  46527. this._buttonA = 0;
  46528. this._buttonB = 0;
  46529. this._buttonX = 0;
  46530. this._buttonY = 0;
  46531. this._buttonBack = 0;
  46532. this._buttonStart = 0;
  46533. this._buttonLB = 0;
  46534. this._buttonRB = 0;
  46535. this._buttonLeftStick = 0;
  46536. this._buttonRightStick = 0;
  46537. this._dPadUp = 0;
  46538. this._dPadDown = 0;
  46539. this._dPadLeft = 0;
  46540. this._dPadRight = 0;
  46541. this._isXboxOnePad = false;
  46542. this._isXboxOnePad = xboxOne;
  46543. }
  46544. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46545. this._onlefttriggerchanged = callback;
  46546. };
  46547. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46548. this._onrighttriggerchanged = callback;
  46549. };
  46550. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46551. get: function () {
  46552. return this._leftTrigger;
  46553. },
  46554. set: function (newValue) {
  46555. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46556. this._onlefttriggerchanged(newValue);
  46557. }
  46558. this._leftTrigger = newValue;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46564. get: function () {
  46565. return this._rightTrigger;
  46566. },
  46567. set: function (newValue) {
  46568. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46569. this._onrighttriggerchanged(newValue);
  46570. }
  46571. this._rightTrigger = newValue;
  46572. },
  46573. enumerable: true,
  46574. configurable: true
  46575. });
  46576. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46577. this._onbuttondown = callback;
  46578. };
  46579. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46580. this._onbuttonup = callback;
  46581. };
  46582. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46583. this._ondpaddown = callback;
  46584. };
  46585. Xbox360Pad.prototype.ondpadup = function (callback) {
  46586. this._ondpadup = callback;
  46587. };
  46588. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46589. if (newValue !== currentValue) {
  46590. if (this._onbuttondown && newValue === 1) {
  46591. this._onbuttondown(buttonType);
  46592. }
  46593. if (this._onbuttonup && newValue === 0) {
  46594. this._onbuttonup(buttonType);
  46595. }
  46596. }
  46597. return newValue;
  46598. };
  46599. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46600. if (newValue !== currentValue) {
  46601. if (this._ondpaddown && newValue === 1) {
  46602. this._ondpaddown(buttonType);
  46603. }
  46604. if (this._ondpadup && newValue === 0) {
  46605. this._ondpadup(buttonType);
  46606. }
  46607. }
  46608. return newValue;
  46609. };
  46610. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46611. get: function () {
  46612. return this._buttonA;
  46613. },
  46614. set: function (value) {
  46615. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46616. },
  46617. enumerable: true,
  46618. configurable: true
  46619. });
  46620. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46621. get: function () {
  46622. return this._buttonB;
  46623. },
  46624. set: function (value) {
  46625. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46626. },
  46627. enumerable: true,
  46628. configurable: true
  46629. });
  46630. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46631. get: function () {
  46632. return this._buttonX;
  46633. },
  46634. set: function (value) {
  46635. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46636. },
  46637. enumerable: true,
  46638. configurable: true
  46639. });
  46640. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46641. get: function () {
  46642. return this._buttonY;
  46643. },
  46644. set: function (value) {
  46645. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46646. },
  46647. enumerable: true,
  46648. configurable: true
  46649. });
  46650. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46651. get: function () {
  46652. return this._buttonStart;
  46653. },
  46654. set: function (value) {
  46655. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46656. },
  46657. enumerable: true,
  46658. configurable: true
  46659. });
  46660. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46661. get: function () {
  46662. return this._buttonBack;
  46663. },
  46664. set: function (value) {
  46665. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46666. },
  46667. enumerable: true,
  46668. configurable: true
  46669. });
  46670. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46671. get: function () {
  46672. return this._buttonLB;
  46673. },
  46674. set: function (value) {
  46675. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46676. },
  46677. enumerable: true,
  46678. configurable: true
  46679. });
  46680. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46681. get: function () {
  46682. return this._buttonRB;
  46683. },
  46684. set: function (value) {
  46685. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46691. get: function () {
  46692. return this._buttonLeftStick;
  46693. },
  46694. set: function (value) {
  46695. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46696. },
  46697. enumerable: true,
  46698. configurable: true
  46699. });
  46700. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46701. get: function () {
  46702. return this._buttonRightStick;
  46703. },
  46704. set: function (value) {
  46705. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46706. },
  46707. enumerable: true,
  46708. configurable: true
  46709. });
  46710. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46711. get: function () {
  46712. return this._dPadUp;
  46713. },
  46714. set: function (value) {
  46715. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46716. },
  46717. enumerable: true,
  46718. configurable: true
  46719. });
  46720. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46721. get: function () {
  46722. return this._dPadDown;
  46723. },
  46724. set: function (value) {
  46725. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46726. },
  46727. enumerable: true,
  46728. configurable: true
  46729. });
  46730. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46731. get: function () {
  46732. return this._dPadLeft;
  46733. },
  46734. set: function (value) {
  46735. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46736. },
  46737. enumerable: true,
  46738. configurable: true
  46739. });
  46740. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46741. get: function () {
  46742. return this._dPadRight;
  46743. },
  46744. set: function (value) {
  46745. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46746. },
  46747. enumerable: true,
  46748. configurable: true
  46749. });
  46750. Xbox360Pad.prototype.update = function () {
  46751. _super.prototype.update.call(this);
  46752. if (this._isXboxOnePad) {
  46753. this.buttonA = this.browserGamepad.buttons[0].value;
  46754. this.buttonB = this.browserGamepad.buttons[1].value;
  46755. this.buttonX = this.browserGamepad.buttons[2].value;
  46756. this.buttonY = this.browserGamepad.buttons[3].value;
  46757. this.buttonLB = this.browserGamepad.buttons[4].value;
  46758. this.buttonRB = this.browserGamepad.buttons[5].value;
  46759. this.leftTrigger = this.browserGamepad.axes[2];
  46760. this.rightTrigger = this.browserGamepad.axes[5];
  46761. this.buttonBack = this.browserGamepad.buttons[9].value;
  46762. this.buttonStart = this.browserGamepad.buttons[8].value;
  46763. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46764. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46765. this.dPadUp = this.browserGamepad.buttons[11].value;
  46766. this.dPadDown = this.browserGamepad.buttons[12].value;
  46767. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46768. this.dPadRight = this.browserGamepad.buttons[14].value;
  46769. }
  46770. else {
  46771. this.buttonA = this.browserGamepad.buttons[0].value;
  46772. this.buttonB = this.browserGamepad.buttons[1].value;
  46773. this.buttonX = this.browserGamepad.buttons[2].value;
  46774. this.buttonY = this.browserGamepad.buttons[3].value;
  46775. this.buttonLB = this.browserGamepad.buttons[4].value;
  46776. this.buttonRB = this.browserGamepad.buttons[5].value;
  46777. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46778. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46779. this.buttonBack = this.browserGamepad.buttons[8].value;
  46780. this.buttonStart = this.browserGamepad.buttons[9].value;
  46781. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46782. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46783. this.dPadUp = this.browserGamepad.buttons[12].value;
  46784. this.dPadDown = this.browserGamepad.buttons[13].value;
  46785. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46786. this.dPadRight = this.browserGamepad.buttons[15].value;
  46787. }
  46788. };
  46789. return Xbox360Pad;
  46790. }(Gamepad));
  46791. BABYLON.Xbox360Pad = Xbox360Pad;
  46792. })(BABYLON || (BABYLON = {}));
  46793. //# sourceMappingURL=babylon.gamepads.js.map
  46794. var BABYLON;
  46795. (function (BABYLON) {
  46796. // We're mainly based on the logic defined into the FreeCamera code
  46797. var GamepadCamera = (function (_super) {
  46798. __extends(GamepadCamera, _super);
  46799. //-- end properties for backward compatibility for inputs
  46800. function GamepadCamera(name, position, scene) {
  46801. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46802. _super.call(this, name, position, scene);
  46803. }
  46804. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46805. //-- Begin properties for backward compatibility for inputs
  46806. get: function () {
  46807. var gamepad = this.inputs.attached["gamepad"];
  46808. if (gamepad)
  46809. return gamepad.gamepadAngularSensibility;
  46810. },
  46811. set: function (value) {
  46812. var gamepad = this.inputs.attached["gamepad"];
  46813. if (gamepad)
  46814. gamepad.gamepadAngularSensibility = value;
  46815. },
  46816. enumerable: true,
  46817. configurable: true
  46818. });
  46819. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46820. get: function () {
  46821. var gamepad = this.inputs.attached["gamepad"];
  46822. if (gamepad)
  46823. return gamepad.gamepadMoveSensibility;
  46824. },
  46825. set: function (value) {
  46826. var gamepad = this.inputs.attached["gamepad"];
  46827. if (gamepad)
  46828. gamepad.gamepadMoveSensibility = value;
  46829. },
  46830. enumerable: true,
  46831. configurable: true
  46832. });
  46833. GamepadCamera.prototype.getClassName = function () {
  46834. return "GamepadCamera";
  46835. };
  46836. return GamepadCamera;
  46837. }(BABYLON.UniversalCamera));
  46838. BABYLON.GamepadCamera = GamepadCamera;
  46839. })(BABYLON || (BABYLON = {}));
  46840. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46841. var BABYLON;
  46842. (function (BABYLON) {
  46843. var Analyser = (function () {
  46844. function Analyser(scene) {
  46845. this.SMOOTHING = 0.75;
  46846. this.FFT_SIZE = 512;
  46847. this.BARGRAPHAMPLITUDE = 256;
  46848. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46849. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46850. this._scene = scene;
  46851. this._audioEngine = BABYLON.Engine.audioEngine;
  46852. if (this._audioEngine.canUseWebAudio) {
  46853. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46854. this._webAudioAnalyser.minDecibels = -140;
  46855. this._webAudioAnalyser.maxDecibels = 0;
  46856. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46857. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46858. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46859. }
  46860. }
  46861. Analyser.prototype.getFrequencyBinCount = function () {
  46862. if (this._audioEngine.canUseWebAudio) {
  46863. return this._webAudioAnalyser.frequencyBinCount;
  46864. }
  46865. else {
  46866. return 0;
  46867. }
  46868. };
  46869. Analyser.prototype.getByteFrequencyData = function () {
  46870. if (this._audioEngine.canUseWebAudio) {
  46871. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46872. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46873. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46874. }
  46875. return this._byteFreqs;
  46876. };
  46877. Analyser.prototype.getByteTimeDomainData = function () {
  46878. if (this._audioEngine.canUseWebAudio) {
  46879. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46880. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46881. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46882. }
  46883. return this._byteTime;
  46884. };
  46885. Analyser.prototype.getFloatFrequencyData = function () {
  46886. if (this._audioEngine.canUseWebAudio) {
  46887. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46888. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46889. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46890. }
  46891. return this._floatFreqs;
  46892. };
  46893. Analyser.prototype.drawDebugCanvas = function () {
  46894. var _this = this;
  46895. if (this._audioEngine.canUseWebAudio) {
  46896. if (!this._debugCanvas) {
  46897. this._debugCanvas = document.createElement("canvas");
  46898. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46899. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46900. this._debugCanvas.style.position = "absolute";
  46901. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46902. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46903. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46904. document.body.appendChild(this._debugCanvas);
  46905. this._registerFunc = function () {
  46906. _this.drawDebugCanvas();
  46907. };
  46908. this._scene.registerBeforeRender(this._registerFunc);
  46909. }
  46910. if (this._registerFunc) {
  46911. var workingArray = this.getByteFrequencyData();
  46912. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46913. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46914. // Draw the frequency domain chart.
  46915. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46916. var value = workingArray[i];
  46917. var percent = value / this.BARGRAPHAMPLITUDE;
  46918. var height = this.DEBUGCANVASSIZE.height * percent;
  46919. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46920. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46921. var hue = i / this.getFrequencyBinCount() * 360;
  46922. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46923. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46924. }
  46925. }
  46926. }
  46927. };
  46928. Analyser.prototype.stopDebugCanvas = function () {
  46929. if (this._debugCanvas) {
  46930. this._scene.unregisterBeforeRender(this._registerFunc);
  46931. this._registerFunc = null;
  46932. document.body.removeChild(this._debugCanvas);
  46933. this._debugCanvas = null;
  46934. this._debugCanvasContext = null;
  46935. }
  46936. };
  46937. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46938. if (this._audioEngine.canUseWebAudio) {
  46939. inputAudioNode.connect(this._webAudioAnalyser);
  46940. this._webAudioAnalyser.connect(outputAudioNode);
  46941. }
  46942. };
  46943. Analyser.prototype.dispose = function () {
  46944. if (this._audioEngine.canUseWebAudio) {
  46945. this._webAudioAnalyser.disconnect();
  46946. }
  46947. };
  46948. return Analyser;
  46949. }());
  46950. BABYLON.Analyser = Analyser;
  46951. })(BABYLON || (BABYLON = {}));
  46952. //# sourceMappingURL=babylon.analyser.js.map
  46953. var BABYLON;
  46954. (function (BABYLON) {
  46955. var DepthRenderer = (function () {
  46956. function DepthRenderer(scene, type) {
  46957. var _this = this;
  46958. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46959. this._viewMatrix = BABYLON.Matrix.Zero();
  46960. this._projectionMatrix = BABYLON.Matrix.Zero();
  46961. this._transformMatrix = BABYLON.Matrix.Zero();
  46962. this._worldViewProjection = BABYLON.Matrix.Zero();
  46963. this._scene = scene;
  46964. var engine = scene.getEngine();
  46965. // Render target
  46966. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46967. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46968. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46969. this._depthMap.refreshRate = 1;
  46970. this._depthMap.renderParticles = false;
  46971. this._depthMap.renderList = null;
  46972. // set default depth value to 1.0 (far away)
  46973. this._depthMap.onClearObservable.add(function (engine) {
  46974. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46975. });
  46976. // Custom render function
  46977. var renderSubMesh = function (subMesh) {
  46978. var mesh = subMesh.getRenderingMesh();
  46979. var scene = _this._scene;
  46980. var engine = scene.getEngine();
  46981. // Culling
  46982. engine.setState(subMesh.getMaterial().backFaceCulling);
  46983. // Managing instances
  46984. var batch = mesh._getInstancesRenderList(subMesh._id);
  46985. if (batch.mustReturn) {
  46986. return;
  46987. }
  46988. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46989. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46990. engine.enableEffect(_this._effect);
  46991. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46992. var material = subMesh.getMaterial();
  46993. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46994. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46995. // Alpha test
  46996. if (material && material.needAlphaTesting()) {
  46997. var alphaTexture = material.getAlphaTestTexture();
  46998. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46999. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47000. }
  47001. // Bones
  47002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47003. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47004. }
  47005. // Draw
  47006. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47007. }
  47008. };
  47009. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47010. var index;
  47011. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47012. renderSubMesh(opaqueSubMeshes.data[index]);
  47013. }
  47014. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47015. renderSubMesh(alphaTestSubMeshes.data[index]);
  47016. }
  47017. };
  47018. }
  47019. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47020. var material = subMesh.getMaterial();
  47021. if (material.disableDepthWrite) {
  47022. return false;
  47023. }
  47024. var defines = [];
  47025. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47026. var mesh = subMesh.getMesh();
  47027. var scene = mesh.getScene();
  47028. // Alpha test
  47029. if (material && material.needAlphaTesting()) {
  47030. defines.push("#define ALPHATEST");
  47031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47032. attribs.push(BABYLON.VertexBuffer.UVKind);
  47033. defines.push("#define UV1");
  47034. }
  47035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47037. defines.push("#define UV2");
  47038. }
  47039. }
  47040. // Bones
  47041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47044. if (mesh.numBoneInfluencers > 4) {
  47045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47047. }
  47048. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47049. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47050. }
  47051. else {
  47052. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47053. }
  47054. // Instances
  47055. if (useInstances) {
  47056. defines.push("#define INSTANCES");
  47057. attribs.push("world0");
  47058. attribs.push("world1");
  47059. attribs.push("world2");
  47060. attribs.push("world3");
  47061. }
  47062. // Get correct effect
  47063. var join = defines.join("\n");
  47064. if (this._cachedDefines !== join) {
  47065. this._cachedDefines = join;
  47066. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47067. }
  47068. return this._effect.isReady();
  47069. };
  47070. DepthRenderer.prototype.getDepthMap = function () {
  47071. return this._depthMap;
  47072. };
  47073. // Methods
  47074. DepthRenderer.prototype.dispose = function () {
  47075. this._depthMap.dispose();
  47076. };
  47077. return DepthRenderer;
  47078. }());
  47079. BABYLON.DepthRenderer = DepthRenderer;
  47080. })(BABYLON || (BABYLON = {}));
  47081. //# sourceMappingURL=babylon.depthRenderer.js.map
  47082. var BABYLON;
  47083. (function (BABYLON) {
  47084. var SSAORenderingPipeline = (function (_super) {
  47085. __extends(SSAORenderingPipeline, _super);
  47086. /**
  47087. * @constructor
  47088. * @param {string} name - The rendering pipeline name
  47089. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47090. * @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 }
  47091. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47092. */
  47093. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47094. var _this = this;
  47095. _super.call(this, scene.getEngine(), name);
  47096. // Members
  47097. /**
  47098. * The PassPostProcess id in the pipeline that contains the original scene color
  47099. * @type {string}
  47100. */
  47101. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47102. /**
  47103. * The SSAO PostProcess id in the pipeline
  47104. * @type {string}
  47105. */
  47106. this.SSAORenderEffect = "SSAORenderEffect";
  47107. /**
  47108. * The horizontal blur PostProcess id in the pipeline
  47109. * @type {string}
  47110. */
  47111. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47112. /**
  47113. * The vertical blur PostProcess id in the pipeline
  47114. * @type {string}
  47115. */
  47116. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47117. /**
  47118. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47119. * @type {string}
  47120. */
  47121. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47122. /**
  47123. * The output strength of the SSAO post-process. Default value is 1.0.
  47124. * @type {number}
  47125. */
  47126. this.totalStrength = 1.0;
  47127. /**
  47128. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47129. * @type {number}
  47130. */
  47131. this.radius = 0.0001;
  47132. /**
  47133. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47134. * Must not be equal to fallOff and superior to fallOff.
  47135. * Default value is 0.975
  47136. * @type {number}
  47137. */
  47138. this.area = 0.0075;
  47139. /**
  47140. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47141. * Must not be equal to area and inferior to area.
  47142. * Default value is 0.0
  47143. * @type {number}
  47144. */
  47145. this.fallOff = 0.000001;
  47146. /**
  47147. * The base color of the SSAO post-process
  47148. * The final result is "base + ssao" between [0, 1]
  47149. * @type {number}
  47150. */
  47151. this.base = 0.5;
  47152. this._firstUpdate = true;
  47153. this._scene = scene;
  47154. // Set up assets
  47155. this._createRandomTexture();
  47156. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47157. var ssaoRatio = ratio.ssaoRatio || ratio;
  47158. var combineRatio = ratio.combineRatio || ratio;
  47159. this._ratio = {
  47160. ssaoRatio: ssaoRatio,
  47161. combineRatio: combineRatio
  47162. };
  47163. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47164. this._createSSAOPostProcess(ssaoRatio);
  47165. this._createBlurPostProcess(ssaoRatio);
  47166. this._createSSAOCombinePostProcess(combineRatio);
  47167. // Set up pipeline
  47168. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47170. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47171. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47173. // Finish
  47174. scene.postProcessRenderPipelineManager.addPipeline(this);
  47175. if (cameras)
  47176. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47177. }
  47178. // Public Methods
  47179. /**
  47180. * Returns the horizontal blur PostProcess
  47181. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47182. */
  47183. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47184. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47185. return null;
  47186. };
  47187. /**
  47188. * Returns the vertical blur PostProcess
  47189. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47190. */
  47191. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47192. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47193. return null;
  47194. };
  47195. /**
  47196. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47197. */
  47198. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47199. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47200. for (var i = 0; i < this._scene.cameras.length; i++) {
  47201. var camera = this._scene.cameras[i];
  47202. this._originalColorPostProcess.dispose(camera);
  47203. this._ssaoPostProcess.dispose(camera);
  47204. this._blurHPostProcess.dispose(camera);
  47205. this._blurVPostProcess.dispose(camera);
  47206. this._ssaoCombinePostProcess.dispose(camera);
  47207. }
  47208. this._randomTexture.dispose();
  47209. if (disableDepthRender)
  47210. this._scene.disableDepthRenderer();
  47211. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47212. };
  47213. // Private Methods
  47214. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47215. var _this = this;
  47216. /*
  47217. var samplerOffsets = [
  47218. -8.0, -6.0, -4.0, -2.0,
  47219. 0.0,
  47220. 2.0, 4.0, 6.0, 8.0
  47221. ];
  47222. */
  47223. var samples = 16;
  47224. var samplerOffsets = [];
  47225. for (var i = -8; i < 8; i++) {
  47226. samplerOffsets.push(i * 2);
  47227. }
  47228. 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");
  47229. this._blurHPostProcess.onApply = function (effect) {
  47230. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47231. effect.setTexture("depthSampler", _this._depthTexture);
  47232. if (_this._firstUpdate) {
  47233. effect.setArray("samplerOffsets", samplerOffsets);
  47234. }
  47235. };
  47236. 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");
  47237. this._blurVPostProcess.onApply = function (effect) {
  47238. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47239. effect.setTexture("depthSampler", _this._depthTexture);
  47240. if (_this._firstUpdate) {
  47241. effect.setArray("samplerOffsets", samplerOffsets);
  47242. _this._firstUpdate = false;
  47243. }
  47244. };
  47245. };
  47246. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47247. var _this = this;
  47248. var numSamples = 16;
  47249. var sampleSphere = [
  47250. 0.5381, 0.1856, -0.4319,
  47251. 0.1379, 0.2486, 0.4430,
  47252. 0.3371, 0.5679, -0.0057,
  47253. -0.6999, -0.0451, -0.0019,
  47254. 0.0689, -0.1598, -0.8547,
  47255. 0.0560, 0.0069, -0.1843,
  47256. -0.0146, 0.1402, 0.0762,
  47257. 0.0100, -0.1924, -0.0344,
  47258. -0.3577, -0.5301, -0.4358,
  47259. -0.3169, 0.1063, 0.0158,
  47260. 0.0103, -0.5869, 0.0046,
  47261. -0.0897, -0.4940, 0.3287,
  47262. 0.7119, -0.0154, -0.0918,
  47263. -0.0533, 0.0596, -0.5411,
  47264. 0.0352, -0.0631, 0.5460,
  47265. -0.4776, 0.2847, -0.0271
  47266. ];
  47267. var samplesFactor = 1.0 / numSamples;
  47268. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47269. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47270. "area", "fallOff", "base", "range", "viewport"
  47271. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47272. var viewport = new BABYLON.Vector2(0, 0);
  47273. this._ssaoPostProcess.onApply = function (effect) {
  47274. if (_this._firstUpdate) {
  47275. effect.setArray3("sampleSphere", sampleSphere);
  47276. effect.setFloat("samplesFactor", samplesFactor);
  47277. effect.setFloat("randTextureTiles", 4.0);
  47278. }
  47279. effect.setFloat("totalStrength", _this.totalStrength);
  47280. effect.setFloat("radius", _this.radius);
  47281. effect.setFloat("area", _this.area);
  47282. effect.setFloat("fallOff", _this.fallOff);
  47283. effect.setFloat("base", _this.base);
  47284. effect.setTexture("textureSampler", _this._depthTexture);
  47285. effect.setTexture("randomSampler", _this._randomTexture);
  47286. };
  47287. };
  47288. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47289. var _this = this;
  47290. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47291. this._ssaoCombinePostProcess.onApply = function (effect) {
  47292. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47293. };
  47294. };
  47295. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47296. var size = 512;
  47297. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47298. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47299. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47300. var context = this._randomTexture.getContext();
  47301. var rand = function (min, max) {
  47302. return Math.random() * (max - min) + min;
  47303. };
  47304. var randVector = BABYLON.Vector3.Zero();
  47305. for (var x = 0; x < size; x++) {
  47306. for (var y = 0; y < size; y++) {
  47307. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47308. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47309. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47310. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47311. context.fillRect(x, y, 1, 1);
  47312. }
  47313. }
  47314. this._randomTexture.update(false);
  47315. };
  47316. __decorate([
  47317. BABYLON.serialize()
  47318. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47319. __decorate([
  47320. BABYLON.serialize()
  47321. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47322. __decorate([
  47323. BABYLON.serialize()
  47324. ], SSAORenderingPipeline.prototype, "area", void 0);
  47325. __decorate([
  47326. BABYLON.serialize()
  47327. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47328. __decorate([
  47329. BABYLON.serialize()
  47330. ], SSAORenderingPipeline.prototype, "base", void 0);
  47331. __decorate([
  47332. BABYLON.serialize()
  47333. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47334. return SSAORenderingPipeline;
  47335. }(BABYLON.PostProcessRenderPipeline));
  47336. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47337. })(BABYLON || (BABYLON = {}));
  47338. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47339. var BABYLON;
  47340. (function (BABYLON) {
  47341. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47342. var VolumetricLightScatteringPostProcess = (function (_super) {
  47343. __extends(VolumetricLightScatteringPostProcess, _super);
  47344. /**
  47345. * @constructor
  47346. * @param {string} name - The post-process name
  47347. * @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)
  47348. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47349. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47350. * @param {number} samples - The post-process quality, default 100
  47351. * @param {number} samplingMode - The post-process filtering mode
  47352. * @param {BABYLON.Engine} engine - The babylon engine
  47353. * @param {boolean} reusable - If the post-process is reusable
  47354. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47355. */
  47356. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47357. var _this = this;
  47358. if (samples === void 0) { samples = 100; }
  47359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47360. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47361. this._screenCoordinates = BABYLON.Vector2.Zero();
  47362. /**
  47363. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47364. * @type {Vector3}
  47365. */
  47366. this.customMeshPosition = BABYLON.Vector3.Zero();
  47367. /**
  47368. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47369. * @type {boolean}
  47370. */
  47371. this.useCustomMeshPosition = false;
  47372. /**
  47373. * If the post-process should inverse the light scattering direction
  47374. * @type {boolean}
  47375. */
  47376. this.invert = true;
  47377. /**
  47378. * Array containing the excluded meshes not rendered in the internal pass
  47379. */
  47380. this.excludedMeshes = new Array();
  47381. /**
  47382. * Controls the overall intensity of the post-process
  47383. * @type {number}
  47384. */
  47385. this.exposure = 0.3;
  47386. /**
  47387. * Dissipates each sample's contribution in range [0, 1]
  47388. * @type {number}
  47389. */
  47390. this.decay = 0.96815;
  47391. /**
  47392. * Controls the overall intensity of each sample
  47393. * @type {number}
  47394. */
  47395. this.weight = 0.58767;
  47396. /**
  47397. * Controls the density of each sample
  47398. * @type {number}
  47399. */
  47400. this.density = 0.926;
  47401. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47402. var engine = scene.getEngine();
  47403. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47404. // Configure mesh
  47405. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47406. // Configure
  47407. this._createPass(scene, ratio.passRatio || ratio);
  47408. this.onActivate = function (camera) {
  47409. if (!_this.isSupported) {
  47410. _this.dispose(camera);
  47411. }
  47412. _this.onActivate = null;
  47413. };
  47414. this.onApplyObservable.add(function (effect) {
  47415. _this._updateMeshScreenCoordinates(scene);
  47416. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47417. effect.setFloat("exposure", _this.exposure);
  47418. effect.setFloat("decay", _this.decay);
  47419. effect.setFloat("weight", _this.weight);
  47420. effect.setFloat("density", _this.density);
  47421. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47422. });
  47423. }
  47424. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47425. get: function () {
  47426. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47427. return false;
  47428. },
  47429. set: function (useDiffuseColor) {
  47430. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47436. var mesh = subMesh.getMesh();
  47437. // Render this.mesh as default
  47438. if (mesh === this.mesh) {
  47439. return mesh.material.isReady(mesh);
  47440. }
  47441. var defines = [];
  47442. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47443. var material = subMesh.getMaterial();
  47444. var needUV = false;
  47445. // Alpha test
  47446. if (material) {
  47447. if (material.needAlphaTesting()) {
  47448. defines.push("#define ALPHATEST");
  47449. }
  47450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47451. attribs.push(BABYLON.VertexBuffer.UVKind);
  47452. defines.push("#define UV1");
  47453. }
  47454. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47455. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47456. defines.push("#define UV2");
  47457. }
  47458. }
  47459. // Bones
  47460. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47463. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47464. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47465. }
  47466. else {
  47467. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47468. }
  47469. // Instances
  47470. if (useInstances) {
  47471. defines.push("#define INSTANCES");
  47472. attribs.push("world0");
  47473. attribs.push("world1");
  47474. attribs.push("world2");
  47475. attribs.push("world3");
  47476. }
  47477. // Get correct effect
  47478. var join = defines.join("\n");
  47479. if (this._cachedDefines !== join) {
  47480. this._cachedDefines = join;
  47481. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47482. }
  47483. return this._volumetricLightScatteringPass.isReady();
  47484. };
  47485. /**
  47486. * Sets the new light position for light scattering effect
  47487. * @param {BABYLON.Vector3} The new custom light position
  47488. */
  47489. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47490. this.customMeshPosition = position;
  47491. };
  47492. /**
  47493. * Returns the light position for light scattering effect
  47494. * @return {BABYLON.Vector3} The custom light position
  47495. */
  47496. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47497. return this.customMeshPosition;
  47498. };
  47499. /**
  47500. * Disposes the internal assets and detaches the post-process from the camera
  47501. */
  47502. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47503. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47504. if (rttIndex !== -1) {
  47505. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47506. }
  47507. this._volumetricLightScatteringRTT.dispose();
  47508. _super.prototype.dispose.call(this, camera);
  47509. };
  47510. /**
  47511. * Returns the render target texture used by the post-process
  47512. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47513. */
  47514. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47515. return this._volumetricLightScatteringRTT;
  47516. };
  47517. // Private methods
  47518. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47519. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47520. return true;
  47521. }
  47522. return false;
  47523. };
  47524. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47525. var _this = this;
  47526. var engine = scene.getEngine();
  47527. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47528. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47529. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47530. this._volumetricLightScatteringRTT.renderList = null;
  47531. this._volumetricLightScatteringRTT.renderParticles = false;
  47532. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47533. // Custom render function for submeshes
  47534. var renderSubMesh = function (subMesh) {
  47535. var mesh = subMesh.getRenderingMesh();
  47536. if (_this._meshExcluded(mesh)) {
  47537. return;
  47538. }
  47539. var scene = mesh.getScene();
  47540. var engine = scene.getEngine();
  47541. // Culling
  47542. engine.setState(subMesh.getMaterial().backFaceCulling);
  47543. // Managing instances
  47544. var batch = mesh._getInstancesRenderList(subMesh._id);
  47545. if (batch.mustReturn) {
  47546. return;
  47547. }
  47548. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47549. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47550. var effect = _this._volumetricLightScatteringPass;
  47551. if (mesh === _this.mesh) {
  47552. effect = subMesh.getMaterial().getEffect();
  47553. }
  47554. engine.enableEffect(effect);
  47555. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47556. if (mesh === _this.mesh) {
  47557. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47558. }
  47559. else {
  47560. var material = subMesh.getMaterial();
  47561. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47562. // Alpha test
  47563. if (material && material.needAlphaTesting()) {
  47564. var alphaTexture = material.getAlphaTestTexture();
  47565. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47566. if (alphaTexture) {
  47567. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47568. }
  47569. }
  47570. // Bones
  47571. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47572. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47573. }
  47574. }
  47575. // Draw
  47576. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47577. }
  47578. };
  47579. // Render target texture callbacks
  47580. var savedSceneClearColor;
  47581. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47582. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47583. savedSceneClearColor = scene.clearColor;
  47584. scene.clearColor = sceneClearColor;
  47585. });
  47586. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47587. scene.clearColor = savedSceneClearColor;
  47588. });
  47589. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47590. var engine = scene.getEngine();
  47591. var index;
  47592. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47593. renderSubMesh(opaqueSubMeshes.data[index]);
  47594. }
  47595. engine.setAlphaTesting(true);
  47596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47597. renderSubMesh(alphaTestSubMeshes.data[index]);
  47598. }
  47599. engine.setAlphaTesting(false);
  47600. if (transparentSubMeshes.length) {
  47601. // Sort sub meshes
  47602. for (index = 0; index < transparentSubMeshes.length; index++) {
  47603. var submesh = transparentSubMeshes.data[index];
  47604. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47605. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47606. }
  47607. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47608. sortedArray.sort(function (a, b) {
  47609. // Alpha index first
  47610. if (a._alphaIndex > b._alphaIndex) {
  47611. return 1;
  47612. }
  47613. if (a._alphaIndex < b._alphaIndex) {
  47614. return -1;
  47615. }
  47616. // Then distance to camera
  47617. if (a._distanceToCamera < b._distanceToCamera) {
  47618. return 1;
  47619. }
  47620. if (a._distanceToCamera > b._distanceToCamera) {
  47621. return -1;
  47622. }
  47623. return 0;
  47624. });
  47625. // Render sub meshes
  47626. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47627. for (index = 0; index < sortedArray.length; index++) {
  47628. renderSubMesh(sortedArray[index]);
  47629. }
  47630. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47631. }
  47632. };
  47633. };
  47634. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47635. var transform = scene.getTransformMatrix();
  47636. var meshPosition;
  47637. if (this.useCustomMeshPosition) {
  47638. meshPosition = this.customMeshPosition;
  47639. }
  47640. else if (this.attachedNode) {
  47641. meshPosition = this.attachedNode.position;
  47642. }
  47643. else {
  47644. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47645. }
  47646. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47647. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47648. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47649. if (this.invert)
  47650. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47651. };
  47652. // Static methods
  47653. /**
  47654. * Creates a default mesh for the Volumeric Light Scattering post-process
  47655. * @param {string} The mesh name
  47656. * @param {BABYLON.Scene} The scene where to create the mesh
  47657. * @return {BABYLON.Mesh} the default mesh
  47658. */
  47659. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47660. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47661. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47662. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47663. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47664. mesh.material = material;
  47665. return mesh;
  47666. };
  47667. __decorate([
  47668. BABYLON.serializeAsVector3()
  47669. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47670. __decorate([
  47671. BABYLON.serialize()
  47672. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47673. __decorate([
  47674. BABYLON.serialize()
  47675. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47676. __decorate([
  47677. BABYLON.serializeAsMeshReference()
  47678. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47679. __decorate([
  47680. BABYLON.serialize()
  47681. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47682. __decorate([
  47683. BABYLON.serialize()
  47684. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47685. __decorate([
  47686. BABYLON.serialize()
  47687. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47688. __decorate([
  47689. BABYLON.serialize()
  47690. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47691. __decorate([
  47692. BABYLON.serialize()
  47693. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47694. return VolumetricLightScatteringPostProcess;
  47695. }(BABYLON.PostProcess));
  47696. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47697. })(BABYLON || (BABYLON = {}));
  47698. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47699. // BABYLON.JS Chromatic Aberration GLSL Shader
  47700. // Author: Olivier Guyot
  47701. // Separates very slightly R, G and B colors on the edges of the screen
  47702. // Inspired by Francois Tarlier & Martins Upitis
  47703. var BABYLON;
  47704. (function (BABYLON) {
  47705. var LensRenderingPipeline = (function (_super) {
  47706. __extends(LensRenderingPipeline, _super);
  47707. /**
  47708. * @constructor
  47709. *
  47710. * Effect parameters are as follow:
  47711. * {
  47712. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47713. * edge_blur: number; // from 0 to x (1 for realism)
  47714. * distortion: number; // from 0 to x (1 for realism)
  47715. * grain_amount: number; // from 0 to 1
  47716. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47717. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47718. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47719. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47720. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47721. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47722. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47723. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47724. * }
  47725. * Note: if an effect parameter is unset, effect is disabled
  47726. *
  47727. * @param {string} name - The rendering pipeline name
  47728. * @param {object} parameters - An object containing all parameters (see above)
  47729. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47730. * @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)
  47731. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47732. */
  47733. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47734. var _this = this;
  47735. if (ratio === void 0) { ratio = 1.0; }
  47736. _super.call(this, scene.getEngine(), name);
  47737. // Lens effects can be of the following:
  47738. // - chromatic aberration (slight shift of RGB colors)
  47739. // - blur on the edge of the lens
  47740. // - lens distortion
  47741. // - depth-of-field blur & highlights enhancing
  47742. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47743. // - grain effect (noise or custom texture)
  47744. // Two additional texture samplers are needed:
  47745. // - depth map (for depth-of-field)
  47746. // - grain texture
  47747. /**
  47748. * The chromatic aberration PostProcess id in the pipeline
  47749. * @type {string}
  47750. */
  47751. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47752. /**
  47753. * The highlights enhancing PostProcess id in the pipeline
  47754. * @type {string}
  47755. */
  47756. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47757. /**
  47758. * The depth-of-field PostProcess id in the pipeline
  47759. * @type {string}
  47760. */
  47761. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47762. this._scene = scene;
  47763. // Fetch texture samplers
  47764. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47765. if (parameters.grain_texture) {
  47766. this._grainTexture = parameters.grain_texture;
  47767. }
  47768. else {
  47769. this._createGrainTexture();
  47770. }
  47771. // save parameters
  47772. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47773. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47774. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47775. this._distortion = parameters.distortion ? parameters.distortion : 0;
  47776. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47777. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47778. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47779. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47780. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47781. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47782. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47783. // Create effects
  47784. this._createChromaticAberrationPostProcess(ratio);
  47785. this._createHighlightsPostProcess(ratio);
  47786. this._createDepthOfFieldPostProcess(ratio / 4);
  47787. // Set up pipeline
  47788. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47791. if (this._highlightsGain === -1) {
  47792. this._disableEffect(this.HighlightsEnhancingEffect, null);
  47793. }
  47794. // Finish
  47795. scene.postProcessRenderPipelineManager.addPipeline(this);
  47796. if (cameras) {
  47797. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47798. }
  47799. }
  47800. // public methods (self explanatory)
  47801. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47802. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47803. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47804. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47805. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47806. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47807. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47808. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47809. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47810. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47811. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47812. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47813. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47814. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47815. };
  47816. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47817. this._highlightsPostProcess.updateEffect();
  47818. };
  47819. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47820. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47821. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47822. this._highlightsGain = amount;
  47823. };
  47824. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47825. if (this._highlightsGain === -1) {
  47826. this._highlightsGain = 1.0;
  47827. }
  47828. this._highlightsThreshold = amount;
  47829. };
  47830. LensRenderingPipeline.prototype.disableHighlights = function () {
  47831. this._highlightsGain = -1;
  47832. };
  47833. /**
  47834. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47835. */
  47836. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47837. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47838. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47839. this._chromaticAberrationPostProcess = undefined;
  47840. this._highlightsPostProcess = undefined;
  47841. this._depthOfFieldPostProcess = undefined;
  47842. this._grainTexture.dispose();
  47843. if (disableDepthRender)
  47844. this._scene.disableDepthRenderer();
  47845. };
  47846. // colors shifting and distortion
  47847. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47848. var _this = this;
  47849. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47850. [], // samplers
  47851. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47852. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47853. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47854. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47855. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47856. };
  47857. };
  47858. // highlights enhancing
  47859. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47860. var _this = this;
  47861. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47862. [], // samplers
  47863. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47864. this._highlightsPostProcess.onApply = function (effect) {
  47865. effect.setFloat('gain', _this._highlightsGain);
  47866. effect.setFloat('threshold', _this._highlightsThreshold);
  47867. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47868. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47869. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47870. };
  47871. };
  47872. // colors shifting and distortion
  47873. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47874. var _this = this;
  47875. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47876. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47877. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47878. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47879. this._depthOfFieldPostProcess.onApply = function (effect) {
  47880. effect.setTexture("depthSampler", _this._depthTexture);
  47881. effect.setTexture("grainSampler", _this._grainTexture);
  47882. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47883. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47884. effect.setFloat('grain_amount', _this._grainAmount);
  47885. effect.setBool('blur_noise', _this._blurNoise);
  47886. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47887. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47888. effect.setFloat('distortion', _this._distortion);
  47889. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47890. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47891. effect.setFloat('aperture', _this._dofAperture);
  47892. effect.setFloat('darken', _this._dofDarken);
  47893. effect.setFloat('edge_blur', _this._edgeBlur);
  47894. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47895. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47896. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47897. };
  47898. };
  47899. // creates a black and white random noise texture, 512x512
  47900. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47901. var size = 512;
  47902. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47903. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47904. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47905. var context = this._grainTexture.getContext();
  47906. var rand = function (min, max) {
  47907. return Math.random() * (max - min) + min;
  47908. };
  47909. var value;
  47910. for (var x = 0; x < size; x++) {
  47911. for (var y = 0; y < size; y++) {
  47912. value = Math.floor(rand(0.42, 0.58) * 255);
  47913. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47914. context.fillRect(x, y, 1, 1);
  47915. }
  47916. }
  47917. this._grainTexture.update(false);
  47918. };
  47919. return LensRenderingPipeline;
  47920. }(BABYLON.PostProcessRenderPipeline));
  47921. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47922. })(BABYLON || (BABYLON = {}));
  47923. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47924. //
  47925. // This post-process allows the modification of rendered colors by using
  47926. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47927. //
  47928. // The object needs to be provided an url to a texture containing the color
  47929. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47930. // Use an image editing software to tweak the LUT to match your needs.
  47931. //
  47932. // For an example of a color LUT, see here:
  47933. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47934. // For explanations on color grading, see here:
  47935. // http://udn.epicgames.com/Three/ColorGrading.html
  47936. //
  47937. var BABYLON;
  47938. (function (BABYLON) {
  47939. var ColorCorrectionPostProcess = (function (_super) {
  47940. __extends(ColorCorrectionPostProcess, _super);
  47941. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47942. var _this = this;
  47943. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  47944. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47945. this._colorTableTexture.anisotropicFilteringLevel = 1;
  47946. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47947. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47948. this.onApply = function (effect) {
  47949. effect.setTexture("colorTable", _this._colorTableTexture);
  47950. };
  47951. }
  47952. return ColorCorrectionPostProcess;
  47953. }(BABYLON.PostProcess));
  47954. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47957. var BABYLON;
  47958. (function (BABYLON) {
  47959. var AnaglyphFreeCamera = (function (_super) {
  47960. __extends(AnaglyphFreeCamera, _super);
  47961. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  47962. _super.call(this, name, position, scene);
  47963. this.interaxialDistance = interaxialDistance;
  47964. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47965. }
  47966. AnaglyphFreeCamera.prototype.getClassName = function () {
  47967. return "AnaglyphFreeCamera";
  47968. };
  47969. return AnaglyphFreeCamera;
  47970. }(BABYLON.FreeCamera));
  47971. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  47972. var AnaglyphArcRotateCamera = (function (_super) {
  47973. __extends(AnaglyphArcRotateCamera, _super);
  47974. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  47975. _super.call(this, name, alpha, beta, radius, target, scene);
  47976. this.interaxialDistance = interaxialDistance;
  47977. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47978. }
  47979. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  47980. return "AnaglyphArcRotateCamera";
  47981. };
  47982. return AnaglyphArcRotateCamera;
  47983. }(BABYLON.ArcRotateCamera));
  47984. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  47985. var AnaglyphGamepadCamera = (function (_super) {
  47986. __extends(AnaglyphGamepadCamera, _super);
  47987. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  47988. _super.call(this, name, position, scene);
  47989. this.interaxialDistance = interaxialDistance;
  47990. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47991. }
  47992. AnaglyphGamepadCamera.prototype.getClassName = function () {
  47993. return "AnaglyphGamepadCamera";
  47994. };
  47995. return AnaglyphGamepadCamera;
  47996. }(BABYLON.GamepadCamera));
  47997. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  47998. var AnaglyphUniversalCamera = (function (_super) {
  47999. __extends(AnaglyphUniversalCamera, _super);
  48000. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48001. _super.call(this, name, position, scene);
  48002. this.interaxialDistance = interaxialDistance;
  48003. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48004. }
  48005. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48006. return "AnaglyphUniversalCamera";
  48007. };
  48008. return AnaglyphUniversalCamera;
  48009. }(BABYLON.UniversalCamera));
  48010. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48011. var StereoscopicFreeCamera = (function (_super) {
  48012. __extends(StereoscopicFreeCamera, _super);
  48013. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48014. _super.call(this, name, position, scene);
  48015. this.interaxialDistance = interaxialDistance;
  48016. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48017. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48018. }
  48019. StereoscopicFreeCamera.prototype.getClassName = function () {
  48020. return "StereoscopicFreeCamera";
  48021. };
  48022. return StereoscopicFreeCamera;
  48023. }(BABYLON.FreeCamera));
  48024. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48025. var StereoscopicArcRotateCamera = (function (_super) {
  48026. __extends(StereoscopicArcRotateCamera, _super);
  48027. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48028. _super.call(this, name, alpha, beta, radius, target, scene);
  48029. this.interaxialDistance = interaxialDistance;
  48030. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48031. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48032. }
  48033. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48034. return "StereoscopicArcRotateCamera";
  48035. };
  48036. return StereoscopicArcRotateCamera;
  48037. }(BABYLON.ArcRotateCamera));
  48038. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48039. var StereoscopicGamepadCamera = (function (_super) {
  48040. __extends(StereoscopicGamepadCamera, _super);
  48041. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48042. _super.call(this, name, position, scene);
  48043. this.interaxialDistance = interaxialDistance;
  48044. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48045. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48046. }
  48047. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48048. return "StereoscopicGamepadCamera";
  48049. };
  48050. return StereoscopicGamepadCamera;
  48051. }(BABYLON.GamepadCamera));
  48052. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48053. var StereoscopicUniversalCamera = (function (_super) {
  48054. __extends(StereoscopicUniversalCamera, _super);
  48055. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48056. _super.call(this, name, position, scene);
  48057. this.interaxialDistance = interaxialDistance;
  48058. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48059. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48060. }
  48061. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48062. return "StereoscopicUniversalCamera";
  48063. };
  48064. return StereoscopicUniversalCamera;
  48065. }(BABYLON.UniversalCamera));
  48066. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48067. })(BABYLON || (BABYLON = {}));
  48068. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48069. var BABYLON;
  48070. (function (BABYLON) {
  48071. var HDRRenderingPipeline = (function (_super) {
  48072. __extends(HDRRenderingPipeline, _super);
  48073. /**
  48074. * @constructor
  48075. * @param {string} name - The rendering pipeline name
  48076. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48077. * @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)
  48078. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48079. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48080. */
  48081. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48082. var _this = this;
  48083. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48084. _super.call(this, scene.getEngine(), name);
  48085. /**
  48086. * Public members
  48087. */
  48088. // Gaussian Blur
  48089. /**
  48090. * Gaussian blur coefficient
  48091. * @type {number}
  48092. */
  48093. this.gaussCoeff = 0.3;
  48094. /**
  48095. * Gaussian blur mean
  48096. * @type {number}
  48097. */
  48098. this.gaussMean = 1.0;
  48099. /**
  48100. * Gaussian blur standard deviation
  48101. * @type {number}
  48102. */
  48103. this.gaussStandDev = 0.8;
  48104. /**
  48105. * Gaussian blur multiplier. Multiplies the blur effect
  48106. * @type {number}
  48107. */
  48108. this.gaussMultiplier = 4.0;
  48109. // HDR
  48110. /**
  48111. * Exposure, controls the overall intensity of the pipeline
  48112. * @type {number}
  48113. */
  48114. this.exposure = 1.0;
  48115. /**
  48116. * Minimum luminance that the post-process can output. Luminance is >= 0
  48117. * @type {number}
  48118. */
  48119. this.minimumLuminance = 1.0;
  48120. /**
  48121. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48122. * @type {number}
  48123. */
  48124. this.maximumLuminance = 1e20;
  48125. /**
  48126. * Increase rate for luminance: eye adaptation speed to dark
  48127. * @type {number}
  48128. */
  48129. this.luminanceIncreaserate = 0.5;
  48130. /**
  48131. * Decrease rate for luminance: eye adaptation speed to bright
  48132. * @type {number}
  48133. */
  48134. this.luminanceDecreaseRate = 0.5;
  48135. // Bright pass
  48136. /**
  48137. * Minimum luminance needed to compute HDR
  48138. * @type {number}
  48139. */
  48140. this.brightThreshold = 0.8;
  48141. this._needUpdate = true;
  48142. this._scene = scene;
  48143. // Bright pass
  48144. this._createBrightPassPostProcess(scene, ratio);
  48145. // Down sample X4
  48146. this._createDownSampleX4PostProcess(scene, ratio);
  48147. // Create gaussian blur post-processes
  48148. this._createGaussianBlurPostProcess(scene, ratio);
  48149. // Texture adder
  48150. this._createTextureAdderPostProcess(scene, ratio);
  48151. // Luminance generator
  48152. this._createLuminanceGeneratorPostProcess(scene);
  48153. // HDR
  48154. this._createHDRPostProcess(scene, ratio);
  48155. // Pass postprocess
  48156. if (originalPostProcess === null) {
  48157. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48158. }
  48159. else {
  48160. this._originalPostProcess = originalPostProcess;
  48161. }
  48162. // Configure pipeline
  48163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48168. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48169. var addDownSamplerPostProcess = function (id) {
  48170. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48171. };
  48172. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48173. addDownSamplerPostProcess(i);
  48174. }
  48175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48176. // Finish
  48177. scene.postProcessRenderPipelineManager.addPipeline(this);
  48178. if (cameras !== null) {
  48179. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48180. }
  48181. this.update();
  48182. }
  48183. /**
  48184. * Tells the pipeline to update its post-processes
  48185. */
  48186. HDRRenderingPipeline.prototype.update = function () {
  48187. this._needUpdate = true;
  48188. };
  48189. /**
  48190. * Returns the current calculated luminance
  48191. */
  48192. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48193. return this._hdrCurrentLuminance;
  48194. };
  48195. /**
  48196. * Returns the currently drawn luminance
  48197. */
  48198. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48199. return this._hdrOutputLuminance;
  48200. };
  48201. /**
  48202. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48203. */
  48204. HDRRenderingPipeline.prototype.dispose = function () {
  48205. this._originalPostProcess = undefined;
  48206. this._brightPassPostProcess = undefined;
  48207. this._downSampleX4PostProcess = undefined;
  48208. this._guassianBlurHPostProcess = undefined;
  48209. this._guassianBlurVPostProcess = undefined;
  48210. this._textureAdderPostProcess = undefined;
  48211. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48212. this._downSamplePostProcesses[i] = undefined;
  48213. }
  48214. this._hdrPostProcess = undefined;
  48215. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48216. };
  48217. /**
  48218. * Creates the HDR post-process and computes the luminance adaptation
  48219. */
  48220. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48221. var _this = this;
  48222. var hdrLastLuminance = 0.0;
  48223. this._hdrOutputLuminance = -1.0;
  48224. this._hdrCurrentLuminance = 1.0;
  48225. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48226. this._hdrPostProcess.onApply = function (effect) {
  48227. if (_this._hdrOutputLuminance < 0.0) {
  48228. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48229. }
  48230. else {
  48231. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48232. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48233. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48234. }
  48235. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48236. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48237. }
  48238. else {
  48239. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48240. }
  48241. }
  48242. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48243. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48244. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48245. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48246. effect.setFloat("exposure", _this.exposure);
  48247. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48248. _this._needUpdate = false;
  48249. };
  48250. };
  48251. /**
  48252. * Texture Adder post-process
  48253. */
  48254. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48255. var _this = this;
  48256. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48257. this._textureAdderPostProcess.onApply = function (effect) {
  48258. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48259. };
  48260. };
  48261. /**
  48262. * Down sample X4 post-process
  48263. */
  48264. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48265. var _this = this;
  48266. var downSampleX4Offsets = new Array(32);
  48267. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48268. this._downSampleX4PostProcess.onApply = function (effect) {
  48269. if (_this._needUpdate) {
  48270. var id = 0;
  48271. for (var i = -2; i < 2; i++) {
  48272. for (var j = -2; j < 2; j++) {
  48273. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48274. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48275. id += 2;
  48276. }
  48277. }
  48278. }
  48279. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48280. };
  48281. };
  48282. /**
  48283. * Bright pass post-process
  48284. */
  48285. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48286. var _this = this;
  48287. var brightOffsets = new Array(8);
  48288. var brightPassCallback = function (effect) {
  48289. if (_this._needUpdate) {
  48290. var sU = (1.0 / _this._brightPassPostProcess.width);
  48291. var sV = (1.0 / _this._brightPassPostProcess.height);
  48292. brightOffsets[0] = -0.5 * sU;
  48293. brightOffsets[1] = 0.5 * sV;
  48294. brightOffsets[2] = 0.5 * sU;
  48295. brightOffsets[3] = 0.5 * sV;
  48296. brightOffsets[4] = -0.5 * sU;
  48297. brightOffsets[5] = -0.5 * sV;
  48298. brightOffsets[6] = 0.5 * sU;
  48299. brightOffsets[7] = -0.5 * sV;
  48300. }
  48301. effect.setArray2("dsOffsets", brightOffsets);
  48302. effect.setFloat("brightThreshold", _this.brightThreshold);
  48303. };
  48304. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48305. this._brightPassPostProcess.onApply = brightPassCallback;
  48306. };
  48307. /**
  48308. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48309. */
  48310. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48311. var _this = this;
  48312. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48313. var luminanceOffsets = new Array(8);
  48314. var downSampleOffsets = new Array(18);
  48315. var halfDestPixelSize;
  48316. this._downSamplePostProcesses = new Array(lumSteps);
  48317. // Utils for luminance
  48318. var luminanceUpdateSourceOffsets = function (width, height) {
  48319. var sU = (1.0 / width);
  48320. var sV = (1.0 / height);
  48321. luminanceOffsets[0] = -0.5 * sU;
  48322. luminanceOffsets[1] = 0.5 * sV;
  48323. luminanceOffsets[2] = 0.5 * sU;
  48324. luminanceOffsets[3] = 0.5 * sV;
  48325. luminanceOffsets[4] = -0.5 * sU;
  48326. luminanceOffsets[5] = -0.5 * sV;
  48327. luminanceOffsets[6] = 0.5 * sU;
  48328. luminanceOffsets[7] = -0.5 * sV;
  48329. };
  48330. var luminanceUpdateDestOffsets = function (width, height) {
  48331. var id = 0;
  48332. for (var x = -1; x < 2; x++) {
  48333. for (var y = -1; y < 2; y++) {
  48334. downSampleOffsets[id] = (x) / width;
  48335. downSampleOffsets[id + 1] = (y) / height;
  48336. id += 2;
  48337. }
  48338. }
  48339. };
  48340. // Luminance callback
  48341. var luminanceCallback = function (effect) {
  48342. if (_this._needUpdate) {
  48343. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48344. }
  48345. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48346. effect.setArray2("lumOffsets", luminanceOffsets);
  48347. };
  48348. // Down sample callbacks
  48349. var downSampleCallback = function (indice) {
  48350. var i = indice;
  48351. return function (effect) {
  48352. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48353. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48354. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48355. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48356. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48357. effect.setArray2("dsOffsets", downSampleOffsets);
  48358. };
  48359. };
  48360. var downSampleAfterRenderCallback = function (effect) {
  48361. // Unpack result
  48362. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48363. 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);
  48364. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48365. };
  48366. // Create luminance post-process
  48367. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48368. 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);
  48369. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48370. // Create down sample post-processes
  48371. for (var i = lumSteps - 2; i >= 0; i--) {
  48372. var length = Math.pow(3, i);
  48373. ratio = { width: length, height: length };
  48374. var defines = "#define DOWN_SAMPLE\n";
  48375. if (i === 0) {
  48376. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48377. }
  48378. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48379. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48380. if (i === 0) {
  48381. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48382. }
  48383. }
  48384. };
  48385. /**
  48386. * Gaussian blur post-processes. Horizontal and Vertical
  48387. */
  48388. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48389. var _this = this;
  48390. var blurOffsetsW = new Array(9);
  48391. var blurOffsetsH = new Array(9);
  48392. var blurWeights = new Array(9);
  48393. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48394. // Utils for gaussian blur
  48395. var calculateBlurOffsets = function (height) {
  48396. var lastOutputDimensions = {
  48397. width: scene.getEngine().getRenderWidth(),
  48398. height: scene.getEngine().getRenderHeight()
  48399. };
  48400. for (var i = 0; i < 9; i++) {
  48401. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48402. if (height) {
  48403. blurOffsetsH[i] = value;
  48404. }
  48405. else {
  48406. blurOffsetsW[i] = value;
  48407. }
  48408. }
  48409. };
  48410. var calculateWeights = function () {
  48411. var x = 0.0;
  48412. for (var i = 0; i < 9; i++) {
  48413. x = (i - 4.0) / 4.0;
  48414. 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));
  48415. }
  48416. };
  48417. // Callback
  48418. var gaussianBlurCallback = function (height) {
  48419. return function (effect) {
  48420. if (_this._needUpdate) {
  48421. calculateWeights();
  48422. calculateBlurOffsets(height);
  48423. }
  48424. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48425. effect.setArray("blurWeights", blurWeights);
  48426. effect.setFloat("multiplier", _this.gaussMultiplier);
  48427. };
  48428. };
  48429. // Create horizontal gaussian blur post-processes
  48430. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48431. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48432. // Create vertical gaussian blur post-process
  48433. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48434. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48435. };
  48436. // Luminance generator
  48437. HDRRenderingPipeline.LUM_STEPS = 6;
  48438. return HDRRenderingPipeline;
  48439. }(BABYLON.PostProcessRenderPipeline));
  48440. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48441. })(BABYLON || (BABYLON = {}));
  48442. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48443. var BABYLON;
  48444. (function (BABYLON) {
  48445. var FaceAdjacencies = (function () {
  48446. function FaceAdjacencies() {
  48447. this.edges = new Array();
  48448. this.edgesConnectedCount = 0;
  48449. }
  48450. return FaceAdjacencies;
  48451. }());
  48452. var EdgesRenderer = (function () {
  48453. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48454. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48455. if (epsilon === void 0) { epsilon = 0.95; }
  48456. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48457. this.edgesWidthScalerForOrthographic = 1000.0;
  48458. this.edgesWidthScalerForPerspective = 50.0;
  48459. this._linesPositions = new Array();
  48460. this._linesNormals = new Array();
  48461. this._linesIndices = new Array();
  48462. this._buffers = {};
  48463. this._checkVerticesInsteadOfIndices = false;
  48464. this._source = source;
  48465. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48466. this._epsilon = epsilon;
  48467. this._prepareRessources();
  48468. this._generateEdgesLines();
  48469. }
  48470. EdgesRenderer.prototype._prepareRessources = function () {
  48471. if (this._lineShader) {
  48472. return;
  48473. }
  48474. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48475. attributes: ["position", "normal"],
  48476. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48477. });
  48478. this._lineShader.disableDepthWrite = true;
  48479. this._lineShader.backFaceCulling = false;
  48480. };
  48481. EdgesRenderer.prototype.dispose = function () {
  48482. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48483. if (buffer) {
  48484. buffer.dispose();
  48485. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48486. }
  48487. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48488. if (buffer) {
  48489. buffer.dispose();
  48490. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48491. }
  48492. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48493. this._lineShader.dispose();
  48494. };
  48495. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48496. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48497. return 0;
  48498. }
  48499. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48500. return 1;
  48501. }
  48502. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48503. return 2;
  48504. }
  48505. return -1;
  48506. };
  48507. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48508. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48509. return 0;
  48510. }
  48511. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48512. return 1;
  48513. }
  48514. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48515. return 2;
  48516. }
  48517. return -1;
  48518. };
  48519. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48520. var needToCreateLine;
  48521. if (edge === undefined) {
  48522. needToCreateLine = true;
  48523. }
  48524. else {
  48525. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48526. needToCreateLine = dotProduct < this._epsilon;
  48527. }
  48528. if (needToCreateLine) {
  48529. var offset = this._linesPositions.length / 3;
  48530. var normal = p0.subtract(p1);
  48531. normal.normalize();
  48532. // Positions
  48533. this._linesPositions.push(p0.x);
  48534. this._linesPositions.push(p0.y);
  48535. this._linesPositions.push(p0.z);
  48536. this._linesPositions.push(p0.x);
  48537. this._linesPositions.push(p0.y);
  48538. this._linesPositions.push(p0.z);
  48539. this._linesPositions.push(p1.x);
  48540. this._linesPositions.push(p1.y);
  48541. this._linesPositions.push(p1.z);
  48542. this._linesPositions.push(p1.x);
  48543. this._linesPositions.push(p1.y);
  48544. this._linesPositions.push(p1.z);
  48545. // Normals
  48546. this._linesNormals.push(p1.x);
  48547. this._linesNormals.push(p1.y);
  48548. this._linesNormals.push(p1.z);
  48549. this._linesNormals.push(-1);
  48550. this._linesNormals.push(p1.x);
  48551. this._linesNormals.push(p1.y);
  48552. this._linesNormals.push(p1.z);
  48553. this._linesNormals.push(1);
  48554. this._linesNormals.push(p0.x);
  48555. this._linesNormals.push(p0.y);
  48556. this._linesNormals.push(p0.z);
  48557. this._linesNormals.push(-1);
  48558. this._linesNormals.push(p0.x);
  48559. this._linesNormals.push(p0.y);
  48560. this._linesNormals.push(p0.z);
  48561. this._linesNormals.push(1);
  48562. // Indices
  48563. this._linesIndices.push(offset);
  48564. this._linesIndices.push(offset + 1);
  48565. this._linesIndices.push(offset + 2);
  48566. this._linesIndices.push(offset);
  48567. this._linesIndices.push(offset + 2);
  48568. this._linesIndices.push(offset + 3);
  48569. }
  48570. };
  48571. EdgesRenderer.prototype._generateEdgesLines = function () {
  48572. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48573. var indices = this._source.getIndices();
  48574. // First let's find adjacencies
  48575. var adjacencies = new Array();
  48576. var faceNormals = new Array();
  48577. var index;
  48578. var faceAdjacencies;
  48579. // Prepare faces
  48580. for (index = 0; index < indices.length; index += 3) {
  48581. faceAdjacencies = new FaceAdjacencies();
  48582. var p0Index = indices[index];
  48583. var p1Index = indices[index + 1];
  48584. var p2Index = indices[index + 2];
  48585. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48586. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48587. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48588. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48589. faceNormal.normalize();
  48590. faceNormals.push(faceNormal);
  48591. adjacencies.push(faceAdjacencies);
  48592. }
  48593. // Scan
  48594. for (index = 0; index < adjacencies.length; index++) {
  48595. faceAdjacencies = adjacencies[index];
  48596. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48597. var otherFaceAdjacencies = adjacencies[otherIndex];
  48598. if (faceAdjacencies.edgesConnectedCount === 3) {
  48599. break;
  48600. }
  48601. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48602. continue;
  48603. }
  48604. var otherP0 = indices[otherIndex * 3];
  48605. var otherP1 = indices[otherIndex * 3 + 1];
  48606. var otherP2 = indices[otherIndex * 3 + 2];
  48607. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48608. var otherEdgeIndex;
  48609. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48610. continue;
  48611. }
  48612. switch (edgeIndex) {
  48613. case 0:
  48614. if (this._checkVerticesInsteadOfIndices) {
  48615. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48616. }
  48617. else {
  48618. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48619. }
  48620. break;
  48621. case 1:
  48622. if (this._checkVerticesInsteadOfIndices) {
  48623. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48624. }
  48625. else {
  48626. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48627. }
  48628. break;
  48629. case 2:
  48630. if (this._checkVerticesInsteadOfIndices) {
  48631. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48632. }
  48633. else {
  48634. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48635. }
  48636. break;
  48637. }
  48638. if (otherEdgeIndex === -1) {
  48639. continue;
  48640. }
  48641. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48642. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48643. faceAdjacencies.edgesConnectedCount++;
  48644. otherFaceAdjacencies.edgesConnectedCount++;
  48645. if (faceAdjacencies.edgesConnectedCount === 3) {
  48646. break;
  48647. }
  48648. }
  48649. }
  48650. }
  48651. // Create lines
  48652. for (index = 0; index < adjacencies.length; index++) {
  48653. // 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
  48654. var current = adjacencies[index];
  48655. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48656. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48657. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48658. }
  48659. // Merge into a single mesh
  48660. var engine = this._source.getScene().getEngine();
  48661. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48662. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48663. this._ib = engine.createIndexBuffer(this._linesIndices);
  48664. this._indicesCount = this._linesIndices.length;
  48665. };
  48666. EdgesRenderer.prototype.render = function () {
  48667. if (!this._lineShader.isReady()) {
  48668. return;
  48669. }
  48670. var scene = this._source.getScene();
  48671. var engine = scene.getEngine();
  48672. this._lineShader._preBind();
  48673. // VBOs
  48674. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48675. scene.resetCachedMaterial();
  48676. this._lineShader.setColor4("color", this._source.edgesColor);
  48677. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48678. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48679. }
  48680. else {
  48681. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48682. }
  48683. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48684. this._lineShader.bind(this._source.getWorldMatrix());
  48685. // Draw order
  48686. engine.draw(true, 0, this._indicesCount);
  48687. this._lineShader.unbind();
  48688. engine.setDepthWrite(true);
  48689. };
  48690. return EdgesRenderer;
  48691. }());
  48692. BABYLON.EdgesRenderer = EdgesRenderer;
  48693. })(BABYLON || (BABYLON = {}));
  48694. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48695. var BABYLON;
  48696. (function (BABYLON) {
  48697. (function (TonemappingOperator) {
  48698. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48699. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48700. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48701. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48702. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48703. var TonemappingOperator = BABYLON.TonemappingOperator;
  48704. ;
  48705. var TonemapPostProcess = (function (_super) {
  48706. __extends(TonemapPostProcess, _super);
  48707. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48708. var _this = this;
  48709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48710. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48711. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48712. this._operator = _operator;
  48713. this.exposureAdjustment = exposureAdjustment;
  48714. var defines = "#define ";
  48715. if (this._operator === TonemappingOperator.Hable)
  48716. defines += "HABLE_TONEMAPPING";
  48717. else if (this._operator === TonemappingOperator.Reinhard)
  48718. defines += "REINHARD_TONEMAPPING";
  48719. else if (this._operator === TonemappingOperator.HejiDawson)
  48720. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48721. else if (this._operator === TonemappingOperator.Photographic)
  48722. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48723. //sadly a second call to create the effect.
  48724. this.updateEffect(defines);
  48725. this.onApply = function (effect) {
  48726. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48727. };
  48728. }
  48729. return TonemapPostProcess;
  48730. }(BABYLON.PostProcess));
  48731. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48732. })(BABYLON || (BABYLON = {}));
  48733. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48734. var BABYLON;
  48735. (function (BABYLON) {
  48736. var ReflectionProbe = (function () {
  48737. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48738. var _this = this;
  48739. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48740. this.name = name;
  48741. this._viewMatrix = BABYLON.Matrix.Identity();
  48742. this._target = BABYLON.Vector3.Zero();
  48743. this._add = BABYLON.Vector3.Zero();
  48744. this.invertYAxis = false;
  48745. this.position = BABYLON.Vector3.Zero();
  48746. this._scene = scene;
  48747. this._scene.reflectionProbes.push(this);
  48748. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48749. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48750. switch (faceIndex) {
  48751. case 0:
  48752. _this._add.copyFromFloats(1, 0, 0);
  48753. break;
  48754. case 1:
  48755. _this._add.copyFromFloats(-1, 0, 0);
  48756. break;
  48757. case 2:
  48758. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48759. break;
  48760. case 3:
  48761. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48762. break;
  48763. case 4:
  48764. _this._add.copyFromFloats(0, 0, 1);
  48765. break;
  48766. case 5:
  48767. _this._add.copyFromFloats(0, 0, -1);
  48768. break;
  48769. }
  48770. if (_this._attachedMesh) {
  48771. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48772. }
  48773. _this.position.addToRef(_this._add, _this._target);
  48774. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48775. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48776. });
  48777. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48778. scene.updateTransformMatrix(true);
  48779. });
  48780. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48781. }
  48782. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48783. get: function () {
  48784. return this._renderTargetTexture.refreshRate;
  48785. },
  48786. set: function (value) {
  48787. this._renderTargetTexture.refreshRate = value;
  48788. },
  48789. enumerable: true,
  48790. configurable: true
  48791. });
  48792. ReflectionProbe.prototype.getScene = function () {
  48793. return this._scene;
  48794. };
  48795. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48796. get: function () {
  48797. return this._renderTargetTexture;
  48798. },
  48799. enumerable: true,
  48800. configurable: true
  48801. });
  48802. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48803. get: function () {
  48804. return this._renderTargetTexture.renderList;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48810. this._attachedMesh = mesh;
  48811. };
  48812. ReflectionProbe.prototype.dispose = function () {
  48813. var index = this._scene.reflectionProbes.indexOf(this);
  48814. if (index !== -1) {
  48815. // Remove from the scene if found
  48816. this._scene.reflectionProbes.splice(index, 1);
  48817. }
  48818. if (this._renderTargetTexture) {
  48819. this._renderTargetTexture.dispose();
  48820. this._renderTargetTexture = null;
  48821. }
  48822. };
  48823. return ReflectionProbe;
  48824. }());
  48825. BABYLON.ReflectionProbe = ReflectionProbe;
  48826. })(BABYLON || (BABYLON = {}));
  48827. //# sourceMappingURL=babylon.reflectionProbe.js.map
  48828. var BABYLON;
  48829. (function (BABYLON) {
  48830. var SolidParticle = (function () {
  48831. /**
  48832. * Creates a Solid Particle object.
  48833. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48834. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48835. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48836. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48837. * `shapeId` (integer) is the model shape identifier in the SPS.
  48838. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48839. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48840. */
  48841. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48842. this.idx = 0; // particle global index
  48843. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48844. this.position = BABYLON.Vector3.Zero(); // position
  48845. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48846. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48847. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48848. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48849. this.alive = true; // alive
  48850. this.isVisible = true; // visibility
  48851. this._pos = 0; // index of this particle in the global "positions" array
  48852. this.shapeId = 0; // model shape id
  48853. this.idxInShape = 0; // index of the particle in its shape id
  48854. this.idx = particleIndex;
  48855. this._pos = positionIndex;
  48856. this._model = model;
  48857. this.shapeId = shapeId;
  48858. this.idxInShape = idxInShape;
  48859. this._sps = sps;
  48860. if (modelBoundingInfo) {
  48861. this._modelBoundingInfo = modelBoundingInfo;
  48862. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48863. }
  48864. }
  48865. Object.defineProperty(SolidParticle.prototype, "scale", {
  48866. /**
  48867. * legacy support, changed scale to scaling
  48868. */
  48869. get: function () {
  48870. return this.scaling;
  48871. },
  48872. set: function (scale) {
  48873. this.scaling = scale;
  48874. },
  48875. enumerable: true,
  48876. configurable: true
  48877. });
  48878. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48879. /**
  48880. * legacy support, changed quaternion to rotationQuaternion
  48881. */
  48882. get: function () {
  48883. return this.rotationQuaternion;
  48884. },
  48885. set: function (q) {
  48886. this.rotationQuaternion = q;
  48887. },
  48888. enumerable: true,
  48889. configurable: true
  48890. });
  48891. /**
  48892. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48893. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48894. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  48895. */
  48896. SolidParticle.prototype.intersectsMesh = function (target) {
  48897. if (!this._boundingInfo || !target._boundingInfo) {
  48898. return false;
  48899. }
  48900. if (this._sps._bSphereOnly) {
  48901. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48902. }
  48903. return this._boundingInfo.intersects(target._boundingInfo, false);
  48904. };
  48905. return SolidParticle;
  48906. }());
  48907. BABYLON.SolidParticle = SolidParticle;
  48908. var ModelShape = (function () {
  48909. /**
  48910. * 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.
  48911. * SPS internal tool, don't use it manually.
  48912. */
  48913. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  48914. this.shapeID = id;
  48915. this._shape = shape;
  48916. this._shapeUV = shapeUV;
  48917. this._positionFunction = posFunction;
  48918. this._vertexFunction = vtxFunction;
  48919. }
  48920. return ModelShape;
  48921. }());
  48922. BABYLON.ModelShape = ModelShape;
  48923. })(BABYLON || (BABYLON = {}));
  48924. //# sourceMappingURL=babylon.solidParticle.js.map
  48925. var BABYLON;
  48926. (function (BABYLON) {
  48927. /**
  48928. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48929. */
  48930. var SolidParticleSystem = (function () {
  48931. /**
  48932. * Creates a SPS (Solid Particle System) object.
  48933. * `name` (String) is the SPS name, this will be the underlying mesh name.
  48934. * `scene` (Scene) is the scene in which the SPS is added.
  48935. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  48936. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  48937. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  48938. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48939. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48940. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48941. */
  48942. function SolidParticleSystem(name, scene, options) {
  48943. // public members
  48944. /**
  48945. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48946. * Example : var p = SPS.particles[i];
  48947. */
  48948. this.particles = new Array();
  48949. /**
  48950. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48951. */
  48952. this.nbParticles = 0;
  48953. /**
  48954. * If the particles must ever face the camera (default false). Useful for planar particles.
  48955. */
  48956. this.billboard = false;
  48957. /**
  48958. * Recompute normals when adding a shape
  48959. */
  48960. this.recomputeNormals = true;
  48961. /**
  48962. * This a counter ofr your own usage. It's not set by any SPS functions.
  48963. */
  48964. this.counter = 0;
  48965. /**
  48966. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48967. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48968. */
  48969. this.vars = {};
  48970. this._positions = new Array();
  48971. this._indices = new Array();
  48972. this._normals = new Array();
  48973. this._colors = new Array();
  48974. this._uvs = new Array();
  48975. this._index = 0; // indices index
  48976. this._updatable = true;
  48977. this._pickable = false;
  48978. this._isVisibilityBoxLocked = false;
  48979. this._alwaysVisible = false;
  48980. this._shapeCounter = 0;
  48981. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  48982. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48983. this._computeParticleColor = true;
  48984. this._computeParticleTexture = true;
  48985. this._computeParticleRotation = true;
  48986. this._computeParticleVertex = false;
  48987. this._computeBoundingBox = false;
  48988. this._cam_axisZ = BABYLON.Vector3.Zero();
  48989. this._cam_axisY = BABYLON.Vector3.Zero();
  48990. this._cam_axisX = BABYLON.Vector3.Zero();
  48991. this._axisX = BABYLON.Axis.X;
  48992. this._axisY = BABYLON.Axis.Y;
  48993. this._axisZ = BABYLON.Axis.Z;
  48994. this._camDir = BABYLON.Vector3.Zero();
  48995. this._rotMatrix = new BABYLON.Matrix();
  48996. this._invertMatrix = new BABYLON.Matrix();
  48997. this._rotated = BABYLON.Vector3.Zero();
  48998. this._quaternion = new BABYLON.Quaternion();
  48999. this._vertex = BABYLON.Vector3.Zero();
  49000. this._normal = BABYLON.Vector3.Zero();
  49001. this._yaw = 0.0;
  49002. this._pitch = 0.0;
  49003. this._roll = 0.0;
  49004. this._halfroll = 0.0;
  49005. this._halfpitch = 0.0;
  49006. this._halfyaw = 0.0;
  49007. this._sinRoll = 0.0;
  49008. this._cosRoll = 0.0;
  49009. this._sinPitch = 0.0;
  49010. this._cosPitch = 0.0;
  49011. this._sinYaw = 0.0;
  49012. this._cosYaw = 0.0;
  49013. this._w = 0.0;
  49014. this._minimum = BABYLON.Tmp.Vector3[0];
  49015. this._maximum = BABYLON.Tmp.Vector3[1];
  49016. this._scale = BABYLON.Tmp.Vector3[2];
  49017. this._translation = BABYLON.Tmp.Vector3[3];
  49018. this._minBbox = BABYLON.Tmp.Vector3[4];
  49019. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49020. this._particlesIntersect = false;
  49021. this._bSphereOnly = false;
  49022. this._bSphereRadiusFactor = 1.0;
  49023. this.name = name;
  49024. this._scene = scene;
  49025. this._camera = scene.activeCamera;
  49026. this._pickable = options ? options.isPickable : false;
  49027. this._particlesIntersect = options ? options.particleIntersection : false;
  49028. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49029. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49030. if (options && options.updatable) {
  49031. this._updatable = options.updatable;
  49032. }
  49033. else {
  49034. this._updatable = true;
  49035. }
  49036. if (this._pickable) {
  49037. this.pickedParticles = [];
  49038. }
  49039. }
  49040. /**
  49041. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49042. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49043. */
  49044. SolidParticleSystem.prototype.buildMesh = function () {
  49045. if (this.nbParticles === 0) {
  49046. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49047. this.addShape(triangle, 1);
  49048. triangle.dispose();
  49049. }
  49050. this._positions32 = new Float32Array(this._positions);
  49051. this._uvs32 = new Float32Array(this._uvs);
  49052. this._colors32 = new Float32Array(this._colors);
  49053. if (this.recomputeNormals) {
  49054. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49055. }
  49056. this._normals32 = new Float32Array(this._normals);
  49057. this._fixedNormal32 = new Float32Array(this._normals);
  49058. var vertexData = new BABYLON.VertexData();
  49059. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49060. vertexData.indices = this._indices;
  49061. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49062. if (this._uvs32) {
  49063. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49064. ;
  49065. }
  49066. if (this._colors32) {
  49067. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49068. }
  49069. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49070. vertexData.applyToMesh(mesh, this._updatable);
  49071. this.mesh = mesh;
  49072. this.mesh.isPickable = this._pickable;
  49073. // free memory
  49074. this._positions = null;
  49075. this._normals = null;
  49076. this._uvs = null;
  49077. this._colors = null;
  49078. if (!this._updatable) {
  49079. this.particles.length = 0;
  49080. }
  49081. return mesh;
  49082. };
  49083. /**
  49084. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49085. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49086. * Thus the particles generated from `digest()` have their property `position` set yet.
  49087. * `mesh` ( Mesh ) is the mesh to be digested
  49088. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49089. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49090. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49091. */
  49092. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49093. var size = (options && options.facetNb) || 1;
  49094. var number = (options && options.number);
  49095. var delta = (options && options.delta) || 0;
  49096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49097. var meshInd = mesh.getIndices();
  49098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49101. var f = 0; // facet counter
  49102. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49103. // compute size from number
  49104. if (number) {
  49105. number = (number > totalFacets) ? totalFacets : number;
  49106. size = Math.round(totalFacets / number);
  49107. delta = 0;
  49108. }
  49109. else {
  49110. size = (size > totalFacets) ? totalFacets : size;
  49111. }
  49112. var facetPos = []; // submesh positions
  49113. var facetInd = []; // submesh indices
  49114. var facetUV = []; // submesh UV
  49115. var facetCol = []; // submesh colors
  49116. var barycenter = BABYLON.Tmp.Vector3[0];
  49117. var rand;
  49118. var sizeO = size;
  49119. while (f < totalFacets) {
  49120. size = sizeO + Math.floor((1 + delta) * Math.random());
  49121. if (f > totalFacets - size) {
  49122. size = totalFacets - f;
  49123. }
  49124. // reset temp arrays
  49125. facetPos.length = 0;
  49126. facetInd.length = 0;
  49127. facetUV.length = 0;
  49128. facetCol.length = 0;
  49129. // iterate over "size" facets
  49130. var fi = 0;
  49131. for (var j = f * 3; j < (f + size) * 3; j++) {
  49132. facetInd.push(fi);
  49133. var i = meshInd[j];
  49134. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49135. if (meshUV) {
  49136. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49137. }
  49138. if (meshCol) {
  49139. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49140. }
  49141. fi++;
  49142. }
  49143. // create a model shape for each single particle
  49144. var idx = this.nbParticles;
  49145. var shape = this._posToShape(facetPos);
  49146. var shapeUV = this._uvsToShapeUV(facetUV);
  49147. // compute the barycenter of the shape
  49148. var v;
  49149. for (v = 0; v < shape.length; v++) {
  49150. barycenter.addInPlace(shape[v]);
  49151. }
  49152. barycenter.scaleInPlace(1 / shape.length);
  49153. // shift the shape from its barycenter to the origin
  49154. for (v = 0; v < shape.length; v++) {
  49155. shape[v].subtractInPlace(barycenter);
  49156. }
  49157. var bInfo;
  49158. if (this._particlesIntersect) {
  49159. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49160. }
  49161. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49162. // add the particle in the SPS
  49163. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49164. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49165. // initialize the particle position
  49166. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49167. this._index += shape.length;
  49168. idx++;
  49169. this.nbParticles++;
  49170. this._shapeCounter++;
  49171. f += size;
  49172. }
  49173. return this;
  49174. };
  49175. //reset copy
  49176. SolidParticleSystem.prototype._resetCopy = function () {
  49177. this._copy.position.x = 0;
  49178. this._copy.position.y = 0;
  49179. this._copy.position.z = 0;
  49180. this._copy.rotation.x = 0;
  49181. this._copy.rotation.y = 0;
  49182. this._copy.rotation.z = 0;
  49183. this._copy.rotationQuaternion = null;
  49184. this._copy.scaling.x = 1;
  49185. this._copy.scaling.y = 1;
  49186. this._copy.scaling.z = 1;
  49187. this._copy.uvs.x = 0;
  49188. this._copy.uvs.y = 0;
  49189. this._copy.uvs.z = 1;
  49190. this._copy.uvs.w = 1;
  49191. this._copy.color = null;
  49192. };
  49193. // _meshBuilder : inserts the shape model in the global SPS mesh
  49194. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49195. var i;
  49196. var u = 0;
  49197. var c = 0;
  49198. var n = 0;
  49199. this._resetCopy();
  49200. if (options && options.positionFunction) {
  49201. options.positionFunction(this._copy, idx, idxInShape);
  49202. }
  49203. if (this._copy.rotationQuaternion) {
  49204. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49205. }
  49206. else {
  49207. this._yaw = this._copy.rotation.y;
  49208. this._pitch = this._copy.rotation.x;
  49209. this._roll = this._copy.rotation.z;
  49210. this._quaternionRotationYPR();
  49211. }
  49212. this._quaternionToRotationMatrix();
  49213. for (i = 0; i < shape.length; i++) {
  49214. this._vertex.x = shape[i].x;
  49215. this._vertex.y = shape[i].y;
  49216. this._vertex.z = shape[i].z;
  49217. if (options && options.vertexFunction) {
  49218. options.vertexFunction(this._copy, this._vertex, i);
  49219. }
  49220. this._vertex.x *= this._copy.scaling.x;
  49221. this._vertex.y *= this._copy.scaling.y;
  49222. this._vertex.z *= this._copy.scaling.z;
  49223. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49224. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49225. if (meshUV) {
  49226. 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);
  49227. u += 2;
  49228. }
  49229. if (this._copy.color) {
  49230. this._color = this._copy.color;
  49231. }
  49232. else if (meshCol && meshCol[c] !== undefined) {
  49233. this._color.r = meshCol[c];
  49234. this._color.g = meshCol[c + 1];
  49235. this._color.b = meshCol[c + 2];
  49236. this._color.a = meshCol[c + 3];
  49237. }
  49238. else {
  49239. this._color.r = 1;
  49240. this._color.g = 1;
  49241. this._color.b = 1;
  49242. this._color.a = 1;
  49243. }
  49244. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49245. c += 4;
  49246. if (!this.recomputeNormals && meshNor) {
  49247. this._normal.x = meshNor[n];
  49248. this._normal.y = meshNor[n + 1];
  49249. this._normal.z = meshNor[n + 2];
  49250. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49251. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49252. n += 3;
  49253. }
  49254. }
  49255. for (i = 0; i < meshInd.length; i++) {
  49256. indices.push(p + meshInd[i]);
  49257. }
  49258. if (this._pickable) {
  49259. var nbfaces = meshInd.length / 3;
  49260. for (i = 0; i < nbfaces; i++) {
  49261. this.pickedParticles.push({ idx: idx, faceId: i });
  49262. }
  49263. }
  49264. };
  49265. // returns a shape array from positions array
  49266. SolidParticleSystem.prototype._posToShape = function (positions) {
  49267. var shape = [];
  49268. for (var i = 0; i < positions.length; i += 3) {
  49269. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49270. }
  49271. return shape;
  49272. };
  49273. // returns a shapeUV array from a Vector4 uvs
  49274. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49275. var shapeUV = [];
  49276. if (uvs) {
  49277. for (var i = 0; i < uvs.length; i++)
  49278. shapeUV.push(uvs[i]);
  49279. }
  49280. return shapeUV;
  49281. };
  49282. // adds a new particle object in the particles array
  49283. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49284. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49285. };
  49286. /**
  49287. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49288. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49289. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49290. * `nb` (positive integer) the number of particles to be created from this model
  49291. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49292. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49293. */
  49294. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49295. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49296. var meshInd = mesh.getIndices();
  49297. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49298. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49299. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49300. var bbInfo;
  49301. if (this._particlesIntersect) {
  49302. bbInfo = mesh.getBoundingInfo();
  49303. }
  49304. var shape = this._posToShape(meshPos);
  49305. var shapeUV = this._uvsToShapeUV(meshUV);
  49306. var posfunc = options ? options.positionFunction : null;
  49307. var vtxfunc = options ? options.vertexFunction : null;
  49308. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49309. // particles
  49310. var idx = this.nbParticles;
  49311. for (var i = 0; i < nb; i++) {
  49312. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49313. if (this._updatable) {
  49314. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49315. }
  49316. this._index += shape.length;
  49317. idx++;
  49318. }
  49319. this.nbParticles += nb;
  49320. this._shapeCounter++;
  49321. return this._shapeCounter - 1;
  49322. };
  49323. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49324. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49325. this._resetCopy();
  49326. if (particle._model._positionFunction) {
  49327. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49328. }
  49329. if (this._copy.rotationQuaternion) {
  49330. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49331. }
  49332. else {
  49333. this._yaw = this._copy.rotation.y;
  49334. this._pitch = this._copy.rotation.x;
  49335. this._roll = this._copy.rotation.z;
  49336. this._quaternionRotationYPR();
  49337. }
  49338. this._quaternionToRotationMatrix();
  49339. this._shape = particle._model._shape;
  49340. for (var pt = 0; pt < this._shape.length; pt++) {
  49341. this._vertex.x = this._shape[pt].x;
  49342. this._vertex.y = this._shape[pt].y;
  49343. this._vertex.z = this._shape[pt].z;
  49344. if (particle._model._vertexFunction) {
  49345. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49346. }
  49347. this._vertex.x *= this._copy.scaling.x;
  49348. this._vertex.y *= this._copy.scaling.y;
  49349. this._vertex.z *= this._copy.scaling.z;
  49350. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49351. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49352. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49353. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49354. }
  49355. particle.position.x = 0.0;
  49356. particle.position.y = 0.0;
  49357. particle.position.z = 0.0;
  49358. particle.rotation.x = 0.0;
  49359. particle.rotation.y = 0.0;
  49360. particle.rotation.z = 0.0;
  49361. particle.rotationQuaternion = null;
  49362. particle.scaling.x = 1.0;
  49363. particle.scaling.y = 1.0;
  49364. particle.scaling.z = 1.0;
  49365. };
  49366. /**
  49367. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49368. */
  49369. SolidParticleSystem.prototype.rebuildMesh = function () {
  49370. for (var p = 0; p < this.particles.length; p++) {
  49371. this._rebuildParticle(this.particles[p]);
  49372. }
  49373. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49374. };
  49375. /**
  49376. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49377. * This method calls `updateParticle()` for each particle of the SPS.
  49378. * For an animated SPS, it is usually called within the render loop.
  49379. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49380. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49381. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49382. */
  49383. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49384. if (start === void 0) { start = 0; }
  49385. if (end === void 0) { end = this.nbParticles - 1; }
  49386. if (update === void 0) { update = true; }
  49387. if (!this._updatable) {
  49388. return;
  49389. }
  49390. // custom beforeUpdate
  49391. this.beforeUpdateParticles(start, end, update);
  49392. this._cam_axisX.x = 1.0;
  49393. this._cam_axisX.y = 0.0;
  49394. this._cam_axisX.z = 0.0;
  49395. this._cam_axisY.x = 0.0;
  49396. this._cam_axisY.y = 1.0;
  49397. this._cam_axisY.z = 0.0;
  49398. this._cam_axisZ.x = 0.0;
  49399. this._cam_axisZ.y = 0.0;
  49400. this._cam_axisZ.z = 1.0;
  49401. // if the particles will always face the camera
  49402. if (this.billboard) {
  49403. // compute the camera position and un-rotate it by the current mesh rotation
  49404. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49405. this._quaternionToRotationMatrix();
  49406. this._rotMatrix.invertToRef(this._invertMatrix);
  49407. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49408. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49409. this._cam_axisZ.normalize();
  49410. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49411. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49412. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49413. this._cam_axisY.normalize();
  49414. this._cam_axisX.normalize();
  49415. }
  49416. }
  49417. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49418. var idx = 0;
  49419. var index = 0;
  49420. var colidx = 0;
  49421. var colorIndex = 0;
  49422. var uvidx = 0;
  49423. var uvIndex = 0;
  49424. var pt = 0;
  49425. if (this._computeBoundingBox) {
  49426. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49427. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49428. }
  49429. // particle loop
  49430. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49431. for (var p = start; p <= end; p++) {
  49432. this._particle = this.particles[p];
  49433. this._shape = this._particle._model._shape;
  49434. this._shapeUV = this._particle._model._shapeUV;
  49435. // call to custom user function to update the particle properties
  49436. this.updateParticle(this._particle);
  49437. if (this._particle.isVisible) {
  49438. // particle rotation matrix
  49439. if (this.billboard) {
  49440. this._particle.rotation.x = 0.0;
  49441. this._particle.rotation.y = 0.0;
  49442. }
  49443. if (this._computeParticleRotation || this.billboard) {
  49444. if (this._particle.rotationQuaternion) {
  49445. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49446. }
  49447. else {
  49448. this._yaw = this._particle.rotation.y;
  49449. this._pitch = this._particle.rotation.x;
  49450. this._roll = this._particle.rotation.z;
  49451. this._quaternionRotationYPR();
  49452. }
  49453. this._quaternionToRotationMatrix();
  49454. }
  49455. // particle vertex loop
  49456. for (pt = 0; pt < this._shape.length; pt++) {
  49457. idx = index + pt * 3;
  49458. colidx = colorIndex + pt * 4;
  49459. uvidx = uvIndex + pt * 2;
  49460. this._vertex.x = this._shape[pt].x;
  49461. this._vertex.y = this._shape[pt].y;
  49462. this._vertex.z = this._shape[pt].z;
  49463. if (this._computeParticleVertex) {
  49464. this.updateParticleVertex(this._particle, this._vertex, pt);
  49465. }
  49466. // positions
  49467. this._vertex.x *= this._particle.scaling.x;
  49468. this._vertex.y *= this._particle.scaling.y;
  49469. this._vertex.z *= this._particle.scaling.z;
  49470. 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];
  49471. 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;
  49472. 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;
  49473. 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;
  49474. 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;
  49475. 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;
  49476. 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;
  49477. if (this._computeBoundingBox) {
  49478. if (this._positions32[idx] < this._minimum.x) {
  49479. this._minimum.x = this._positions32[idx];
  49480. }
  49481. if (this._positions32[idx] > this._maximum.x) {
  49482. this._maximum.x = this._positions32[idx];
  49483. }
  49484. if (this._positions32[idx + 1] < this._minimum.y) {
  49485. this._minimum.y = this._positions32[idx + 1];
  49486. }
  49487. if (this._positions32[idx + 1] > this._maximum.y) {
  49488. this._maximum.y = this._positions32[idx + 1];
  49489. }
  49490. if (this._positions32[idx + 2] < this._minimum.z) {
  49491. this._minimum.z = this._positions32[idx + 2];
  49492. }
  49493. if (this._positions32[idx + 2] > this._maximum.z) {
  49494. this._maximum.z = this._positions32[idx + 2];
  49495. }
  49496. }
  49497. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49498. if (!this._computeParticleVertex) {
  49499. this._normal.x = this._fixedNormal32[idx];
  49500. this._normal.y = this._fixedNormal32[idx + 1];
  49501. this._normal.z = this._fixedNormal32[idx + 2];
  49502. 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];
  49503. 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;
  49504. 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;
  49505. 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;
  49506. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49507. 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;
  49508. 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;
  49509. }
  49510. if (this._computeParticleColor) {
  49511. this._colors32[colidx] = this._particle.color.r;
  49512. this._colors32[colidx + 1] = this._particle.color.g;
  49513. this._colors32[colidx + 2] = this._particle.color.b;
  49514. this._colors32[colidx + 3] = this._particle.color.a;
  49515. }
  49516. if (this._computeParticleTexture) {
  49517. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49518. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49519. }
  49520. }
  49521. }
  49522. else {
  49523. for (pt = 0; pt < this._shape.length; pt++) {
  49524. idx = index + pt * 3;
  49525. colidx = colorIndex + pt * 4;
  49526. uvidx = uvIndex + pt * 2;
  49527. this._positions32[idx] = this._camera.position.x;
  49528. this._positions32[idx + 1] = this._camera.position.y;
  49529. this._positions32[idx + 2] = this._camera.position.z;
  49530. this._normals32[idx] = 0.0;
  49531. this._normals32[idx + 1] = 0.0;
  49532. this._normals32[idx + 2] = 0.0;
  49533. if (this._computeParticleColor) {
  49534. this._colors32[colidx] = this._particle.color.r;
  49535. this._colors32[colidx + 1] = this._particle.color.g;
  49536. this._colors32[colidx + 2] = this._particle.color.b;
  49537. this._colors32[colidx + 3] = this._particle.color.a;
  49538. }
  49539. if (this._computeParticleTexture) {
  49540. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49541. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49542. }
  49543. }
  49544. }
  49545. // if the particle intersections must be computed : update the bbInfo
  49546. if (this._particlesIntersect) {
  49547. var bInfo = this._particle._boundingInfo;
  49548. var bBox = bInfo.boundingBox;
  49549. var bSphere = bInfo.boundingSphere;
  49550. if (!this._bSphereOnly) {
  49551. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49552. for (var b = 0; b < bBox.vectors.length; b++) {
  49553. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49554. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49555. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49556. 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];
  49557. 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;
  49558. 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;
  49559. 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;
  49560. 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;
  49561. 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;
  49562. 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;
  49563. }
  49564. bBox._update(this.mesh._worldMatrix);
  49565. }
  49566. // place and scale the particle bouding sphere in the SPS local system, then update it
  49567. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49568. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49569. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49570. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49571. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49572. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49573. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49574. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49575. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49576. 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));
  49577. bSphere._update(this.mesh._worldMatrix);
  49578. }
  49579. // increment indexes for the next particle
  49580. index = idx + 3;
  49581. colorIndex = colidx + 4;
  49582. uvIndex = uvidx + 2;
  49583. }
  49584. // if the VBO must be updated
  49585. if (update) {
  49586. if (this._computeParticleColor) {
  49587. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49588. }
  49589. if (this._computeParticleTexture) {
  49590. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49591. }
  49592. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49593. if (!this.mesh.areNormalsFrozen) {
  49594. if (this._computeParticleVertex) {
  49595. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49596. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49597. for (var i = 0; i < this._normals32.length; i++) {
  49598. this._fixedNormal32[i] = this._normals32[i];
  49599. }
  49600. }
  49601. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49602. }
  49603. }
  49604. if (this._computeBoundingBox) {
  49605. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49606. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49607. }
  49608. this.afterUpdateParticles(start, end, update);
  49609. };
  49610. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49611. this._halfroll = this._roll * 0.5;
  49612. this._halfpitch = this._pitch * 0.5;
  49613. this._halfyaw = this._yaw * 0.5;
  49614. this._sinRoll = Math.sin(this._halfroll);
  49615. this._cosRoll = Math.cos(this._halfroll);
  49616. this._sinPitch = Math.sin(this._halfpitch);
  49617. this._cosPitch = Math.cos(this._halfpitch);
  49618. this._sinYaw = Math.sin(this._halfyaw);
  49619. this._cosYaw = Math.cos(this._halfyaw);
  49620. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49621. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49622. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49623. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49624. };
  49625. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49626. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49627. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49628. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49629. this._rotMatrix.m[3] = 0;
  49630. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49631. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49632. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49633. this._rotMatrix.m[7] = 0;
  49634. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49635. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49636. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49637. this._rotMatrix.m[11] = 0;
  49638. this._rotMatrix.m[12] = 0;
  49639. this._rotMatrix.m[13] = 0;
  49640. this._rotMatrix.m[14] = 0;
  49641. this._rotMatrix.m[15] = 1.0;
  49642. };
  49643. /**
  49644. * Disposes the SPS
  49645. */
  49646. SolidParticleSystem.prototype.dispose = function () {
  49647. this.mesh.dispose();
  49648. this.vars = null;
  49649. // drop references to internal big arrays for the GC
  49650. this._positions = null;
  49651. this._indices = null;
  49652. this._normals = null;
  49653. this._uvs = null;
  49654. this._colors = null;
  49655. this._positions32 = null;
  49656. this._normals32 = null;
  49657. this._fixedNormal32 = null;
  49658. this._uvs32 = null;
  49659. this._colors32 = null;
  49660. this.pickedParticles = null;
  49661. };
  49662. /**
  49663. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49664. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49665. */
  49666. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49667. if (!this._isVisibilityBoxLocked) {
  49668. this.mesh.refreshBoundingInfo();
  49669. }
  49670. };
  49671. /**
  49672. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49673. * @param size the size (float) of the visibility box
  49674. * note : this doesn't lock the SPS mesh bounding box.
  49675. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49676. */
  49677. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49678. var vis = size / 2;
  49679. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49680. };
  49681. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49682. // getter and setter
  49683. get: function () {
  49684. return this._alwaysVisible;
  49685. },
  49686. /**
  49687. * Sets the SPS as always visible or not
  49688. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49689. */
  49690. set: function (val) {
  49691. this._alwaysVisible = val;
  49692. this.mesh.alwaysSelectAsActiveMesh = val;
  49693. },
  49694. enumerable: true,
  49695. configurable: true
  49696. });
  49697. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49698. get: function () {
  49699. return this._isVisibilityBoxLocked;
  49700. },
  49701. /**
  49702. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49704. */
  49705. set: function (val) {
  49706. this._isVisibilityBoxLocked = val;
  49707. this.mesh.getBoundingInfo().isLocked = val;
  49708. },
  49709. enumerable: true,
  49710. configurable: true
  49711. });
  49712. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49713. // getters
  49714. get: function () {
  49715. return this._computeParticleRotation;
  49716. },
  49717. // Optimizer setters
  49718. /**
  49719. * Tells to `setParticles()` to compute the particle rotations or not.
  49720. * Default value : true. The SPS is faster when it's set to false.
  49721. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49722. */
  49723. set: function (val) {
  49724. this._computeParticleRotation = val;
  49725. },
  49726. enumerable: true,
  49727. configurable: true
  49728. });
  49729. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49730. get: function () {
  49731. return this._computeParticleColor;
  49732. },
  49733. /**
  49734. * Tells to `setParticles()` to compute the particle colors or not.
  49735. * Default value : true. The SPS is faster when it's set to false.
  49736. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49737. */
  49738. set: function (val) {
  49739. this._computeParticleColor = val;
  49740. },
  49741. enumerable: true,
  49742. configurable: true
  49743. });
  49744. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49745. get: function () {
  49746. return this._computeParticleTexture;
  49747. },
  49748. /**
  49749. * Tells to `setParticles()` to compute the particle textures or not.
  49750. * Default value : true. The SPS is faster when it's set to false.
  49751. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49752. */
  49753. set: function (val) {
  49754. this._computeParticleTexture = val;
  49755. },
  49756. enumerable: true,
  49757. configurable: true
  49758. });
  49759. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49760. get: function () {
  49761. return this._computeParticleVertex;
  49762. },
  49763. /**
  49764. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49765. * Default value : false. The SPS is faster when it's set to false.
  49766. * Note : the particle custom vertex positions aren't stored values.
  49767. */
  49768. set: function (val) {
  49769. this._computeParticleVertex = val;
  49770. },
  49771. enumerable: true,
  49772. configurable: true
  49773. });
  49774. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49775. get: function () {
  49776. return this._computeBoundingBox;
  49777. },
  49778. /**
  49779. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49780. */
  49781. set: function (val) {
  49782. this._computeBoundingBox = val;
  49783. },
  49784. enumerable: true,
  49785. configurable: true
  49786. });
  49787. // =======================================================================
  49788. // Particle behavior logic
  49789. // these following methods may be overwritten by the user to fit his needs
  49790. /**
  49791. * This function does nothing. It may be overwritten to set all the particle first values.
  49792. * The SPS doesn't call this function, you may have to call it by your own.
  49793. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49794. */
  49795. SolidParticleSystem.prototype.initParticles = function () {
  49796. };
  49797. /**
  49798. * This function does nothing. It may be overwritten to recycle a particle.
  49799. * The SPS doesn't call this function, you may have to call it by your own.
  49800. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49801. */
  49802. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49803. return particle;
  49804. };
  49805. /**
  49806. * Updates a particle : this function should be overwritten by the user.
  49807. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49808. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49809. * ex : just set a particle position or velocity and recycle conditions
  49810. */
  49811. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49812. return particle;
  49813. };
  49814. /**
  49815. * Updates a vertex of a particle : it can be overwritten by the user.
  49816. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49817. * @param particle the current particle
  49818. * @param vertex the current index of the current particle
  49819. * @param pt the index of the current vertex in the particle shape
  49820. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49821. * ex : just set a vertex particle position
  49822. */
  49823. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49824. return vertex;
  49825. };
  49826. /**
  49827. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49828. * This does nothing and may be overwritten by the user.
  49829. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49830. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49831. * @param update the boolean update value actually passed to setParticles()
  49832. */
  49833. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49834. };
  49835. /**
  49836. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49837. * This will be passed three parameters.
  49838. * This does nothing and may be overwritten by the user.
  49839. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49840. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49841. * @param update the boolean update value actually passed to setParticles()
  49842. */
  49843. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49844. };
  49845. return SolidParticleSystem;
  49846. }());
  49847. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49848. })(BABYLON || (BABYLON = {}));
  49849. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49850. var BABYLON;
  49851. (function (BABYLON) {
  49852. var Internals;
  49853. (function (Internals) {
  49854. var FileFaceOrientation = (function () {
  49855. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49856. this.name = name;
  49857. this.worldAxisForNormal = worldAxisForNormal;
  49858. this.worldAxisForFileX = worldAxisForFileX;
  49859. this.worldAxisForFileY = worldAxisForFileY;
  49860. }
  49861. return FileFaceOrientation;
  49862. }());
  49863. ;
  49864. /**
  49865. * Helper class dealing with the extraction of spherical polynomial dataArray
  49866. * from a cube map.
  49867. */
  49868. var CubeMapToSphericalPolynomialTools = (function () {
  49869. function CubeMapToSphericalPolynomialTools() {
  49870. }
  49871. /**
  49872. * Converts a cubemap to the according Spherical Polynomial data.
  49873. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49874. *
  49875. * @param cubeInfo The Cube map to extract the information from.
  49876. * @return The Spherical Polynomial data.
  49877. */
  49878. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49879. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49880. var totalSolidAngle = 0.0;
  49881. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49882. var du = 2.0 / cubeInfo.size;
  49883. var dv = du;
  49884. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49885. var minUV = du * 0.5 - 1.0;
  49886. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49887. var fileFace = this.FileFaces[faceIndex];
  49888. var dataArray = cubeInfo[fileFace.name];
  49889. var v = minUV;
  49890. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49891. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49892. // Because SP is still linear, so summation is fine in that basis.
  49893. for (var y = 0; y < cubeInfo.size; y++) {
  49894. var u = minUV;
  49895. for (var x = 0; x < cubeInfo.size; x++) {
  49896. // World direction (not normalised)
  49897. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49898. worldDirection.normalize();
  49899. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49900. if (1) {
  49901. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49902. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49903. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49904. var color = new BABYLON.Color3(r, g, b);
  49905. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49906. }
  49907. else {
  49908. if (faceIndex == 0) {
  49909. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49910. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49911. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49912. }
  49913. else if (faceIndex == 1) {
  49914. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49915. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49916. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49917. }
  49918. else if (faceIndex == 2) {
  49919. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49920. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49921. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49922. }
  49923. else if (faceIndex == 3) {
  49924. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49925. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49926. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49927. }
  49928. else if (faceIndex == 4) {
  49929. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49930. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49931. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49932. }
  49933. else if (faceIndex == 5) {
  49934. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49935. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49936. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49937. }
  49938. 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]);
  49939. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49940. }
  49941. totalSolidAngle += deltaSolidAngle;
  49942. u += du;
  49943. }
  49944. v += dv;
  49945. }
  49946. }
  49947. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49948. var correction = correctSolidAngle / totalSolidAngle;
  49949. sphericalHarmonics.scale(correction);
  49950. // Additionally scale by pi -- audit needed
  49951. sphericalHarmonics.scale(1.0 / Math.PI);
  49952. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49953. };
  49954. CubeMapToSphericalPolynomialTools.FileFaces = [
  49955. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49956. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49957. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49958. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49959. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49960. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49961. ];
  49962. return CubeMapToSphericalPolynomialTools;
  49963. }());
  49964. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49965. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49966. })(BABYLON || (BABYLON = {}));
  49967. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  49968. var BABYLON;
  49969. (function (BABYLON) {
  49970. var Internals;
  49971. (function (Internals) {
  49972. /**
  49973. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49974. */
  49975. var PanoramaToCubeMapTools = (function () {
  49976. function PanoramaToCubeMapTools() {
  49977. }
  49978. /**
  49979. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49980. *
  49981. * @param float32Array The source data.
  49982. * @param inputWidth The width of the input panorama.
  49983. * @param inputhHeight The height of the input panorama.
  49984. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49985. * @return The cubemap data
  49986. */
  49987. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49988. if (!float32Array) {
  49989. throw "ConvertPanoramaToCubemap: input cannot be null";
  49990. }
  49991. if (float32Array.length != inputWidth * inputHeight * 3) {
  49992. throw "ConvertPanoramaToCubemap: input size is wrong";
  49993. }
  49994. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49995. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49996. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49997. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49998. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49999. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50000. return {
  50001. front: textureFront,
  50002. back: textureBack,
  50003. left: textureLeft,
  50004. right: textureRight,
  50005. up: textureUp,
  50006. down: textureDown,
  50007. size: size
  50008. };
  50009. };
  50010. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50011. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50012. var textureArray = new Float32Array(buffer);
  50013. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50014. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50015. var dy = 1 / texSize;
  50016. var fy = 0;
  50017. for (var y = 0; y < texSize; y++) {
  50018. var xv1 = faceData[0];
  50019. var xv2 = faceData[2];
  50020. for (var x = 0; x < texSize; x++) {
  50021. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50022. v.normalize();
  50023. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50024. // 3 channels per pixels
  50025. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50026. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50027. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50028. xv1 = xv1.add(rotDX1);
  50029. xv2 = xv2.add(rotDX2);
  50030. }
  50031. fy += dy;
  50032. }
  50033. return textureArray;
  50034. };
  50035. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50036. var theta = Math.atan2(vDir.z, vDir.x);
  50037. var phi = Math.acos(vDir.y);
  50038. while (theta < -Math.PI)
  50039. theta += 2 * Math.PI;
  50040. while (theta > Math.PI)
  50041. theta -= 2 * Math.PI;
  50042. var dx = theta / Math.PI;
  50043. var dy = phi / Math.PI;
  50044. // recenter.
  50045. dx = dx * 0.5 + 0.5;
  50046. var px = Math.round(dx * inputWidth);
  50047. if (px < 0)
  50048. px = 0;
  50049. else if (px >= inputWidth)
  50050. px = inputWidth - 1;
  50051. var py = Math.round(dy * inputHeight);
  50052. if (py < 0)
  50053. py = 0;
  50054. else if (py >= inputHeight)
  50055. py = inputHeight - 1;
  50056. var inputY = (inputHeight - py - 1);
  50057. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50058. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50059. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50060. return {
  50061. r: r,
  50062. g: g,
  50063. b: b
  50064. };
  50065. };
  50066. PanoramaToCubeMapTools.FACE_FRONT = [
  50067. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50068. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50069. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50070. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50071. ];
  50072. PanoramaToCubeMapTools.FACE_BACK = [
  50073. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50074. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50075. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50076. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50077. ];
  50078. PanoramaToCubeMapTools.FACE_RIGHT = [
  50079. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50080. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50081. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50082. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50083. ];
  50084. PanoramaToCubeMapTools.FACE_LEFT = [
  50085. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50086. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50087. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50088. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50089. ];
  50090. PanoramaToCubeMapTools.FACE_DOWN = [
  50091. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50092. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50093. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50094. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50095. ];
  50096. PanoramaToCubeMapTools.FACE_UP = [
  50097. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50098. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50099. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50100. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50101. ];
  50102. return PanoramaToCubeMapTools;
  50103. }());
  50104. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50105. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50106. })(BABYLON || (BABYLON = {}));
  50107. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50108. var BABYLON;
  50109. (function (BABYLON) {
  50110. var Internals;
  50111. (function (Internals) {
  50112. ;
  50113. /**
  50114. * This groups tools to convert HDR texture to native colors array.
  50115. */
  50116. var HDRTools = (function () {
  50117. function HDRTools() {
  50118. }
  50119. HDRTools.Ldexp = function (mantissa, exponent) {
  50120. if (exponent > 1023) {
  50121. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50122. }
  50123. if (exponent < -1074) {
  50124. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50125. }
  50126. return mantissa * Math.pow(2, exponent);
  50127. };
  50128. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50129. if (exponent > 0) {
  50130. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50131. float32array[index + 0] = red * exponent;
  50132. float32array[index + 1] = green * exponent;
  50133. float32array[index + 2] = blue * exponent;
  50134. }
  50135. else {
  50136. float32array[index + 0] = 0;
  50137. float32array[index + 1] = 0;
  50138. float32array[index + 2] = 0;
  50139. }
  50140. };
  50141. HDRTools.readStringLine = function (uint8array, startIndex) {
  50142. var line = "";
  50143. var character = "";
  50144. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50145. character = String.fromCharCode(uint8array[i]);
  50146. if (character == "\n") {
  50147. break;
  50148. }
  50149. line += character;
  50150. }
  50151. return line;
  50152. };
  50153. /**
  50154. * Reads header information from an RGBE texture stored in a native array.
  50155. * More information on this format are available here:
  50156. * https://en.wikipedia.org/wiki/RGBE_image_format
  50157. *
  50158. * @param uint8array The binary file stored in native array.
  50159. * @return The header information.
  50160. */
  50161. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50162. var height = 0;
  50163. var width = 0;
  50164. var line = this.readStringLine(uint8array, 0);
  50165. if (line[0] != '#' || line[1] != '?') {
  50166. throw "Bad HDR Format.";
  50167. }
  50168. var endOfHeader = false;
  50169. var findFormat = false;
  50170. var lineIndex = 0;
  50171. do {
  50172. lineIndex += (line.length + 1);
  50173. line = this.readStringLine(uint8array, lineIndex);
  50174. if (line == "FORMAT=32-bit_rle_rgbe") {
  50175. findFormat = true;
  50176. }
  50177. else if (line.length == 0) {
  50178. endOfHeader = true;
  50179. }
  50180. } while (!endOfHeader);
  50181. if (!findFormat) {
  50182. throw "HDR Bad header format, unsupported FORMAT";
  50183. }
  50184. lineIndex += (line.length + 1);
  50185. line = this.readStringLine(uint8array, lineIndex);
  50186. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50187. var match = sizeRegexp.exec(line);
  50188. // TODO. Support +Y and -X if needed.
  50189. if (match.length < 3) {
  50190. throw "HDR Bad header format, no size";
  50191. }
  50192. width = parseInt(match[2]);
  50193. height = parseInt(match[1]);
  50194. if (width < 8 || width > 0x7fff) {
  50195. throw "HDR Bad header format, unsupported size";
  50196. }
  50197. lineIndex += (line.length + 1);
  50198. return {
  50199. height: height,
  50200. width: width,
  50201. dataPosition: lineIndex
  50202. };
  50203. };
  50204. /**
  50205. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50206. * This RGBE texture needs to store the information as a panorama.
  50207. *
  50208. * More information on this format are available here:
  50209. * https://en.wikipedia.org/wiki/RGBE_image_format
  50210. *
  50211. * @param buffer The binary file stored in an array buffer.
  50212. * @param size The expected size of the extracted cubemap.
  50213. * @return The Cube Map information.
  50214. */
  50215. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50216. var uint8array = new Uint8Array(buffer);
  50217. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50218. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50219. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50220. return cubeMapData;
  50221. };
  50222. /**
  50223. * Returns the pixels data extracted from an RGBE texture.
  50224. * This pixels will be stored left to right up to down in the R G B order in one array.
  50225. *
  50226. * More information on this format are available here:
  50227. * https://en.wikipedia.org/wiki/RGBE_image_format
  50228. *
  50229. * @param uint8array The binary file stored in an array buffer.
  50230. * @param hdrInfo The header information of the file.
  50231. * @return The pixels data in RGB right to left up to down order.
  50232. */
  50233. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50234. // Keep for multi format supports.
  50235. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50236. };
  50237. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50238. var num_scanlines = hdrInfo.height;
  50239. var scanline_width = hdrInfo.width;
  50240. var a, b, c, d, count;
  50241. var dataIndex = hdrInfo.dataPosition;
  50242. var index = 0, endIndex = 0, i = 0;
  50243. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50244. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50245. // 3 channels of 4 bytes per pixel in float.
  50246. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50247. var resultArray = new Float32Array(resultBuffer);
  50248. // read in each successive scanline
  50249. while (num_scanlines > 0) {
  50250. a = uint8array[dataIndex++];
  50251. b = uint8array[dataIndex++];
  50252. c = uint8array[dataIndex++];
  50253. d = uint8array[dataIndex++];
  50254. if (a != 2 || b != 2 || (c & 0x80)) {
  50255. // this file is not run length encoded
  50256. throw "HDR Bad header format, not RLE";
  50257. }
  50258. if (((c << 8) | d) != scanline_width) {
  50259. throw "HDR Bad header format, wrong scan line width";
  50260. }
  50261. index = 0;
  50262. // read each of the four channels for the scanline into the buffer
  50263. for (i = 0; i < 4; i++) {
  50264. endIndex = (i + 1) * scanline_width;
  50265. while (index < endIndex) {
  50266. a = uint8array[dataIndex++];
  50267. b = uint8array[dataIndex++];
  50268. if (a > 128) {
  50269. // a run of the same value
  50270. count = a - 128;
  50271. if ((count == 0) || (count > endIndex - index)) {
  50272. throw "HDR Bad Format, bad scanline data (run)";
  50273. }
  50274. while (count-- > 0) {
  50275. scanLineArray[index++] = b;
  50276. }
  50277. }
  50278. else {
  50279. // a non-run
  50280. count = a;
  50281. if ((count == 0) || (count > endIndex - index)) {
  50282. throw "HDR Bad Format, bad scanline data (non-run)";
  50283. }
  50284. scanLineArray[index++] = b;
  50285. if (--count > 0) {
  50286. for (var j = 0; j < count; j++) {
  50287. scanLineArray[index++] = uint8array[dataIndex++];
  50288. }
  50289. }
  50290. }
  50291. }
  50292. }
  50293. // now convert data from buffer into floats
  50294. for (i = 0; i < scanline_width; i++) {
  50295. a = scanLineArray[i];
  50296. b = scanLineArray[i + scanline_width];
  50297. c = scanLineArray[i + 2 * scanline_width];
  50298. d = scanLineArray[i + 3 * scanline_width];
  50299. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50300. }
  50301. num_scanlines--;
  50302. }
  50303. return resultArray;
  50304. };
  50305. return HDRTools;
  50306. }());
  50307. Internals.HDRTools = HDRTools;
  50308. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50309. })(BABYLON || (BABYLON = {}));
  50310. //# sourceMappingURL=babylon.tools.hdr.js.map
  50311. //_______________________________________________________________
  50312. // Extracted from CubeMapGen:
  50313. // https://code.google.com/archive/p/cubemapgen/
  50314. //
  50315. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50316. //_______________________________________________________________
  50317. var BABYLON;
  50318. (function (BABYLON) {
  50319. var Internals;
  50320. (function (Internals) {
  50321. /**
  50322. * The bounding box information used during the conversion process.
  50323. */
  50324. var CMGBoundinBox = (function () {
  50325. function CMGBoundinBox() {
  50326. this.min = new BABYLON.Vector3(0, 0, 0);
  50327. this.max = new BABYLON.Vector3(0, 0, 0);
  50328. this.clear();
  50329. }
  50330. CMGBoundinBox.prototype.clear = function () {
  50331. this.min.x = CMGBoundinBox.MAX;
  50332. this.min.y = CMGBoundinBox.MAX;
  50333. this.min.z = CMGBoundinBox.MAX;
  50334. this.max.x = CMGBoundinBox.MIN;
  50335. this.max.y = CMGBoundinBox.MIN;
  50336. this.max.z = CMGBoundinBox.MIN;
  50337. };
  50338. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50339. this.min.x = Math.min(this.min.x, x);
  50340. this.min.y = Math.min(this.min.y, y);
  50341. this.min.z = Math.min(this.min.z, z);
  50342. this.max.x = Math.max(this.max.x, x);
  50343. this.max.y = Math.max(this.max.y, y);
  50344. this.max.z = Math.max(this.max.z, z);
  50345. };
  50346. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50347. this.min.x = Math.max(this.min.x, x);
  50348. this.min.y = Math.max(this.min.y, y);
  50349. this.min.z = Math.max(this.min.z, z);
  50350. };
  50351. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50352. this.max.x = Math.min(this.max.x, x);
  50353. this.max.y = Math.min(this.max.y, y);
  50354. this.max.z = Math.min(this.max.z, z);
  50355. };
  50356. CMGBoundinBox.prototype.empty = function () {
  50357. if ((this.min.x > this.max.y) ||
  50358. (this.min.y > this.max.y) ||
  50359. (this.min.z > this.max.y)) {
  50360. return true;
  50361. }
  50362. else {
  50363. return false;
  50364. }
  50365. };
  50366. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50367. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50368. return CMGBoundinBox;
  50369. }());
  50370. /**
  50371. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50372. * required by the glossinees of a material.
  50373. *
  50374. * This only supports the cosine drop power as well as Warp fixup generation method.
  50375. *
  50376. * This is using the process from CubeMapGen described here:
  50377. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50378. */
  50379. var PMREMGenerator = (function () {
  50380. /**
  50381. * Constructor of the generator.
  50382. *
  50383. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50384. * @param inputSize The size of the cubemap faces
  50385. * @param outputSize The size of the output cubemap faces
  50386. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50387. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50388. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50389. * @param specularPower The max specular level of the desired cubemap
  50390. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50391. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50392. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50393. */
  50394. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50395. this.input = input;
  50396. this.inputSize = inputSize;
  50397. this.outputSize = outputSize;
  50398. this.maxNumMipLevels = maxNumMipLevels;
  50399. this.numChannels = numChannels;
  50400. this.isFloat = isFloat;
  50401. this.specularPower = specularPower;
  50402. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50403. this.excludeBase = excludeBase;
  50404. this.fixup = fixup;
  50405. this._outputSurface = [];
  50406. this._numMipLevels = 0;
  50407. }
  50408. /**
  50409. * Launches the filter process and return the result.
  50410. *
  50411. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50412. */
  50413. PMREMGenerator.prototype.filterCubeMap = function () {
  50414. // Init cubemap processor
  50415. this.init();
  50416. // Filters the cubemap
  50417. this.filterCubeMapMipChain();
  50418. // Returns the filtered mips.
  50419. return this._outputSurface;
  50420. };
  50421. PMREMGenerator.prototype.init = function () {
  50422. var i;
  50423. var j;
  50424. var mipLevelSize;
  50425. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50426. if (this.maxNumMipLevels == 0) {
  50427. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50428. }
  50429. //first miplevel size
  50430. mipLevelSize = this.outputSize;
  50431. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50432. for (j = 0; j < this.maxNumMipLevels; j++) {
  50433. this._outputSurface.length++;
  50434. this._outputSurface[j] = [];
  50435. //Iterate over faces for output images
  50436. for (i = 0; i < 6; i++) {
  50437. this._outputSurface[j].length++;
  50438. // Initializes a new array for the output.
  50439. if (this.isFloat) {
  50440. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50441. }
  50442. else {
  50443. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50444. }
  50445. }
  50446. //next mip level is half size
  50447. mipLevelSize >>= 1;
  50448. this._numMipLevels++;
  50449. //terminate if mip chain becomes too small
  50450. if (mipLevelSize == 0) {
  50451. this.maxNumMipLevels = j;
  50452. return;
  50453. }
  50454. }
  50455. };
  50456. //--------------------------------------------------------------------------------------
  50457. //Cube map filtering and mip chain generation.
  50458. // the cube map filtereing is specified using a number of parameters:
  50459. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50460. // indicates the region of the hemisphere to filter over for each tap.
  50461. //
  50462. // Note that the top mip level is also a filtered version of the original input images
  50463. // as well in order to create mip chains for diffuse environment illumination.
  50464. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50465. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50466. //
  50467. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50468. // is a_InitialMipAngle
  50469. //
  50470. // The angle for the subsequent levels of the mip chain are specified by their parents
  50471. // filtering angle and a per-level scale and bias
  50472. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50473. //
  50474. //--------------------------------------------------------------------------------------
  50475. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50476. // First, take count of the lighting model to modify SpecularPower
  50477. // 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;
  50478. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50479. //Cone angle start (for generating subsequent mip levels)
  50480. var currentSpecularPower = this.specularPower;
  50481. //Build filter lookup tables based on the source miplevel size
  50482. this.precomputeFilterLookupTables(this.inputSize);
  50483. // Note that we need to filter the first level before generating mipmap
  50484. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50485. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50486. // TODO : Write a function to copy and scale the base mipmap in output
  50487. // I am just lazy here and just put a high specular power value, and do some if.
  50488. if (this.excludeBase && (levelIndex == 0)) {
  50489. // 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).
  50490. currentSpecularPower = 100000.0;
  50491. }
  50492. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50493. var srcCubeImage = this.input;
  50494. var dstCubeImage = this._outputSurface[levelIndex];
  50495. var dstSize = this.outputSize >> levelIndex;
  50496. // Compute required angle.
  50497. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50498. // filter cube surfaces
  50499. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50500. // fix seams
  50501. if (this.fixup) {
  50502. this.fixupCubeEdges(dstCubeImage, dstSize);
  50503. }
  50504. // Decrease the specular power to generate the mipmap chain
  50505. // TODO : Use another method for Exclude (see first comment at start of the function
  50506. if (this.excludeBase && (levelIndex == 0)) {
  50507. currentSpecularPower = this.specularPower;
  50508. }
  50509. currentSpecularPower *= this.cosinePowerDropPerMip;
  50510. }
  50511. };
  50512. //--------------------------------------------------------------------------------------
  50513. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50514. // It allow to optimize the texel to access base on the specular power.
  50515. //--------------------------------------------------------------------------------------
  50516. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50517. // We want to find the alpha such that:
  50518. // cos(alpha)^cosinePower = epsilon
  50519. // That's: acos(epsilon^(1/cosinePower))
  50520. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50521. var angle = 180.0;
  50522. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50523. angle *= 180.0 / Math.PI; // Convert to degree
  50524. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50525. return angle;
  50526. };
  50527. //--------------------------------------------------------------------------------------
  50528. //Builds the following lookup tables prior to filtering:
  50529. // -normalizer cube map
  50530. // -tap weight lookup table
  50531. //
  50532. //--------------------------------------------------------------------------------------
  50533. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50534. var srcTexelAngle;
  50535. var iCubeFace;
  50536. //clear pre-existing normalizer cube map
  50537. this._normCubeMap = [];
  50538. //Normalized vectors per cubeface and per-texel solid angle
  50539. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50540. };
  50541. //--------------------------------------------------------------------------------------
  50542. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50543. //
  50544. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50545. //
  50546. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50547. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50548. // below
  50549. //--------------------------------------------------------------------------------------
  50550. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50551. var iCubeFace;
  50552. var u;
  50553. var v;
  50554. //iterate over cube faces
  50555. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50556. //First three channels for norm cube, and last channel for solid angle
  50557. this._normCubeMap.push(new Float32Array(size * size * 4));
  50558. //fast texture walk, build normalizer cube map
  50559. var facesData = this.input[iCubeFace];
  50560. for (v = 0; v < size; v++) {
  50561. for (u = 0; u < size; u++) {
  50562. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50563. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50564. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50565. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50566. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50567. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50568. }
  50569. }
  50570. }
  50571. };
  50572. //--------------------------------------------------------------------------------------
  50573. // Convert cubemap face texel coordinates and face idx to 3D vector
  50574. // note the U and V coords are integer coords and range from 0 to size-1
  50575. // this routine can be used to generate a normalizer cube map
  50576. //--------------------------------------------------------------------------------------
  50577. // SL BEGIN
  50578. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50579. var nvcU;
  50580. var nvcV;
  50581. var tempVec;
  50582. // Change from original AMD code
  50583. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50584. // + 0.5f is for texel center addressing
  50585. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50586. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50587. // warp fixup
  50588. if (fixup && size > 1) {
  50589. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50590. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50591. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50592. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50593. }
  50594. // Get current vector
  50595. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50596. // U contribution
  50597. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50598. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50599. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50600. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50601. // V contribution and Sum
  50602. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50603. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50604. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50605. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50606. //add face axis
  50607. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50608. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50609. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50610. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50611. //normalize vector
  50612. PMREMGenerator._vectorTemp.normalize();
  50613. return PMREMGenerator._vectorTemp;
  50614. };
  50615. //--------------------------------------------------------------------------------------
  50616. // Convert 3D vector to cubemap face texel coordinates and face idx
  50617. // note the U and V coords are integer coords and range from 0 to size-1
  50618. // this routine can be used to generate a normalizer cube map
  50619. //
  50620. // returns face IDX and texel coords
  50621. //--------------------------------------------------------------------------------------
  50622. // SL BEGIN
  50623. /*
  50624. Mapping Texture Coordinates to Cube Map Faces
  50625. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50626. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50627. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50628. map arrangement in Pixar's RenderMan package.
  50629. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50630. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50631. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50632. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50633. the major axis direction). The target column in the table below explains how the major axis direction
  50634. maps to the 2D image of a particular cube map target.
  50635. major axis
  50636. direction target sc tc ma
  50637. ---------- --------------------------------- --- --- ---
  50638. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50639. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50640. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50641. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50642. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50643. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50644. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50645. an updated (s,t) is calculated as follows
  50646. s = ( sc/|ma| + 1 ) / 2
  50647. t = ( tc/|ma| + 1 ) / 2
  50648. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50649. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50650. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50651. */
  50652. // Note this method return U and V in range from 0 to size-1
  50653. // SL END
  50654. // Store the information in vector3 for convenience (faceindex, u, v)
  50655. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50656. var maxCoord;
  50657. var faceIdx;
  50658. //absolute value 3
  50659. var absX = Math.abs(x);
  50660. var absY = Math.abs(y);
  50661. var absZ = Math.abs(z);
  50662. if (absX >= absY && absX >= absZ) {
  50663. maxCoord = absX;
  50664. if (x >= 0) {
  50665. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50666. }
  50667. else {
  50668. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50669. }
  50670. }
  50671. else if (absY >= absX && absY >= absZ) {
  50672. maxCoord = absY;
  50673. if (y >= 0) {
  50674. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50675. }
  50676. else {
  50677. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50678. }
  50679. }
  50680. else {
  50681. maxCoord = absZ;
  50682. if (z >= 0) {
  50683. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50684. }
  50685. else {
  50686. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50687. }
  50688. }
  50689. //divide through by max coord so face vector lies on cube face
  50690. var scale = 1 / maxCoord;
  50691. x *= scale;
  50692. y *= scale;
  50693. z *= scale;
  50694. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50695. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50696. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50697. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50698. // Modify original AMD code to return value from 0 to Size - 1
  50699. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50700. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50701. PMREMGenerator._vectorTemp.x = faceIdx;
  50702. PMREMGenerator._vectorTemp.y = u;
  50703. PMREMGenerator._vectorTemp.z = v;
  50704. return PMREMGenerator._vectorTemp;
  50705. };
  50706. //--------------------------------------------------------------------------------------
  50707. //Original code from Ignacio CastaÒo
  50708. // This formula is from Manne ÷hrstrˆm's thesis.
  50709. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50710. // cube face and return the area of the projection of that portion on the
  50711. // surface of the sphere.
  50712. //--------------------------------------------------------------------------------------
  50713. PMREMGenerator.prototype.areaElement = function (x, y) {
  50714. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50715. };
  50716. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50717. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50718. // (+ 0.5f is for texel center addressing)
  50719. u = (2.0 * (u + 0.5) / size) - 1.0;
  50720. v = (2.0 * (v + 0.5) / size) - 1.0;
  50721. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50722. var invResolution = 1.0 / size;
  50723. // U and V are the -1..1 texture coordinate on the current face.
  50724. // Get projected area for this texel
  50725. var x0 = u - invResolution;
  50726. var y0 = v - invResolution;
  50727. var x1 = u + invResolution;
  50728. var y1 = v + invResolution;
  50729. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50730. return solidAngle;
  50731. };
  50732. //--------------------------------------------------------------------------------------
  50733. //The key to the speed of these filtering routines is to quickly define a per-face
  50734. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50735. // Later these pixels are selectively processed based on their dot products to see if
  50736. // they reside within the filtering cone.
  50737. //
  50738. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50739. // of the number of texels needed to be covered in width and height order to filter the
  50740. // region. the bounding box for the center taps face is defined first, and if the
  50741. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50742. // defined next
  50743. //--------------------------------------------------------------------------------------
  50744. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50745. // note that pixels within these regions may be rejected
  50746. // based on the anlge
  50747. var iCubeFace;
  50748. var u;
  50749. var v;
  50750. // bounding box per face to specify region to process
  50751. var filterExtents = [];
  50752. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50753. filterExtents.push(new CMGBoundinBox());
  50754. }
  50755. // min angle a src texel can cover (in degrees)
  50756. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50757. // angle about center tap to define filter cone
  50758. // filter angle is 1/2 the cone angle
  50759. var filterAngle = filterConeAngle / 2.0;
  50760. //ensure filter angle is larger than a texel
  50761. if (filterAngle < srcTexelAngle) {
  50762. filterAngle = srcTexelAngle;
  50763. }
  50764. //ensure filter cone is always smaller than the hemisphere
  50765. if (filterAngle > 90.0) {
  50766. filterAngle = 90.0;
  50767. }
  50768. // the maximum number of texels in 1D the filter cone angle will cover
  50769. // used to determine bounding box size for filter extents
  50770. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50771. // ensure conservative region always covers at least one texel
  50772. if (filterSize < 1) {
  50773. filterSize = 1;
  50774. }
  50775. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50776. // reside within the cone angle
  50777. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50778. // process required faces
  50779. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50780. //iterate over dst cube map face texel
  50781. for (v = 0; v < dstSize; v++) {
  50782. for (u = 0; u < dstSize; u++) {
  50783. //get center tap direction
  50784. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50785. //clear old per-face filter extents
  50786. this.clearFilterExtents(filterExtents);
  50787. //define per-face filter extents
  50788. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50789. //perform filtering of src faces using filter extents
  50790. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50791. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50792. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50793. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50794. }
  50795. }
  50796. }
  50797. };
  50798. //--------------------------------------------------------------------------------------
  50799. //Clear filter extents for the 6 cube map faces
  50800. //--------------------------------------------------------------------------------------
  50801. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50802. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50803. filterExtents[iCubeFaces].clear();
  50804. }
  50805. };
  50806. //--------------------------------------------------------------------------------------
  50807. //Define per-face bounding box filter extents
  50808. //
  50809. // These define conservative texel regions in each of the faces the filter can possibly
  50810. // process. When the pixels in the regions are actually processed, the dot product
  50811. // between the tap vector and the center tap vector is used to determine the weight of
  50812. // the tap and whether or not the tap is within the cone.
  50813. //
  50814. //--------------------------------------------------------------------------------------
  50815. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50816. //neighboring face and bleed over amount, and width of BBOX for
  50817. // left, right, top, and bottom edges of this face
  50818. var bleedOverAmount = [0, 0, 0, 0];
  50819. var bleedOverBBoxMin = [0, 0, 0, 0];
  50820. var bleedOverBBoxMax = [0, 0, 0, 0];
  50821. var neighborFace;
  50822. var neighborEdge;
  50823. var oppositeFaceIdx;
  50824. //get face idx, and u, v info from center tap dir
  50825. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50826. var faceIdx = result.x;
  50827. var u = result.y;
  50828. var v = result.z;
  50829. //define bbox size within face
  50830. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50831. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50832. filterExtents[faceIdx].clampMin(0, 0, 0);
  50833. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50834. //u and v extent in face corresponding to center tap
  50835. var minU = filterExtents[faceIdx].min.x;
  50836. var minV = filterExtents[faceIdx].min.y;
  50837. var maxU = filterExtents[faceIdx].max.x;
  50838. var maxV = filterExtents[faceIdx].max.y;
  50839. //bleed over amounts for face across u=0 edge (left)
  50840. bleedOverAmount[0] = (bboxSize - u);
  50841. bleedOverBBoxMin[0] = minV;
  50842. bleedOverBBoxMax[0] = maxV;
  50843. //bleed over amounts for face across u=1 edge (right)
  50844. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50845. bleedOverBBoxMin[1] = minV;
  50846. bleedOverBBoxMax[1] = maxV;
  50847. //bleed over to face across v=0 edge (up)
  50848. bleedOverAmount[2] = (bboxSize - v);
  50849. bleedOverBBoxMin[2] = minU;
  50850. bleedOverBBoxMax[2] = maxU;
  50851. //bleed over to face across v=1 edge (down)
  50852. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50853. bleedOverBBoxMin[3] = minU;
  50854. bleedOverBBoxMax[3] = maxU;
  50855. //compute bleed over regions in neighboring faces
  50856. for (var i = 0; i < 4; i++) {
  50857. if (bleedOverAmount[i] > 0) {
  50858. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50859. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50860. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50861. // be flipped: the cases are
  50862. // if a left edge mates with a left or bottom edge on the neighbor
  50863. // if a top edge mates with a top or right edge on the neighbor
  50864. // if a right edge mates with a right or top edge on the neighbor
  50865. // if a bottom edge mates with a bottom or left edge on the neighbor
  50866. //Seeing as the edges are enumerated as follows
  50867. // left =0
  50868. // right =1
  50869. // top =2
  50870. // bottom =3
  50871. //
  50872. // so if the edge enums are the same, or the sum of the enums == 3,
  50873. // the bbox needs to be flipped
  50874. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50875. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50876. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50877. }
  50878. //The way the bounding box is extended onto the neighboring face
  50879. // depends on which edge of neighboring face abuts with this one
  50880. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50881. case PMREMGenerator.CP_EDGE_LEFT:
  50882. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50883. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50884. break;
  50885. case PMREMGenerator.CP_EDGE_RIGHT:
  50886. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50887. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50888. break;
  50889. case PMREMGenerator.CP_EDGE_TOP:
  50890. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50891. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50892. break;
  50893. case PMREMGenerator.CP_EDGE_BOTTOM:
  50894. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50895. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50896. break;
  50897. }
  50898. //clamp filter extents in non-center tap faces to remain within surface
  50899. filterExtents[neighborFace].clampMin(0, 0, 0);
  50900. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50901. }
  50902. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50903. // from the center tap face, then process the opposite face entirely for now.
  50904. //Note that the cases in which this happens, what usually happens is that
  50905. // more than one edge bleeds onto the opposite face, and the bounding box
  50906. // encompasses the entire cube map face.
  50907. if (bleedOverAmount[i] > srcSize) {
  50908. //determine opposite face
  50909. switch (faceIdx) {
  50910. case PMREMGenerator.CP_FACE_X_POS:
  50911. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50912. break;
  50913. case PMREMGenerator.CP_FACE_X_NEG:
  50914. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50915. break;
  50916. case PMREMGenerator.CP_FACE_Y_POS:
  50917. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50918. break;
  50919. case PMREMGenerator.CP_FACE_Y_NEG:
  50920. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50921. break;
  50922. case PMREMGenerator.CP_FACE_Z_POS:
  50923. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50924. break;
  50925. case PMREMGenerator.CP_FACE_Z_NEG:
  50926. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50927. break;
  50928. default:
  50929. break;
  50930. }
  50931. //just encompass entire face for now
  50932. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50933. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50934. }
  50935. }
  50936. };
  50937. //--------------------------------------------------------------------------------------
  50938. //ProcessFilterExtents
  50939. // Process bounding box in each cube face
  50940. //
  50941. //--------------------------------------------------------------------------------------
  50942. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50943. //accumulators are 64-bit floats in order to have the precision needed
  50944. // over a summation of a large number of pixels
  50945. var dstAccum = [0, 0, 0, 0];
  50946. var weightAccum = 0;
  50947. var k = 0;
  50948. var nSrcChannels = this.numChannels;
  50949. // norm cube map and srcCubeMap have same face width
  50950. var faceWidth = srcSize;
  50951. //amount to add to pointer to move to next scanline in images
  50952. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50953. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50954. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50955. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50956. // iterate over cubefaces
  50957. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50958. //if bbox is non empty
  50959. if (!filterExtents[iFaceIdx].empty()) {
  50960. var uStart = filterExtents[iFaceIdx].min.x;
  50961. var vStart = filterExtents[iFaceIdx].min.y;
  50962. var uEnd = filterExtents[iFaceIdx].max.x;
  50963. var vEnd = filterExtents[iFaceIdx].max.y;
  50964. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50965. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50966. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50967. for (var v = vStart; v <= vEnd; v++) {
  50968. var normCubeRowWalk = 0;
  50969. var srcCubeRowWalk = 0;
  50970. for (var u = uStart; u <= uEnd; u++) {
  50971. //pointer to direction in cube map associated with texel
  50972. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50973. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50974. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50975. //check dot product to see if texel is within cone
  50976. var tapDotProd = texelVectX * centerTapDir.x +
  50977. texelVectY * centerTapDir.y +
  50978. texelVectZ * centerTapDir.z;
  50979. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50980. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50981. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50982. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50983. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50984. // so just adding one to specularpower do the trick.
  50985. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50986. //iterate over channels
  50987. for (k = 0; k < nSrcChannels; k++) {
  50988. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50989. srcCubeRowWalk++;
  50990. }
  50991. weightAccum += weight; //accumulate weight
  50992. }
  50993. else {
  50994. //step across source pixel
  50995. srcCubeRowWalk += nSrcChannels;
  50996. }
  50997. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50998. }
  50999. startIndexNormCubeMap += normCubePitch;
  51000. startIndexSrcCubeMap += srcCubePitch;
  51001. }
  51002. }
  51003. }
  51004. //divide through by weights if weight is non zero
  51005. if (weightAccum != 0.0) {
  51006. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51007. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51008. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51009. if (this.numChannels > 3) {
  51010. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51011. }
  51012. }
  51013. else {
  51014. // otherwise sample nearest
  51015. // get face idx and u, v texel coordinate in face
  51016. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51017. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51018. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51019. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51020. if (this.numChannels > 3) {
  51021. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51022. }
  51023. }
  51024. return PMREMGenerator._vectorTemp;
  51025. };
  51026. //--------------------------------------------------------------------------------------
  51027. // Fixup cube edges
  51028. //
  51029. // average texels on cube map faces across the edges
  51030. // WARP/BENT Method Only.
  51031. //--------------------------------------------------------------------------------------
  51032. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51033. var k;
  51034. var j;
  51035. var i;
  51036. var iFace;
  51037. var iCorner = 0;
  51038. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51039. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51040. // note that if functionality to filter across the three texels for each corner, then
  51041. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51042. var cornerPtr = [
  51043. [[], [], []],
  51044. [[], [], []],
  51045. [[], [], []],
  51046. [[], [], []],
  51047. [[], [], []],
  51048. [[], [], []],
  51049. [[], [], []],
  51050. [[], [], []]
  51051. ];
  51052. //if there is no fixup, or fixup width = 0, do nothing
  51053. if (cubeMapSize < 1) {
  51054. return;
  51055. }
  51056. //special case 1x1 cubemap, average face colors
  51057. if (cubeMapSize == 1) {
  51058. //iterate over channels
  51059. for (k = 0; k < this.numChannels; k++) {
  51060. var accum = 0.0;
  51061. //iterate over faces to accumulate face colors
  51062. for (iFace = 0; iFace < 6; iFace++) {
  51063. accum += cubeMap[iFace][k];
  51064. }
  51065. //compute average over 6 face colors
  51066. accum /= 6.0;
  51067. //iterate over faces to distribute face colors
  51068. for (iFace = 0; iFace < 6; iFace++) {
  51069. cubeMap[iFace][k] = accum;
  51070. }
  51071. }
  51072. return;
  51073. }
  51074. //iterate over faces to collect list of corner texel pointers
  51075. for (iFace = 0; iFace < 6; iFace++) {
  51076. //the 4 corner pointers for this face
  51077. faceCornerStartIndicies[0] = [iFace, 0];
  51078. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51079. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51080. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51081. //iterate over face corners to collect cube corner pointers
  51082. for (iCorner = 0; iCorner < 4; iCorner++) {
  51083. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51084. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51085. cornerNumPtrs[corner]++;
  51086. }
  51087. }
  51088. //iterate over corners to average across corner tap values
  51089. for (iCorner = 0; iCorner < 8; iCorner++) {
  51090. for (k = 0; k < this.numChannels; k++) {
  51091. var cornerTapAccum = 0.0;
  51092. //iterate over corner texels and average results
  51093. for (i = 0; i < 3; i++) {
  51094. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51095. }
  51096. //divide by 3 to compute average of corner tap values
  51097. cornerTapAccum *= (1.0 / 3.0);
  51098. //iterate over corner texels and average results
  51099. for (i = 0; i < 3; i++) {
  51100. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51101. }
  51102. }
  51103. }
  51104. //iterate over the twelve edges of the cube to average across edges
  51105. for (i = 0; i < 12; i++) {
  51106. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51107. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51108. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51109. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51110. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51111. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51112. var edgeWalk = 0;
  51113. var neighborEdgeWalk = 0;
  51114. //Determine walking pointers based on edge type
  51115. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51116. switch (edge) {
  51117. case PMREMGenerator.CP_EDGE_LEFT:
  51118. // no change to faceEdgeStartPtr
  51119. edgeWalk = this.numChannels * cubeMapSize;
  51120. break;
  51121. case PMREMGenerator.CP_EDGE_RIGHT:
  51122. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51123. edgeWalk = this.numChannels * cubeMapSize;
  51124. break;
  51125. case PMREMGenerator.CP_EDGE_TOP:
  51126. // no change to faceEdgeStartPtr
  51127. edgeWalk = this.numChannels;
  51128. break;
  51129. case PMREMGenerator.CP_EDGE_BOTTOM:
  51130. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51131. edgeWalk = this.numChannels;
  51132. break;
  51133. }
  51134. //For certain types of edge abutments, the neighbor edge walk needs to
  51135. // be flipped: the cases are
  51136. // if a left edge mates with a left or bottom edge on the neighbor
  51137. // if a top edge mates with a top or right edge on the neighbor
  51138. // if a right edge mates with a right or top edge on the neighbor
  51139. // if a bottom edge mates with a bottom or left edge on the neighbor
  51140. //Seeing as the edges are enumerated as follows
  51141. // left =0
  51142. // right =1
  51143. // top =2
  51144. // bottom =3
  51145. //
  51146. //If the edge enums are the same, or the sum of the enums == 3,
  51147. // the neighbor edge walk needs to be flipped
  51148. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51149. switch (neighborEdge) {
  51150. case PMREMGenerator.CP_EDGE_LEFT:
  51151. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51152. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51153. break;
  51154. case PMREMGenerator.CP_EDGE_RIGHT:
  51155. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51156. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51157. break;
  51158. case PMREMGenerator.CP_EDGE_TOP:
  51159. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51160. neighborEdgeWalk = -this.numChannels;
  51161. break;
  51162. case PMREMGenerator.CP_EDGE_BOTTOM:
  51163. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51164. neighborEdgeWalk = -this.numChannels;
  51165. break;
  51166. }
  51167. }
  51168. else {
  51169. //swapped direction neighbor edge walk
  51170. switch (neighborEdge) {
  51171. case PMREMGenerator.CP_EDGE_LEFT:
  51172. //no change to neighborEdgeStartPtr for this case since it points
  51173. // to the upper left corner already
  51174. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51175. break;
  51176. case PMREMGenerator.CP_EDGE_RIGHT:
  51177. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51178. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51179. break;
  51180. case PMREMGenerator.CP_EDGE_TOP:
  51181. //no change to neighborEdgeStartPtr for this case since it points
  51182. // to the upper left corner already
  51183. neighborEdgeWalk = this.numChannels;
  51184. break;
  51185. case PMREMGenerator.CP_EDGE_BOTTOM:
  51186. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51187. neighborEdgeWalk = this.numChannels;
  51188. break;
  51189. }
  51190. }
  51191. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51192. //nearby neighborhood
  51193. //step ahead one texel on edge
  51194. edgeStartIndex += edgeWalk;
  51195. neighborEdgeStartIndex += neighborEdgeWalk;
  51196. // note that this loop does not process the corner texels, since they have already been
  51197. // averaged across faces across earlier
  51198. for (j = 1; j < (cubeMapSize - 1); j++) {
  51199. //for each set of taps along edge, average them
  51200. // and rewrite the results into the edges
  51201. for (k = 0; k < this.numChannels; k++) {
  51202. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51203. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51204. //compute average of tap intensity values
  51205. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51206. //propagate average of taps to edge taps
  51207. cubeMap[face][edgeStartIndex + k] = avgTap;
  51208. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51209. }
  51210. edgeStartIndex += edgeWalk;
  51211. neighborEdgeStartIndex += neighborEdgeWalk;
  51212. }
  51213. }
  51214. };
  51215. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51216. PMREMGenerator.CP_UDIR = 0;
  51217. PMREMGenerator.CP_VDIR = 1;
  51218. PMREMGenerator.CP_FACEAXIS = 2;
  51219. //used to index cube faces
  51220. PMREMGenerator.CP_FACE_X_POS = 0;
  51221. PMREMGenerator.CP_FACE_X_NEG = 1;
  51222. PMREMGenerator.CP_FACE_Y_POS = 2;
  51223. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51224. PMREMGenerator.CP_FACE_Z_POS = 4;
  51225. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51226. //used to index image edges
  51227. // NOTE.. the actual number corresponding to the edge is important
  51228. // do not change these, or the code will break
  51229. //
  51230. // CP_EDGE_LEFT is u = 0
  51231. // CP_EDGE_RIGHT is u = width-1
  51232. // CP_EDGE_TOP is v = 0
  51233. // CP_EDGE_BOTTOM is v = height-1
  51234. PMREMGenerator.CP_EDGE_LEFT = 0;
  51235. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51236. PMREMGenerator.CP_EDGE_TOP = 2;
  51237. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51238. //corners of CUBE map (P or N specifys if it corresponds to the
  51239. // positive or negative direction each of X, Y, and Z
  51240. PMREMGenerator.CP_CORNER_NNN = 0;
  51241. PMREMGenerator.CP_CORNER_NNP = 1;
  51242. PMREMGenerator.CP_CORNER_NPN = 2;
  51243. PMREMGenerator.CP_CORNER_NPP = 3;
  51244. PMREMGenerator.CP_CORNER_PNN = 4;
  51245. PMREMGenerator.CP_CORNER_PNP = 5;
  51246. PMREMGenerator.CP_CORNER_PPN = 6;
  51247. PMREMGenerator.CP_CORNER_PPP = 7;
  51248. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51249. //3x2 matrices that map cube map indexing vectors in 3d
  51250. // (after face selection and divide through by the
  51251. // _ABSOLUTE VALUE_ of the max coord)
  51252. // into NVC space
  51253. //Note this currently assumes the D3D cube face ordering and orientation
  51254. PMREMGenerator._sgFace2DMapping = [
  51255. //XPOS face
  51256. [[0, 0, -1],
  51257. [0, -1, 0],
  51258. [1, 0, 0]],
  51259. //XNEG face
  51260. [[0, 0, 1],
  51261. [0, -1, 0],
  51262. [-1, 0, 0]],
  51263. //YPOS face
  51264. [[1, 0, 0],
  51265. [0, 0, 1],
  51266. [0, 1, 0]],
  51267. //YNEG face
  51268. [[1, 0, 0],
  51269. [0, 0, -1],
  51270. [0, -1, 0]],
  51271. //ZPOS face
  51272. [[1, 0, 0],
  51273. [0, -1, 0],
  51274. [0, 0, 1]],
  51275. //ZNEG face
  51276. [[-1, 0, 0],
  51277. [0, -1, 0],
  51278. [0, 0, -1]],
  51279. ];
  51280. //------------------------------------------------------------------------------
  51281. // D3D cube map face specification
  51282. // mapping from 3D x,y,z cube map lookup coordinates
  51283. // to 2D within face u,v coordinates
  51284. //
  51285. // --------------------> U direction
  51286. // | (within-face texture space)
  51287. // | _____
  51288. // | | |
  51289. // | | +Y |
  51290. // | _____|_____|_____ _____
  51291. // | | | | | |
  51292. // | | -X | +Z | +X | -Z |
  51293. // | |_____|_____|_____|_____|
  51294. // | | |
  51295. // | | -Y |
  51296. // | |_____|
  51297. // |
  51298. // v V direction
  51299. // (within-face texture space)
  51300. //------------------------------------------------------------------------------
  51301. //Information about neighbors and how texture coorrdinates change across faces
  51302. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51303. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51304. //Note this currently assumes the D3D cube face ordering and orientation
  51305. PMREMGenerator._sgCubeNgh = [
  51306. //XPOS face
  51307. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51308. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51309. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51310. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51311. //XNEG face
  51312. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51313. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51314. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51315. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51316. //YPOS face
  51317. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51318. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51319. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51320. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51321. //YNEG face
  51322. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51323. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51324. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51325. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51326. //ZPOS face
  51327. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51328. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51329. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51330. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51331. //ZNEG face
  51332. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51333. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51334. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51335. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51336. ];
  51337. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51338. // this table is used to average over the edges.
  51339. PMREMGenerator._sgCubeEdgeList = [
  51340. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51341. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51342. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51343. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51344. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51345. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51346. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51347. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51348. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51349. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51350. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51351. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51352. ];
  51353. //Information about which of the 8 cube corners are correspond to the
  51354. // the 4 corners in each cube face
  51355. // the order is upper left, upper right, lower left, lower right
  51356. PMREMGenerator._sgCubeCornerList = [
  51357. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51358. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51359. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51360. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51361. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51362. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51363. ];
  51364. return PMREMGenerator;
  51365. }());
  51366. Internals.PMREMGenerator = PMREMGenerator;
  51367. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51368. })(BABYLON || (BABYLON = {}));
  51369. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  51370. var BABYLON;
  51371. (function (BABYLON) {
  51372. /**
  51373. * This represents a texture coming from an HDR input.
  51374. *
  51375. * The only supported format is currently panorama picture stored in RGBE format.
  51376. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51377. */
  51378. var HDRCubeTexture = (function (_super) {
  51379. __extends(HDRCubeTexture, _super);
  51380. /**
  51381. * Instantiates an HDRTexture from the following parameters.
  51382. *
  51383. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51384. * @param scene The scene the texture will be used in
  51385. * @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.
  51386. * @param noMipmap Forces to not generate the mipmap if true
  51387. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51388. * @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)
  51389. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51390. */
  51391. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51392. if (noMipmap === void 0) { noMipmap = false; }
  51393. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51394. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51395. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51396. _super.call(this, scene);
  51397. this._useInGammaSpace = false;
  51398. this._generateHarmonics = true;
  51399. this._isBABYLONPreprocessed = false;
  51400. /**
  51401. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51402. */
  51403. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51404. /**
  51405. * The spherical polynomial data extracted from the texture.
  51406. */
  51407. this.sphericalPolynomial = null;
  51408. /**
  51409. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51410. * This is usefull at run time to apply the good shader.
  51411. */
  51412. this.isPMREM = false;
  51413. if (!url) {
  51414. return;
  51415. }
  51416. this.name = url;
  51417. this.url = url;
  51418. this.hasAlpha = false;
  51419. this.isCube = true;
  51420. this._textureMatrix = BABYLON.Matrix.Identity();
  51421. if (size) {
  51422. this._isBABYLONPreprocessed = false;
  51423. this._noMipmap = noMipmap;
  51424. this._size = size;
  51425. this._useInGammaSpace = useInGammaSpace;
  51426. this._usePMREMGenerator = usePMREMGenerator &&
  51427. scene.getEngine().getCaps().textureLOD &&
  51428. this.getScene().getEngine().getCaps().textureFloat &&
  51429. !this._useInGammaSpace;
  51430. }
  51431. else {
  51432. this._isBABYLONPreprocessed = true;
  51433. this._noMipmap = false;
  51434. this._useInGammaSpace = false;
  51435. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51436. this.getScene().getEngine().getCaps().textureFloat &&
  51437. !this._useInGammaSpace;
  51438. }
  51439. this.isPMREM = this._usePMREMGenerator;
  51440. this._texture = this._getFromCache(url, this._noMipmap);
  51441. if (!this._texture) {
  51442. if (!scene.useDelayedTextureLoading) {
  51443. this.loadTexture();
  51444. }
  51445. else {
  51446. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51447. }
  51448. }
  51449. }
  51450. /**
  51451. * Occurs when the file is a preprocessed .babylon.hdr file.
  51452. */
  51453. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51454. var _this = this;
  51455. var mipLevels = 0;
  51456. var floatArrayView = null;
  51457. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51458. var mips = [];
  51459. var startIndex = 30;
  51460. for (var level = 0; level < mipLevels; level++) {
  51461. mips.push([]);
  51462. // Fill each pixel of the mip level.
  51463. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51464. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51465. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51466. mips[level].push(faceData);
  51467. startIndex += faceSize;
  51468. }
  51469. }
  51470. return mips;
  51471. } : null;
  51472. var callback = function (buffer) {
  51473. // Create Native Array Views
  51474. var intArrayView = new Int32Array(buffer);
  51475. floatArrayView = new Float32Array(buffer);
  51476. // Fill header.
  51477. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51478. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51479. // Update Texture Information.
  51480. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51481. // Fill polynomial information.
  51482. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51483. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51484. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51485. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51486. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51487. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51488. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51489. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51490. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51491. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51492. // Fill pixel data.
  51493. mipLevels = intArrayView[29]; // Number of mip levels.
  51494. var startIndex = 30;
  51495. var data = [];
  51496. var faceSize = Math.pow(_this._size, 2) * 3;
  51497. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51498. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51499. startIndex += faceSize;
  51500. }
  51501. var results = [];
  51502. var byteArray = null;
  51503. // Push each faces.
  51504. for (var k = 0; k < 6; k++) {
  51505. var dataFace = null;
  51506. // If special cases.
  51507. if (!mipmapGenerator) {
  51508. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51509. dataFace = data[j];
  51510. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51511. // 3 channels of 1 bytes per pixel in bytes.
  51512. var byteBuffer = new ArrayBuffer(faceSize);
  51513. byteArray = new Uint8Array(byteBuffer);
  51514. }
  51515. for (var i = 0; i < _this._size * _this._size; i++) {
  51516. // Put in gamma space if requested.
  51517. if (_this._useInGammaSpace) {
  51518. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51519. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51520. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51521. }
  51522. // Convert to int texture for fallback.
  51523. if (byteArray) {
  51524. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51525. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51526. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51527. // May use luminance instead if the result is not accurate.
  51528. var max = Math.max(Math.max(r, g), b);
  51529. if (max > 255) {
  51530. var scale = 255 / max;
  51531. r *= scale;
  51532. g *= scale;
  51533. b *= scale;
  51534. }
  51535. byteArray[(i * 3) + 0] = r;
  51536. byteArray[(i * 3) + 1] = g;
  51537. byteArray[(i * 3) + 2] = b;
  51538. }
  51539. }
  51540. }
  51541. else {
  51542. dataFace = data[k];
  51543. }
  51544. // Fill the array accordingly.
  51545. if (byteArray) {
  51546. results.push(byteArray);
  51547. }
  51548. else {
  51549. results.push(dataFace);
  51550. }
  51551. }
  51552. return results;
  51553. };
  51554. 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);
  51555. };
  51556. /**
  51557. * Occurs when the file is raw .hdr file.
  51558. */
  51559. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51560. var _this = this;
  51561. var callback = function (buffer) {
  51562. // Extract the raw linear data.
  51563. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51564. // Generate harmonics if needed.
  51565. if (_this._generateHarmonics) {
  51566. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51567. }
  51568. var results = [];
  51569. var byteArray = null;
  51570. // Push each faces.
  51571. for (var j = 0; j < 6; j++) {
  51572. // Create uintarray fallback.
  51573. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51574. // 3 channels of 1 bytes per pixel in bytes.
  51575. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51576. byteArray = new Uint8Array(byteBuffer);
  51577. }
  51578. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51579. // If special cases.
  51580. if (_this._useInGammaSpace || byteArray) {
  51581. for (var i = 0; i < _this._size * _this._size; i++) {
  51582. // Put in gamma space if requested.
  51583. if (_this._useInGammaSpace) {
  51584. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51585. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51586. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51587. }
  51588. // Convert to int texture for fallback.
  51589. if (byteArray) {
  51590. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51591. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51592. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51593. // May use luminance instead if the result is not accurate.
  51594. var max = Math.max(Math.max(r, g), b);
  51595. if (max > 255) {
  51596. var scale = 255 / max;
  51597. r *= scale;
  51598. g *= scale;
  51599. b *= scale;
  51600. }
  51601. byteArray[(i * 3) + 0] = r;
  51602. byteArray[(i * 3) + 1] = g;
  51603. byteArray[(i * 3) + 2] = b;
  51604. }
  51605. }
  51606. }
  51607. if (byteArray) {
  51608. results.push(byteArray);
  51609. }
  51610. else {
  51611. results.push(dataFace);
  51612. }
  51613. }
  51614. return results;
  51615. };
  51616. var mipmapGenerator = null;
  51617. if (!this._noMipmap &&
  51618. this._usePMREMGenerator) {
  51619. mipmapGenerator = function (data) {
  51620. // Custom setup of the generator matching with the PBR shader values.
  51621. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51622. return generator.filterCubeMap();
  51623. };
  51624. }
  51625. 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);
  51626. };
  51627. /**
  51628. * Starts the loading process of the texture.
  51629. */
  51630. HDRCubeTexture.prototype.loadTexture = function () {
  51631. if (this._isBABYLONPreprocessed) {
  51632. this.loadBabylonTexture();
  51633. }
  51634. else {
  51635. this.loadHDRTexture();
  51636. }
  51637. };
  51638. HDRCubeTexture.prototype.clone = function () {
  51639. var size = this._isBABYLONPreprocessed ? null : this._size;
  51640. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51641. // Base texture
  51642. newTexture.level = this.level;
  51643. newTexture.wrapU = this.wrapU;
  51644. newTexture.wrapV = this.wrapV;
  51645. newTexture.coordinatesIndex = this.coordinatesIndex;
  51646. newTexture.coordinatesMode = this.coordinatesMode;
  51647. return newTexture;
  51648. };
  51649. // Methods
  51650. HDRCubeTexture.prototype.delayLoad = function () {
  51651. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51652. return;
  51653. }
  51654. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51655. this._texture = this._getFromCache(this.url, this._noMipmap);
  51656. if (!this._texture) {
  51657. this.loadTexture();
  51658. }
  51659. };
  51660. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51661. return this._textureMatrix;
  51662. };
  51663. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51664. var texture = null;
  51665. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51666. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51667. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51668. texture.name = parsedTexture.name;
  51669. texture.hasAlpha = parsedTexture.hasAlpha;
  51670. texture.level = parsedTexture.level;
  51671. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51672. }
  51673. return texture;
  51674. };
  51675. HDRCubeTexture.prototype.serialize = function () {
  51676. if (!this.name) {
  51677. return null;
  51678. }
  51679. var serializationObject = {};
  51680. serializationObject.name = this.name;
  51681. serializationObject.hasAlpha = this.hasAlpha;
  51682. serializationObject.isCube = true;
  51683. serializationObject.level = this.level;
  51684. serializationObject.size = this._size;
  51685. serializationObject.coordinatesMode = this.coordinatesMode;
  51686. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51687. serializationObject.generateHarmonics = this._generateHarmonics;
  51688. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51689. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51690. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51691. return serializationObject;
  51692. };
  51693. /**
  51694. * Saves as a file the data contained in the texture in a binary format.
  51695. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51696. * as the spherical used in the lighting.
  51697. * @param url The HDR file url.
  51698. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51699. * @param onError Method called if any error happens during download.
  51700. * @return The packed binary data.
  51701. */
  51702. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51703. if (onError === void 0) { onError = null; }
  51704. var callback = function (buffer) {
  51705. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51706. // Returns a URL you can use as a href.
  51707. var objUrl = window.URL.createObjectURL(data);
  51708. // Simulates a link to it and click to dowload.
  51709. var a = document.createElement("a");
  51710. document.body.appendChild(a);
  51711. a.style.display = "none";
  51712. a.href = objUrl;
  51713. a.download = "envmap.babylon.hdr";
  51714. a.click();
  51715. };
  51716. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51717. };
  51718. /**
  51719. * Serializes the data contained in the texture in a binary format.
  51720. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51721. * as the spherical used in the lighting.
  51722. * @param url The HDR file url.
  51723. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51724. * @param onError Method called if any error happens during download.
  51725. * @return The packed binary data.
  51726. */
  51727. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51728. if (onError === void 0) { onError = null; }
  51729. // Needs the url tho create the texture.
  51730. if (!url) {
  51731. return null;
  51732. }
  51733. // Check Power of two size.
  51734. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51735. return null;
  51736. }
  51737. var getDataCallback = function (dataBuffer) {
  51738. // Extract the raw linear data.
  51739. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51740. // Generate harmonics if needed.
  51741. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51742. // Generate seamless faces
  51743. var mipGeneratorArray = [];
  51744. // Data are known to be in +X +Y +Z -X -Y -Z
  51745. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51746. mipGeneratorArray.push(cubeData.right); // +X
  51747. mipGeneratorArray.push(cubeData.left); // -X
  51748. mipGeneratorArray.push(cubeData.up); // +Y
  51749. mipGeneratorArray.push(cubeData.down); // -Y
  51750. mipGeneratorArray.push(cubeData.front); // +Z
  51751. mipGeneratorArray.push(cubeData.back); // -Z
  51752. // Custom setup of the generator matching with the PBR shader values.
  51753. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51754. var mippedData = generator.filterCubeMap();
  51755. // Compute required byte length.
  51756. var byteLength = 1 * 4; // Raw Data Version int32.
  51757. byteLength += 4; // CubeMap max mip face size int32.
  51758. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51759. // Add data size.
  51760. byteLength += 4; // Number of mip levels int32.
  51761. for (var level = 0; level < mippedData.length; level++) {
  51762. var mipSize = size >> level;
  51763. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51764. }
  51765. // Prepare binary structure.
  51766. var buffer = new ArrayBuffer(byteLength);
  51767. var intArrayView = new Int32Array(buffer);
  51768. var floatArrayView = new Float32Array(buffer);
  51769. // Fill header.
  51770. intArrayView[0] = 1; // Version 1.
  51771. intArrayView[1] = size; // CubeMap max mip face size.
  51772. // Fill polynomial information.
  51773. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51774. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51775. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51776. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51777. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51778. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51779. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51780. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51781. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51782. // Fill pixel data.
  51783. intArrayView[29] = mippedData.length; // Number of mip levels.
  51784. var startIndex = 30;
  51785. for (var level = 0; level < mippedData.length; level++) {
  51786. // Fill each pixel of the mip level.
  51787. var faceSize = Math.pow(size >> level, 2) * 3;
  51788. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51789. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51790. startIndex += faceSize;
  51791. }
  51792. }
  51793. // Callback.
  51794. callback(buffer);
  51795. };
  51796. // Download and process.
  51797. BABYLON.Tools.LoadFile(url, function (data) {
  51798. getDataCallback(data);
  51799. }, null, null, true, onError);
  51800. };
  51801. HDRCubeTexture._facesMapping = [
  51802. "right",
  51803. "up",
  51804. "front",
  51805. "left",
  51806. "down",
  51807. "back"
  51808. ];
  51809. return HDRCubeTexture;
  51810. }(BABYLON.BaseTexture));
  51811. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51812. })(BABYLON || (BABYLON = {}));
  51813. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51814. var BABYLON;
  51815. (function (BABYLON) {
  51816. var Debug;
  51817. (function (Debug) {
  51818. /**
  51819. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51820. */
  51821. var SkeletonViewer = (function () {
  51822. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51823. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51824. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51825. this.skeleton = skeleton;
  51826. this.mesh = mesh;
  51827. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51828. this.renderingGroupId = renderingGroupId;
  51829. this.color = BABYLON.Color3.White();
  51830. this._debugLines = [];
  51831. this._isEnabled = false;
  51832. this._scene = scene;
  51833. this.update();
  51834. this._renderFunction = this.update.bind(this);
  51835. }
  51836. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51837. get: function () {
  51838. return this._isEnabled;
  51839. },
  51840. set: function (value) {
  51841. if (this._isEnabled === value) {
  51842. return;
  51843. }
  51844. this._isEnabled = value;
  51845. if (value) {
  51846. this._scene.registerBeforeRender(this._renderFunction);
  51847. }
  51848. else {
  51849. this._scene.unregisterBeforeRender(this._renderFunction);
  51850. }
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51856. if (x === void 0) { x = 0; }
  51857. if (y === void 0) { y = 0; }
  51858. if (z === void 0) { z = 0; }
  51859. var tmat = BABYLON.Tmp.Matrix[0];
  51860. var parentBone = bone.getParent();
  51861. tmat.copyFrom(bone.getLocalMatrix());
  51862. if (x !== 0 || y !== 0 || z !== 0) {
  51863. var tmat2 = BABYLON.Tmp.Matrix[1];
  51864. BABYLON.Matrix.IdentityToRef(tmat2);
  51865. tmat2.m[12] = x;
  51866. tmat2.m[13] = y;
  51867. tmat2.m[14] = z;
  51868. tmat2.multiplyToRef(tmat, tmat);
  51869. }
  51870. if (parentBone) {
  51871. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51872. }
  51873. tmat.multiplyToRef(meshMat, tmat);
  51874. position.x = tmat.m[12];
  51875. position.y = tmat.m[13];
  51876. position.z = tmat.m[14];
  51877. };
  51878. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  51879. var len = bones.length;
  51880. for (var i = 0; i < len; i++) {
  51881. var bone = bones[i];
  51882. var points = this._debugLines[i];
  51883. if (!points) {
  51884. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51885. this._debugLines[i] = points;
  51886. }
  51887. this._getBonePosition(points[0], bone, meshMat);
  51888. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  51889. }
  51890. };
  51891. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  51892. var len = bones.length;
  51893. var boneNum = 0;
  51894. for (var i = len - 1; i >= 0; i--) {
  51895. var childBone = bones[i];
  51896. var parentBone = childBone.getParent();
  51897. if (!parentBone) {
  51898. continue;
  51899. }
  51900. var points = this._debugLines[boneNum];
  51901. if (!points) {
  51902. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51903. this._debugLines[boneNum] = points;
  51904. }
  51905. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  51906. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  51907. boneNum++;
  51908. }
  51909. };
  51910. SkeletonViewer.prototype.update = function () {
  51911. if (this.autoUpdateBonesMatrices) {
  51912. this.skeleton.computeAbsoluteTransforms();
  51913. }
  51914. if (this.skeleton.bones[0].length === undefined) {
  51915. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51916. }
  51917. else {
  51918. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51919. }
  51920. if (!this._debugMesh) {
  51921. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  51922. this._debugMesh.renderingGroupId = this.renderingGroupId;
  51923. }
  51924. else {
  51925. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  51926. }
  51927. this._debugMesh.color = this.color;
  51928. };
  51929. SkeletonViewer.prototype.dispose = function () {
  51930. if (this._debugMesh) {
  51931. this.isEnabled = false;
  51932. this._debugMesh.dispose();
  51933. this._debugMesh = null;
  51934. }
  51935. };
  51936. return SkeletonViewer;
  51937. }());
  51938. Debug.SkeletonViewer = SkeletonViewer;
  51939. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51940. })(BABYLON || (BABYLON = {}));
  51941. //# sourceMappingURL=babylon.skeletonViewer.js.map
  51942. var BABYLON;
  51943. (function (BABYLON) {
  51944. var Debug;
  51945. (function (Debug) {
  51946. var AxesViewer = (function () {
  51947. function AxesViewer(scene, scaleLines) {
  51948. if (scaleLines === void 0) { scaleLines = 1; }
  51949. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51950. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51951. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51952. this.scaleLines = 1;
  51953. this.scaleLines = scaleLines;
  51954. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  51955. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  51956. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  51957. this._xmesh.renderingGroupId = 2;
  51958. this._ymesh.renderingGroupId = 2;
  51959. this._zmesh.renderingGroupId = 2;
  51960. this._xmesh.material.checkReadyOnlyOnce = true;
  51961. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  51962. this._ymesh.material.checkReadyOnlyOnce = true;
  51963. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  51964. this._zmesh.material.checkReadyOnlyOnce = true;
  51965. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  51966. this.scene = scene;
  51967. }
  51968. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  51969. var scaleLines = this.scaleLines;
  51970. var point1 = this._xline[0];
  51971. var point2 = this._xline[1];
  51972. point1.x = position.x;
  51973. point1.y = position.y;
  51974. point1.z = position.z;
  51975. point2.x = point1.x + xaxis.x * scaleLines;
  51976. point2.y = point1.y + xaxis.y * scaleLines;
  51977. point2.z = point1.z + xaxis.z * scaleLines;
  51978. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  51979. point1 = this._yline[0];
  51980. point2 = this._yline[1];
  51981. point1.x = position.x;
  51982. point1.y = position.y;
  51983. point1.z = position.z;
  51984. point2.x = point1.x + yaxis.x * scaleLines;
  51985. point2.y = point1.y + yaxis.y * scaleLines;
  51986. point2.z = point1.z + yaxis.z * scaleLines;
  51987. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  51988. point1 = this._zline[0];
  51989. point2 = this._zline[1];
  51990. point1.x = position.x;
  51991. point1.y = position.y;
  51992. point1.z = position.z;
  51993. point2.x = point1.x + zaxis.x * scaleLines;
  51994. point2.y = point1.y + zaxis.y * scaleLines;
  51995. point2.z = point1.z + zaxis.z * scaleLines;
  51996. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  51997. };
  51998. AxesViewer.prototype.dispose = function () {
  51999. if (this._xmesh) {
  52000. this._xmesh.dispose();
  52001. this._ymesh.dispose();
  52002. this._zmesh.dispose();
  52003. this._xmesh = null;
  52004. this._ymesh = null;
  52005. this._zmesh = null;
  52006. this._xline = null;
  52007. this._yline = null;
  52008. this._zline = null;
  52009. this.scene = null;
  52010. }
  52011. };
  52012. return AxesViewer;
  52013. }());
  52014. Debug.AxesViewer = AxesViewer;
  52015. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52016. })(BABYLON || (BABYLON = {}));
  52017. //# sourceMappingURL=babylon.axesViewer.js.map
  52018. var BABYLON;
  52019. (function (BABYLON) {
  52020. var Debug;
  52021. (function (Debug) {
  52022. var BoneAxesViewer = (function (_super) {
  52023. __extends(BoneAxesViewer, _super);
  52024. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52025. if (scaleLines === void 0) { scaleLines = 1; }
  52026. _super.call(this, scene, scaleLines);
  52027. this.pos = BABYLON.Vector3.Zero();
  52028. this.xaxis = BABYLON.Vector3.Zero();
  52029. this.yaxis = BABYLON.Vector3.Zero();
  52030. this.zaxis = BABYLON.Vector3.Zero();
  52031. this.mesh = mesh;
  52032. this.bone = bone;
  52033. }
  52034. BoneAxesViewer.prototype.update = function () {
  52035. var bone = this.bone;
  52036. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52037. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52038. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52039. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52040. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52041. };
  52042. BoneAxesViewer.prototype.dispose = function () {
  52043. if (this.pos) {
  52044. this.pos = null;
  52045. this.xaxis = null;
  52046. this.yaxis = null;
  52047. this.zaxis = null;
  52048. this.mesh = null;
  52049. this.bone = null;
  52050. _super.prototype.dispose.call(this);
  52051. }
  52052. };
  52053. return BoneAxesViewer;
  52054. }(Debug.AxesViewer));
  52055. Debug.BoneAxesViewer = BoneAxesViewer;
  52056. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52057. })(BABYLON || (BABYLON = {}));
  52058. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52059. var BABYLON;
  52060. (function (BABYLON) {
  52061. /**
  52062. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52063. * It can help converting any input color in a desired output one. This can then be used to create effects
  52064. * from sepia, black and white to sixties or futuristic rendering...
  52065. *
  52066. * The only supported format is currently 3dl.
  52067. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52068. */
  52069. var ColorGradingTexture = (function (_super) {
  52070. __extends(ColorGradingTexture, _super);
  52071. /**
  52072. * Instantiates a ColorGradingTexture from the following parameters.
  52073. *
  52074. * @param url The location of the color gradind data (currently only supporting 3dl)
  52075. * @param scene The scene the texture will be used in
  52076. */
  52077. function ColorGradingTexture(url, scene) {
  52078. _super.call(this, scene);
  52079. if (!url) {
  52080. return;
  52081. }
  52082. this._textureMatrix = BABYLON.Matrix.Identity();
  52083. this.name = url;
  52084. this.url = url;
  52085. this.hasAlpha = false;
  52086. this.isCube = false;
  52087. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52088. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52089. this.anisotropicFilteringLevel = 1;
  52090. this._texture = this._getFromCache(url, true);
  52091. if (!this._texture) {
  52092. if (!scene.useDelayedTextureLoading) {
  52093. this.loadTexture();
  52094. }
  52095. else {
  52096. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52097. }
  52098. }
  52099. }
  52100. /**
  52101. * Returns the texture matrix used in most of the material.
  52102. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52103. */
  52104. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52105. return this._textureMatrix;
  52106. };
  52107. /**
  52108. * Occurs when the file being loaded is a .3dl LUT file.
  52109. */
  52110. ColorGradingTexture.prototype.load3dlTexture = function () {
  52111. var _this = this;
  52112. var mipLevels = 0;
  52113. var floatArrayView = null;
  52114. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52115. this._texture = texture;
  52116. var callback = function (text) {
  52117. var data;
  52118. var tempData;
  52119. var line;
  52120. var lines = text.split('\n');
  52121. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52122. var maxColor = 0;
  52123. for (var i = 0; i < lines.length; i++) {
  52124. line = lines[i];
  52125. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52126. continue;
  52127. if (line.indexOf('#') === 0)
  52128. continue;
  52129. var words = line.split(" ");
  52130. if (size === 0) {
  52131. // Number of space + one
  52132. size = words.length;
  52133. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52134. tempData = new Float32Array(size * size * size * 4);
  52135. continue;
  52136. }
  52137. if (size != 0) {
  52138. var r = Math.max(parseInt(words[0]), 0);
  52139. var g = Math.max(parseInt(words[1]), 0);
  52140. var b = Math.max(parseInt(words[2]), 0);
  52141. maxColor = Math.max(r, maxColor);
  52142. maxColor = Math.max(g, maxColor);
  52143. maxColor = Math.max(b, maxColor);
  52144. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52145. tempData[pixelStorageIndex + 0] = r;
  52146. tempData[pixelStorageIndex + 1] = g;
  52147. tempData[pixelStorageIndex + 2] = b;
  52148. tempData[pixelStorageIndex + 3] = 0;
  52149. pixelIndexSlice++;
  52150. if (pixelIndexSlice % size == 0) {
  52151. pixelIndexH++;
  52152. pixelIndexSlice = 0;
  52153. if (pixelIndexH % size == 0) {
  52154. pixelIndexW++;
  52155. pixelIndexH = 0;
  52156. }
  52157. }
  52158. }
  52159. }
  52160. for (var i = 0; i < tempData.length; i++) {
  52161. var value = tempData[i];
  52162. data[i] = (value / maxColor * 255);
  52163. }
  52164. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52165. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52166. };
  52167. BABYLON.Tools.LoadFile(this.url, callback);
  52168. return this._texture;
  52169. };
  52170. /**
  52171. * Starts the loading process of the texture.
  52172. */
  52173. ColorGradingTexture.prototype.loadTexture = function () {
  52174. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52175. this.load3dlTexture();
  52176. }
  52177. };
  52178. /**
  52179. * Clones the color gradind texture.
  52180. */
  52181. ColorGradingTexture.prototype.clone = function () {
  52182. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52183. // Base texture
  52184. newTexture.level = this.level;
  52185. return newTexture;
  52186. };
  52187. /**
  52188. * Called during delayed load for textures.
  52189. */
  52190. ColorGradingTexture.prototype.delayLoad = function () {
  52191. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52192. return;
  52193. }
  52194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52195. this._texture = this._getFromCache(this.url, true);
  52196. if (!this._texture) {
  52197. this.loadTexture();
  52198. }
  52199. };
  52200. /**
  52201. * Binds the color grading to the shader.
  52202. * @param colorGrading The texture to bind
  52203. * @param effect The effect to bind to
  52204. */
  52205. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52206. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52207. var x = colorGrading.level; // Texture Level
  52208. var y = colorGrading.getSize().height; // Texture Size example with 8
  52209. var z = y - 1.0; // SizeMinusOne 8 - 1
  52210. var w = 1 / y; // Space of 1 slice 1 / 8
  52211. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52212. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52213. 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
  52214. 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
  52215. 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
  52216. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52217. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52218. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52219. };
  52220. /**
  52221. * Prepare the list of uniforms associated with the ColorGrading effects.
  52222. * @param uniformsList The list of uniforms used in the effect
  52223. * @param samplersList The list of samplers used in the effect
  52224. */
  52225. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52226. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52227. samplersList.push("cameraColorGrading2DSampler");
  52228. };
  52229. /**
  52230. * Parses a color grading texture serialized by Babylon.
  52231. * @param parsedTexture The texture information being parsedTexture
  52232. * @param scene The scene to load the texture in
  52233. * @param rootUrl The root url of the data assets to load
  52234. * @return A color gradind texture
  52235. */
  52236. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52237. var texture = null;
  52238. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52239. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52240. texture.name = parsedTexture.name;
  52241. texture.level = parsedTexture.level;
  52242. }
  52243. return texture;
  52244. };
  52245. /**
  52246. * Serializes the LUT texture to json format.
  52247. */
  52248. ColorGradingTexture.prototype.serialize = function () {
  52249. if (!this.name) {
  52250. return null;
  52251. }
  52252. var serializationObject = {};
  52253. serializationObject.name = this.name;
  52254. serializationObject.level = this.level;
  52255. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52256. return serializationObject;
  52257. };
  52258. /**
  52259. * Empty line regex stored for GC.
  52260. */
  52261. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52262. return ColorGradingTexture;
  52263. }(BABYLON.BaseTexture));
  52264. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52265. })(BABYLON || (BABYLON = {}));
  52266. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52267. var BABYLON;
  52268. (function (BABYLON) {
  52269. /**
  52270. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52271. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52272. * 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;
  52273. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52274. */
  52275. var ColorCurves = (function () {
  52276. function ColorCurves() {
  52277. this._dirty = true;
  52278. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52279. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52280. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52281. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52282. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52283. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52284. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52285. this._globalHue = 30;
  52286. this._globalDensity = 0;
  52287. this._globalSaturation = 0;
  52288. this._globalExposure = 0;
  52289. this._highlightsHue = 30;
  52290. this._highlightsDensity = 0;
  52291. this._highlightsSaturation = 0;
  52292. this._highlightsExposure = 0;
  52293. this._midtonesHue = 30;
  52294. this._midtonesDensity = 0;
  52295. this._midtonesSaturation = 0;
  52296. this._midtonesExposure = 0;
  52297. this._shadowsHue = 30;
  52298. this._shadowsDensity = 0;
  52299. this._shadowsSaturation = 0;
  52300. this._shadowsExposure = 0;
  52301. }
  52302. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52303. /**
  52304. * Gets the global Hue value.
  52305. * 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).
  52306. */
  52307. get: function () {
  52308. return this._globalHue;
  52309. },
  52310. /**
  52311. * Sets the global Hue value.
  52312. * 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).
  52313. */
  52314. set: function (value) {
  52315. this._globalHue = value;
  52316. this._dirty = true;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52322. /**
  52323. * Gets the global Density value.
  52324. * 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.
  52325. * Values less than zero provide a filter of opposite hue.
  52326. */
  52327. get: function () {
  52328. return this._globalDensity;
  52329. },
  52330. /**
  52331. * Sets the global Density value.
  52332. * 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.
  52333. * Values less than zero provide a filter of opposite hue.
  52334. */
  52335. set: function (value) {
  52336. this._globalDensity = value;
  52337. this._dirty = true;
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52343. /**
  52344. * Gets the global Saturation value.
  52345. * 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.
  52346. */
  52347. get: function () {
  52348. return this._globalSaturation;
  52349. },
  52350. /**
  52351. * Sets the global Saturation value.
  52352. * 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.
  52353. */
  52354. set: function (value) {
  52355. this._globalSaturation = value;
  52356. this._dirty = true;
  52357. },
  52358. enumerable: true,
  52359. configurable: true
  52360. });
  52361. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52362. /**
  52363. * Gets the highlights Hue value.
  52364. * 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).
  52365. */
  52366. get: function () {
  52367. return this._highlightsHue;
  52368. },
  52369. /**
  52370. * Sets the highlights Hue value.
  52371. * 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).
  52372. */
  52373. set: function (value) {
  52374. this._highlightsHue = value;
  52375. this._dirty = true;
  52376. },
  52377. enumerable: true,
  52378. configurable: true
  52379. });
  52380. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52381. /**
  52382. * Gets the highlights Density value.
  52383. * 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.
  52384. * Values less than zero provide a filter of opposite hue.
  52385. */
  52386. get: function () {
  52387. return this._highlightsDensity;
  52388. },
  52389. /**
  52390. * Sets the highlights Density value.
  52391. * 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.
  52392. * Values less than zero provide a filter of opposite hue.
  52393. */
  52394. set: function (value) {
  52395. this._highlightsDensity = value;
  52396. this._dirty = true;
  52397. },
  52398. enumerable: true,
  52399. configurable: true
  52400. });
  52401. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52402. /**
  52403. * Gets the highlights Saturation value.
  52404. * 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.
  52405. */
  52406. get: function () {
  52407. return this._highlightsSaturation;
  52408. },
  52409. /**
  52410. * Sets the highlights Saturation value.
  52411. * 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.
  52412. */
  52413. set: function (value) {
  52414. this._highlightsSaturation = value;
  52415. this._dirty = true;
  52416. },
  52417. enumerable: true,
  52418. configurable: true
  52419. });
  52420. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52421. /**
  52422. * Gets the highlights Exposure value.
  52423. * 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.
  52424. */
  52425. get: function () {
  52426. return this._highlightsExposure;
  52427. },
  52428. /**
  52429. * Sets the highlights Exposure value.
  52430. * 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.
  52431. */
  52432. set: function (value) {
  52433. this._highlightsExposure = value;
  52434. this._dirty = true;
  52435. },
  52436. enumerable: true,
  52437. configurable: true
  52438. });
  52439. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52440. /**
  52441. * Gets the midtones Hue value.
  52442. * 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).
  52443. */
  52444. get: function () {
  52445. return this._midtonesHue;
  52446. },
  52447. /**
  52448. * Sets the midtones Hue value.
  52449. * 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).
  52450. */
  52451. set: function (value) {
  52452. this._midtonesHue = value;
  52453. this._dirty = true;
  52454. },
  52455. enumerable: true,
  52456. configurable: true
  52457. });
  52458. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52459. /**
  52460. * Gets the midtones Density value.
  52461. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52462. * Values less than zero provide a filter of opposite hue.
  52463. */
  52464. get: function () {
  52465. return this._midtonesDensity;
  52466. },
  52467. /**
  52468. * Sets the midtones Density value.
  52469. * 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.
  52470. * Values less than zero provide a filter of opposite hue.
  52471. */
  52472. set: function (value) {
  52473. this._midtonesDensity = value;
  52474. this._dirty = true;
  52475. },
  52476. enumerable: true,
  52477. configurable: true
  52478. });
  52479. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52480. /**
  52481. * Gets the midtones Saturation value.
  52482. * 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.
  52483. */
  52484. get: function () {
  52485. return this._midtonesSaturation;
  52486. },
  52487. /**
  52488. * Sets the midtones Saturation value.
  52489. * 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.
  52490. */
  52491. set: function (value) {
  52492. this._midtonesSaturation = value;
  52493. this._dirty = true;
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52499. /**
  52500. * Gets the midtones Exposure value.
  52501. * 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.
  52502. */
  52503. get: function () {
  52504. return this._midtonesExposure;
  52505. },
  52506. /**
  52507. * Sets the midtones Exposure value.
  52508. * 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.
  52509. */
  52510. set: function (value) {
  52511. this._midtonesExposure = value;
  52512. this._dirty = true;
  52513. },
  52514. enumerable: true,
  52515. configurable: true
  52516. });
  52517. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52518. /**
  52519. * Gets the shadows Hue value.
  52520. * 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).
  52521. */
  52522. get: function () {
  52523. return this._shadowsHue;
  52524. },
  52525. /**
  52526. * Sets the shadows Hue value.
  52527. * 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).
  52528. */
  52529. set: function (value) {
  52530. this._shadowsHue = value;
  52531. this._dirty = true;
  52532. },
  52533. enumerable: true,
  52534. configurable: true
  52535. });
  52536. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52537. /**
  52538. * Gets the shadows Density value.
  52539. * 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.
  52540. * Values less than zero provide a filter of opposite hue.
  52541. */
  52542. get: function () {
  52543. return this._shadowsDensity;
  52544. },
  52545. /**
  52546. * Sets the shadows Density value.
  52547. * 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.
  52548. * Values less than zero provide a filter of opposite hue.
  52549. */
  52550. set: function (value) {
  52551. this._shadowsDensity = value;
  52552. this._dirty = true;
  52553. },
  52554. enumerable: true,
  52555. configurable: true
  52556. });
  52557. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52558. /**
  52559. * Gets the shadows Saturation value.
  52560. * 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.
  52561. */
  52562. get: function () {
  52563. return this._shadowsSaturation;
  52564. },
  52565. /**
  52566. * Sets the shadows Saturation value.
  52567. * 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.
  52568. */
  52569. set: function (value) {
  52570. this._shadowsSaturation = value;
  52571. this._dirty = true;
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52577. /**
  52578. * Gets the shadows Exposure value.
  52579. * 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.
  52580. */
  52581. get: function () {
  52582. return this._shadowsExposure;
  52583. },
  52584. /**
  52585. * Sets the shadows Exposure value.
  52586. * 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.
  52587. */
  52588. set: function (value) {
  52589. this._shadowsExposure = value;
  52590. this._dirty = true;
  52591. },
  52592. enumerable: true,
  52593. configurable: true
  52594. });
  52595. /**
  52596. * Binds the color curves to the shader.
  52597. * @param colorCurves The color curve to bind
  52598. * @param effect The effect to bind to
  52599. */
  52600. ColorCurves.Bind = function (colorCurves, effect) {
  52601. if (colorCurves._dirty) {
  52602. colorCurves._dirty = false;
  52603. // Fill in global info.
  52604. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52605. // Compute highlights info.
  52606. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52607. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52608. // Compute midtones info.
  52609. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52610. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52611. // Compute shadows info.
  52612. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52613. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52614. // Compute deltas (neutral is midtones).
  52615. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52616. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52617. }
  52618. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52619. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52620. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52621. };
  52622. /**
  52623. * Prepare the list of uniforms associated with the ColorCurves effects.
  52624. * @param uniformsList The list of uniforms used in the effect
  52625. */
  52626. ColorCurves.PrepareUniforms = function (uniformsList) {
  52627. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52628. };
  52629. /**
  52630. * Returns color grading data based on a hue, density, saturation and exposure value.
  52631. * @param filterHue The hue of the color filter.
  52632. * @param filterDensity The density of the color filter.
  52633. * @param saturation The saturation.
  52634. * @param exposure The exposure.
  52635. * @param result The result data container.
  52636. */
  52637. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52638. if (hue == null) {
  52639. return;
  52640. }
  52641. hue = ColorCurves.clamp(hue, 0, 360);
  52642. density = ColorCurves.clamp(density, -100, 100);
  52643. saturation = ColorCurves.clamp(saturation, -100, 100);
  52644. exposure = ColorCurves.clamp(exposure, -100, 100);
  52645. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52646. // so that the maximum filter density is only 50% control. This provides fine control
  52647. // for small values and reasonable range.
  52648. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52649. density *= 0.5;
  52650. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52651. if (density < 0) {
  52652. density *= -1;
  52653. hue = (hue + 180) % 360;
  52654. }
  52655. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52656. result.scaleToRef(2, result);
  52657. result.a = 1 + 0.01 * saturation;
  52658. };
  52659. /**
  52660. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52661. * @param value The input slider value in range [-100,100].
  52662. * @returns Adjusted value.
  52663. */
  52664. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52665. value /= 100;
  52666. var x = Math.abs(value);
  52667. x = Math.pow(x, 2);
  52668. if (value < 0) {
  52669. x *= -1;
  52670. }
  52671. x *= 100;
  52672. return x;
  52673. };
  52674. /**
  52675. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52676. * @param hue The hue (H) input.
  52677. * @param saturation The saturation (S) input.
  52678. * @param brightness The brightness (B) input.
  52679. * @result An RGBA color represented as Vector4.
  52680. */
  52681. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52682. var h = ColorCurves.clamp(hue, 0, 360);
  52683. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52684. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52685. if (s === 0) {
  52686. result.r = v;
  52687. result.g = v;
  52688. result.b = v;
  52689. }
  52690. else {
  52691. // sector 0 to 5
  52692. h /= 60;
  52693. var i = Math.floor(h);
  52694. // fractional part of h
  52695. var f = h - i;
  52696. var p = v * (1 - s);
  52697. var q = v * (1 - s * f);
  52698. var t = v * (1 - s * (1 - f));
  52699. switch (i) {
  52700. case 0:
  52701. result.r = v;
  52702. result.g = t;
  52703. result.b = p;
  52704. break;
  52705. case 1:
  52706. result.r = q;
  52707. result.g = v;
  52708. result.b = p;
  52709. break;
  52710. case 2:
  52711. result.r = p;
  52712. result.g = v;
  52713. result.b = t;
  52714. break;
  52715. case 3:
  52716. result.r = p;
  52717. result.g = q;
  52718. result.b = v;
  52719. break;
  52720. case 4:
  52721. result.r = t;
  52722. result.g = p;
  52723. result.b = v;
  52724. break;
  52725. default:
  52726. result.r = v;
  52727. result.g = p;
  52728. result.b = q;
  52729. break;
  52730. }
  52731. }
  52732. result.a = 1;
  52733. };
  52734. /**
  52735. * Returns a value clamped between min and max
  52736. * @param value The value to clamp
  52737. * @param min The minimum of value
  52738. * @param max The maximum of value
  52739. * @returns The clamped value.
  52740. */
  52741. ColorCurves.clamp = function (value, min, max) {
  52742. return Math.min(Math.max(value, min), max);
  52743. };
  52744. /**
  52745. * Clones the current color curve instance.
  52746. * @return The cloned curves
  52747. */
  52748. ColorCurves.prototype.clone = function () {
  52749. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52750. };
  52751. /**
  52752. * Serializes the current color curve instance to a json representation.
  52753. * @return a JSON representation
  52754. */
  52755. ColorCurves.prototype.serialize = function () {
  52756. return BABYLON.SerializationHelper.Serialize(this);
  52757. };
  52758. /**
  52759. * Parses the color curve from a json representation.
  52760. * @param source the JSON source to parse
  52761. * @return The parsed curves
  52762. */
  52763. ColorCurves.Parse = function (source) {
  52764. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52765. };
  52766. __decorate([
  52767. BABYLON.serialize()
  52768. ], ColorCurves.prototype, "_globalHue", void 0);
  52769. __decorate([
  52770. BABYLON.serialize()
  52771. ], ColorCurves.prototype, "_globalDensity", void 0);
  52772. __decorate([
  52773. BABYLON.serialize()
  52774. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52775. __decorate([
  52776. BABYLON.serialize()
  52777. ], ColorCurves.prototype, "_globalExposure", void 0);
  52778. __decorate([
  52779. BABYLON.serialize()
  52780. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52781. __decorate([
  52782. BABYLON.serialize()
  52783. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52784. __decorate([
  52785. BABYLON.serialize()
  52786. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52787. __decorate([
  52788. BABYLON.serialize()
  52789. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52790. __decorate([
  52791. BABYLON.serialize()
  52792. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52793. __decorate([
  52794. BABYLON.serialize()
  52795. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52796. __decorate([
  52797. BABYLON.serialize()
  52798. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52799. __decorate([
  52800. BABYLON.serialize()
  52801. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52802. return ColorCurves;
  52803. }());
  52804. BABYLON.ColorCurves = ColorCurves;
  52805. })(BABYLON || (BABYLON = {}));
  52806. //# sourceMappingURL=babylon.colorCurves.js.map
  52807. var BABYLON;
  52808. (function (BABYLON) {
  52809. var PBRMaterialDefines = (function (_super) {
  52810. __extends(PBRMaterialDefines, _super);
  52811. function PBRMaterialDefines() {
  52812. _super.call(this);
  52813. this.ALBEDO = false;
  52814. this.AMBIENT = false;
  52815. this.OPACITY = false;
  52816. this.OPACITYRGB = false;
  52817. this.REFLECTION = false;
  52818. this.EMISSIVE = false;
  52819. this.REFLECTIVITY = false;
  52820. this.BUMP = false;
  52821. this.PARALLAX = false;
  52822. this.PARALLAXOCCLUSION = false;
  52823. this.SPECULAROVERALPHA = false;
  52824. this.CLIPPLANE = false;
  52825. this.ALPHATEST = false;
  52826. this.ALPHAFROMALBEDO = false;
  52827. this.POINTSIZE = false;
  52828. this.FOG = false;
  52829. this.SPECULARTERM = false;
  52830. this.OPACITYFRESNEL = false;
  52831. this.EMISSIVEFRESNEL = false;
  52832. this.FRESNEL = false;
  52833. this.NORMAL = false;
  52834. this.UV1 = false;
  52835. this.UV2 = false;
  52836. this.VERTEXCOLOR = false;
  52837. this.VERTEXALPHA = false;
  52838. this.NUM_BONE_INFLUENCERS = 0;
  52839. this.BonesPerMesh = 0;
  52840. this.INSTANCES = false;
  52841. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52842. this.MICROSURFACEAUTOMATIC = false;
  52843. this.EMISSIVEASILLUMINATION = false;
  52844. this.LINKEMISSIVEWITHALBEDO = false;
  52845. this.LIGHTMAP = false;
  52846. this.USELIGHTMAPASSHADOWMAP = false;
  52847. this.REFLECTIONMAP_3D = false;
  52848. this.REFLECTIONMAP_SPHERICAL = false;
  52849. this.REFLECTIONMAP_PLANAR = false;
  52850. this.REFLECTIONMAP_CUBIC = false;
  52851. this.REFLECTIONMAP_PROJECTION = false;
  52852. this.REFLECTIONMAP_SKYBOX = false;
  52853. this.REFLECTIONMAP_EXPLICIT = false;
  52854. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52855. this.INVERTCUBICMAP = false;
  52856. this.LOGARITHMICDEPTH = false;
  52857. this.CAMERATONEMAP = false;
  52858. this.CAMERACONTRAST = false;
  52859. this.CAMERACOLORGRADING = false;
  52860. this.CAMERACOLORCURVES = false;
  52861. this.OVERLOADEDVALUES = false;
  52862. this.OVERLOADEDSHADOWVALUES = false;
  52863. this.USESPHERICALFROMREFLECTIONMAP = false;
  52864. this.REFRACTION = false;
  52865. this.REFRACTIONMAP_3D = false;
  52866. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52867. this.REFRACTIONMAPINLINEARSPACE = false;
  52868. this.LODBASEDMICROSFURACE = false;
  52869. this.USEPHYSICALLIGHTFALLOFF = false;
  52870. this.RADIANCEOVERALPHA = false;
  52871. this.USEPMREMREFLECTION = false;
  52872. this.USEPMREMREFRACTION = false;
  52873. this.OPENGLNORMALMAP = false;
  52874. this.INVERTNORMALMAPX = false;
  52875. this.INVERTNORMALMAPY = false;
  52876. this.SHADOWFULLFLOAT = false;
  52877. this.METALLICWORKFLOW = false;
  52878. this.METALLICROUGHNESSGSTOREINALPHA = false;
  52879. this.METALLICROUGHNESSGSTOREINGREEN = false;
  52880. this.rebuild();
  52881. }
  52882. return PBRMaterialDefines;
  52883. }(BABYLON.MaterialDefines));
  52884. /**
  52885. * The Physically based material of BJS.
  52886. *
  52887. * This offers the main features of a standard PBR material.
  52888. * For more information, please refer to the documentation :
  52889. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52890. */
  52891. var PBRMaterial = (function (_super) {
  52892. __extends(PBRMaterial, _super);
  52893. /**
  52894. * Instantiates a new PBRMaterial instance.
  52895. *
  52896. * @param name The material name
  52897. * @param scene The scene the material will be use in.
  52898. */
  52899. function PBRMaterial(name, scene) {
  52900. var _this = this;
  52901. _super.call(this, name, scene);
  52902. /**
  52903. * Intensity of the direct lights e.g. the four lights available in your scene.
  52904. * This impacts both the direct diffuse and specular highlights.
  52905. */
  52906. this.directIntensity = 1.0;
  52907. /**
  52908. * Intensity of the emissive part of the material.
  52909. * This helps controlling the emissive effect without modifying the emissive color.
  52910. */
  52911. this.emissiveIntensity = 1.0;
  52912. /**
  52913. * Intensity of the environment e.g. how much the environment will light the object
  52914. * either through harmonics for rough material or through the refelction for shiny ones.
  52915. */
  52916. this.environmentIntensity = 1.0;
  52917. /**
  52918. * This is a special control allowing the reduction of the specular highlights coming from the
  52919. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52920. */
  52921. this.specularIntensity = 1.0;
  52922. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52923. /**
  52924. * Debug Control allowing disabling the bump map on this material.
  52925. */
  52926. this.disableBumpMap = false;
  52927. /**
  52928. * Debug Control helping enforcing or dropping the darkness of shadows.
  52929. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52930. */
  52931. this.overloadedShadowIntensity = 1.0;
  52932. /**
  52933. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52934. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52935. */
  52936. this.overloadedShadeIntensity = 1.0;
  52937. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52938. /**
  52939. * The camera exposure used on this material.
  52940. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52941. * This corresponds to a photographic exposure.
  52942. */
  52943. this.cameraExposure = 1.0;
  52944. /**
  52945. * The camera contrast used on this material.
  52946. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52947. */
  52948. this.cameraContrast = 1.0;
  52949. /**
  52950. * Color Grading 2D Lookup Texture.
  52951. * This allows special effects like sepia, black and white to sixties rendering style.
  52952. */
  52953. this.cameraColorGradingTexture = null;
  52954. /**
  52955. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52956. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52957. * 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;
  52958. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52959. */
  52960. this.cameraColorCurves = null;
  52961. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52962. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52963. /**
  52964. * Debug Control allowing to overload the ambient color.
  52965. * This as to be use with the overloadedAmbientIntensity parameter.
  52966. */
  52967. this.overloadedAmbient = BABYLON.Color3.White();
  52968. /**
  52969. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  52970. */
  52971. this.overloadedAmbientIntensity = 0.0;
  52972. /**
  52973. * Debug Control allowing to overload the albedo color.
  52974. * This as to be use with the overloadedAlbedoIntensity parameter.
  52975. */
  52976. this.overloadedAlbedo = BABYLON.Color3.White();
  52977. /**
  52978. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  52979. */
  52980. this.overloadedAlbedoIntensity = 0.0;
  52981. /**
  52982. * Debug Control allowing to overload the reflectivity color.
  52983. * This as to be use with the overloadedReflectivityIntensity parameter.
  52984. */
  52985. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  52986. /**
  52987. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  52988. */
  52989. this.overloadedReflectivityIntensity = 0.0;
  52990. /**
  52991. * Debug Control allowing to overload the emissive color.
  52992. * This as to be use with the overloadedEmissiveIntensity parameter.
  52993. */
  52994. this.overloadedEmissive = BABYLON.Color3.White();
  52995. /**
  52996. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  52997. */
  52998. this.overloadedEmissiveIntensity = 0.0;
  52999. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  53000. /**
  53001. * Debug Control allowing to overload the reflection color.
  53002. * This as to be use with the overloadedReflectionIntensity parameter.
  53003. */
  53004. this.overloadedReflection = BABYLON.Color3.White();
  53005. /**
  53006. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53007. */
  53008. this.overloadedReflectionIntensity = 0.0;
  53009. /**
  53010. * Debug Control allowing to overload the microsurface.
  53011. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53012. */
  53013. this.overloadedMicroSurface = 0.0;
  53014. /**
  53015. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53016. */
  53017. this.overloadedMicroSurfaceIntensity = 0.0;
  53018. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  53019. /**
  53020. * AKA Occlusion Texture Intensity in other nomenclature.
  53021. */
  53022. this.ambientTextureStrength = 1.0;
  53023. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53024. /**
  53025. * AKA Diffuse Color in other nomenclature.
  53026. */
  53027. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53028. /**
  53029. * AKA Specular Color in other nomenclature.
  53030. */
  53031. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53032. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53033. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53034. /**
  53035. * AKA Glossiness in other nomenclature.
  53036. */
  53037. this.microSurface = 0.9;
  53038. /**
  53039. * source material index of refraction (IOR)' / 'destination material IOR.
  53040. */
  53041. this.indexOfRefraction = 0.66;
  53042. /**
  53043. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53044. */
  53045. this.invertRefractionY = false;
  53046. /**
  53047. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53048. * Materials half opaque for instance using refraction could benefit from this control.
  53049. */
  53050. this.linkRefractionWithTransparency = false;
  53051. /**
  53052. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53053. */
  53054. this.linkEmissiveWithAlbedo = false;
  53055. this.useLightmapAsShadowmap = false;
  53056. /**
  53057. * In this mode, the emissive informtaion will always be added to the lighting once.
  53058. * A light for instance can be thought as emissive.
  53059. */
  53060. this.useEmissiveAsIllumination = false;
  53061. /**
  53062. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53063. */
  53064. this.useAlphaFromAlbedoTexture = false;
  53065. /**
  53066. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53067. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53068. */
  53069. this.useSpecularOverAlpha = true;
  53070. /**
  53071. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53072. */
  53073. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53074. /**
  53075. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53076. */
  53077. this.useRoughnessFromMetallicTextureAlpha = true;
  53078. /**
  53079. * Specifies if the metallic texture contains the roughness information in its green channel.
  53080. */
  53081. this.useRoughnessFromMetallicTextureGreen = false;
  53082. /**
  53083. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53084. * The material will try to infer what glossiness each pixel should be.
  53085. */
  53086. this.useAutoMicroSurfaceFromReflectivityMap = false;
  53087. /**
  53088. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53089. * the creation of the material.
  53090. */
  53091. this.useScalarInLinearSpace = false;
  53092. /**
  53093. * BJS is using an harcoded light falloff based on a manually sets up range.
  53094. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53095. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53096. */
  53097. this.usePhysicalLightFalloff = true;
  53098. /**
  53099. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53100. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53101. */
  53102. this.useRadianceOverAlpha = true;
  53103. /**
  53104. * Allows using the bump map in parallax mode.
  53105. */
  53106. this.useParallax = false;
  53107. /**
  53108. * Allows using the bump map in parallax occlusion mode.
  53109. */
  53110. this.useParallaxOcclusion = false;
  53111. /**
  53112. * Controls the scale bias of the parallax mode.
  53113. */
  53114. this.parallaxScaleBias = 0.05;
  53115. /**
  53116. * If sets to true, disables all the lights affecting the material.
  53117. */
  53118. this.disableLighting = false;
  53119. /**
  53120. * Number of Simultaneous lights allowed on the material.
  53121. */
  53122. this.maxSimultaneousLights = 4;
  53123. /**
  53124. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53125. */
  53126. this.invertNormalMapX = false;
  53127. /**
  53128. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53129. */
  53130. this.invertNormalMapY = false;
  53131. this._renderTargets = new BABYLON.SmartArray(16);
  53132. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53133. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53134. this._tempColor = new BABYLON.Color3();
  53135. this._defines = new PBRMaterialDefines();
  53136. this._cachedDefines = new PBRMaterialDefines();
  53137. this._myScene = null;
  53138. this._myShadowGenerator = null;
  53139. this._cachedDefines.BonesPerMesh = -1;
  53140. this.getRenderTargetTextures = function () {
  53141. _this._renderTargets.reset();
  53142. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53143. _this._renderTargets.push(_this.reflectionTexture);
  53144. }
  53145. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53146. _this._renderTargets.push(_this.refractionTexture);
  53147. }
  53148. return _this._renderTargets;
  53149. };
  53150. }
  53151. PBRMaterial.prototype.getClassName = function () {
  53152. return "PBRMaterial";
  53153. };
  53154. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53155. get: function () {
  53156. return this._useLogarithmicDepth;
  53157. },
  53158. set: function (value) {
  53159. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53160. },
  53161. enumerable: true,
  53162. configurable: true
  53163. });
  53164. PBRMaterial.prototype.needAlphaBlending = function () {
  53165. if (this.linkRefractionWithTransparency) {
  53166. return false;
  53167. }
  53168. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53169. };
  53170. PBRMaterial.prototype.needAlphaTesting = function () {
  53171. if (this.linkRefractionWithTransparency) {
  53172. return false;
  53173. }
  53174. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53175. };
  53176. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53177. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53178. };
  53179. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53180. return this.albedoTexture;
  53181. };
  53182. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53183. if (!mesh) {
  53184. return true;
  53185. }
  53186. if (this._defines.INSTANCES !== useInstances) {
  53187. return false;
  53188. }
  53189. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53190. return true;
  53191. }
  53192. return false;
  53193. };
  53194. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53195. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53196. };
  53197. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53198. if (!useScalarInLinear) {
  53199. color.toLinearSpaceToRef(ref);
  53200. }
  53201. else {
  53202. ref.r = color.r;
  53203. ref.g = color.g;
  53204. ref.b = color.b;
  53205. }
  53206. };
  53207. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53208. var lightIndex = 0;
  53209. var depthValuesAlreadySet = false;
  53210. for (var index = 0; index < scene.lights.length; index++) {
  53211. var light = scene.lights[index];
  53212. if (!light.isEnabled()) {
  53213. continue;
  53214. }
  53215. if (!light.canAffectMesh(mesh)) {
  53216. continue;
  53217. }
  53218. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53219. // GAMMA CORRECTION.
  53220. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53221. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53222. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53223. if (defines["SPECULARTERM"]) {
  53224. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53225. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53226. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53227. }
  53228. // Shadows
  53229. if (scene.shadowsEnabled) {
  53230. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53231. }
  53232. lightIndex++;
  53233. if (lightIndex === maxSimultaneousLights)
  53234. break;
  53235. }
  53236. };
  53237. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53238. if (this.checkReadyOnlyOnce) {
  53239. if (this._wasPreviouslyReady) {
  53240. return true;
  53241. }
  53242. }
  53243. var scene = this.getScene();
  53244. var engine = scene.getEngine();
  53245. var needNormals = false;
  53246. var needUVs = false;
  53247. this._defines.reset();
  53248. if (scene.lightsEnabled && !this.disableLighting) {
  53249. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53250. }
  53251. if (!this.checkReadyOnEveryCall) {
  53252. if (this._renderId === scene.getRenderId()) {
  53253. if (this._checkCache(scene, mesh, useInstances)) {
  53254. return true;
  53255. }
  53256. }
  53257. }
  53258. if (scene.texturesEnabled) {
  53259. if (scene.getEngine().getCaps().textureLOD) {
  53260. this._defines.LODBASEDMICROSFURACE = true;
  53261. }
  53262. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53263. if (!this.albedoTexture.isReady()) {
  53264. return false;
  53265. }
  53266. else {
  53267. needUVs = true;
  53268. this._defines.ALBEDO = true;
  53269. }
  53270. }
  53271. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53272. if (!this.ambientTexture.isReady()) {
  53273. return false;
  53274. }
  53275. else {
  53276. needUVs = true;
  53277. this._defines.AMBIENT = true;
  53278. }
  53279. }
  53280. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53281. if (!this.opacityTexture.isReady()) {
  53282. return false;
  53283. }
  53284. else {
  53285. needUVs = true;
  53286. this._defines.OPACITY = true;
  53287. if (this.opacityTexture.getAlphaFromRGB) {
  53288. this._defines.OPACITYRGB = true;
  53289. }
  53290. }
  53291. }
  53292. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53293. if (!this.reflectionTexture.isReady()) {
  53294. return false;
  53295. }
  53296. else {
  53297. needNormals = true;
  53298. this._defines.REFLECTION = true;
  53299. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53300. this._defines.INVERTCUBICMAP = true;
  53301. }
  53302. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53303. switch (this.reflectionTexture.coordinatesMode) {
  53304. case BABYLON.Texture.CUBIC_MODE:
  53305. case BABYLON.Texture.INVCUBIC_MODE:
  53306. this._defines.REFLECTIONMAP_CUBIC = true;
  53307. break;
  53308. case BABYLON.Texture.EXPLICIT_MODE:
  53309. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53310. break;
  53311. case BABYLON.Texture.PLANAR_MODE:
  53312. this._defines.REFLECTIONMAP_PLANAR = true;
  53313. break;
  53314. case BABYLON.Texture.PROJECTION_MODE:
  53315. this._defines.REFLECTIONMAP_PROJECTION = true;
  53316. break;
  53317. case BABYLON.Texture.SKYBOX_MODE:
  53318. this._defines.REFLECTIONMAP_SKYBOX = true;
  53319. break;
  53320. case BABYLON.Texture.SPHERICAL_MODE:
  53321. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53322. break;
  53323. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53324. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53325. break;
  53326. }
  53327. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53328. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53329. needNormals = true;
  53330. if (this.reflectionTexture.isPMREM) {
  53331. this._defines.USEPMREMREFLECTION = true;
  53332. }
  53333. }
  53334. }
  53335. }
  53336. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53337. if (!this.lightmapTexture.isReady()) {
  53338. return false;
  53339. }
  53340. else {
  53341. needUVs = true;
  53342. this._defines.LIGHTMAP = true;
  53343. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53344. }
  53345. }
  53346. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53347. if (!this.emissiveTexture.isReady()) {
  53348. return false;
  53349. }
  53350. else {
  53351. needUVs = true;
  53352. this._defines.EMISSIVE = true;
  53353. }
  53354. }
  53355. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53356. if (this.metallicTexture) {
  53357. if (!this.metallicTexture.isReady()) {
  53358. return false;
  53359. }
  53360. else {
  53361. needUVs = true;
  53362. this._defines.METALLICWORKFLOW = true;
  53363. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53364. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53365. }
  53366. }
  53367. else if (this.reflectivityTexture) {
  53368. if (!this.reflectivityTexture.isReady()) {
  53369. return false;
  53370. }
  53371. else {
  53372. needUVs = true;
  53373. this._defines.REFLECTIVITY = true;
  53374. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53375. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53376. }
  53377. }
  53378. }
  53379. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53380. if (!this.bumpTexture.isReady()) {
  53381. return false;
  53382. }
  53383. else {
  53384. needUVs = true;
  53385. this._defines.BUMP = true;
  53386. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53387. this._defines.PARALLAX = true;
  53388. if (this.useParallaxOcclusion) {
  53389. this._defines.PARALLAXOCCLUSION = true;
  53390. }
  53391. }
  53392. if (this.invertNormalMapX) {
  53393. this._defines.INVERTNORMALMAPX = true;
  53394. }
  53395. if (this.invertNormalMapY) {
  53396. this._defines.INVERTNORMALMAPY = true;
  53397. }
  53398. }
  53399. }
  53400. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53401. if (!this.refractionTexture.isReady()) {
  53402. return false;
  53403. }
  53404. else {
  53405. needUVs = true;
  53406. this._defines.REFRACTION = true;
  53407. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53408. if (this.linkRefractionWithTransparency) {
  53409. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53410. }
  53411. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53412. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53413. if (this.refractionTexture.isPMREM) {
  53414. this._defines.USEPMREMREFRACTION = true;
  53415. }
  53416. }
  53417. }
  53418. }
  53419. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53420. if (!this.cameraColorGradingTexture.isReady()) {
  53421. return false;
  53422. }
  53423. else {
  53424. this._defines.CAMERACOLORGRADING = true;
  53425. }
  53426. }
  53427. }
  53428. // Effect
  53429. if (scene.clipPlane) {
  53430. this._defines.CLIPPLANE = true;
  53431. }
  53432. if (engine.getAlphaTesting()) {
  53433. this._defines.ALPHATEST = true;
  53434. }
  53435. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53436. this._defines.ALPHAFROMALBEDO = true;
  53437. }
  53438. if (this.useEmissiveAsIllumination) {
  53439. this._defines.EMISSIVEASILLUMINATION = true;
  53440. }
  53441. if (this.linkEmissiveWithAlbedo) {
  53442. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53443. }
  53444. if (this.useLogarithmicDepth) {
  53445. this._defines.LOGARITHMICDEPTH = true;
  53446. }
  53447. if (this.cameraContrast != 1) {
  53448. this._defines.CAMERACONTRAST = true;
  53449. }
  53450. if (this.cameraExposure != 1) {
  53451. this._defines.CAMERATONEMAP = true;
  53452. }
  53453. if (this.cameraColorCurves) {
  53454. this._defines.CAMERACOLORCURVES = true;
  53455. }
  53456. if (this.overloadedShadeIntensity != 1 ||
  53457. this.overloadedShadowIntensity != 1) {
  53458. this._defines.OVERLOADEDSHADOWVALUES = true;
  53459. }
  53460. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53461. this.overloadedEmissiveIntensity > 0 ||
  53462. this.overloadedReflectivityIntensity > 0 ||
  53463. this.overloadedAlbedoIntensity > 0 ||
  53464. this.overloadedAmbientIntensity > 0 ||
  53465. this.overloadedReflectionIntensity > 0) {
  53466. this._defines.OVERLOADEDVALUES = true;
  53467. }
  53468. // Point size
  53469. if (this.pointsCloud || scene.forcePointsCloud) {
  53470. this._defines.POINTSIZE = true;
  53471. }
  53472. // Fog
  53473. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53474. this._defines.FOG = true;
  53475. }
  53476. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53477. // Fresnel
  53478. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53479. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53480. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53481. this._defines.OPACITYFRESNEL = true;
  53482. }
  53483. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53484. this._defines.EMISSIVEFRESNEL = true;
  53485. }
  53486. needNormals = true;
  53487. this._defines.FRESNEL = true;
  53488. }
  53489. }
  53490. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53491. this._defines.SPECULAROVERALPHA = true;
  53492. }
  53493. if (this.usePhysicalLightFalloff) {
  53494. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53495. }
  53496. if (this.useRadianceOverAlpha) {
  53497. this._defines.RADIANCEOVERALPHA = true;
  53498. }
  53499. // Attribs
  53500. if (mesh) {
  53501. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53502. this._defines.NORMAL = true;
  53503. }
  53504. if (needUVs) {
  53505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53506. this._defines.UV1 = true;
  53507. }
  53508. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53509. this._defines.UV2 = true;
  53510. }
  53511. }
  53512. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53513. this._defines.VERTEXCOLOR = true;
  53514. if (mesh.hasVertexAlpha) {
  53515. this._defines.VERTEXALPHA = true;
  53516. }
  53517. }
  53518. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53519. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53520. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53521. }
  53522. // Instances
  53523. if (useInstances) {
  53524. this._defines.INSTANCES = true;
  53525. }
  53526. }
  53527. // Get correct effect
  53528. if (!this._defines.isEqual(this._cachedDefines)) {
  53529. this._defines.cloneTo(this._cachedDefines);
  53530. scene.resetCachedMaterial();
  53531. // Fallbacks
  53532. var fallbacks = new BABYLON.EffectFallbacks();
  53533. if (this._defines.REFLECTION) {
  53534. fallbacks.addFallback(0, "REFLECTION");
  53535. }
  53536. if (this._defines.REFRACTION) {
  53537. fallbacks.addFallback(0, "REFRACTION");
  53538. }
  53539. if (this._defines.REFLECTIVITY) {
  53540. fallbacks.addFallback(0, "REFLECTIVITY");
  53541. }
  53542. if (this._defines.BUMP) {
  53543. fallbacks.addFallback(0, "BUMP");
  53544. }
  53545. if (this._defines.PARALLAX) {
  53546. fallbacks.addFallback(1, "PARALLAX");
  53547. }
  53548. if (this._defines.PARALLAXOCCLUSION) {
  53549. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53550. }
  53551. if (this._defines.SPECULAROVERALPHA) {
  53552. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53553. }
  53554. if (this._defines.FOG) {
  53555. fallbacks.addFallback(1, "FOG");
  53556. }
  53557. if (this._defines.POINTSIZE) {
  53558. fallbacks.addFallback(0, "POINTSIZE");
  53559. }
  53560. if (this._defines.LOGARITHMICDEPTH) {
  53561. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53562. }
  53563. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53564. if (this._defines.SPECULARTERM) {
  53565. fallbacks.addFallback(0, "SPECULARTERM");
  53566. }
  53567. if (this._defines.OPACITYFRESNEL) {
  53568. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53569. }
  53570. if (this._defines.EMISSIVEFRESNEL) {
  53571. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53572. }
  53573. if (this._defines.FRESNEL) {
  53574. fallbacks.addFallback(3, "FRESNEL");
  53575. }
  53576. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53577. fallbacks.addCPUSkinningFallback(0, mesh);
  53578. }
  53579. //Attributes
  53580. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53581. if (this._defines.NORMAL) {
  53582. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53583. }
  53584. if (this._defines.UV1) {
  53585. attribs.push(BABYLON.VertexBuffer.UVKind);
  53586. }
  53587. if (this._defines.UV2) {
  53588. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53589. }
  53590. if (this._defines.VERTEXCOLOR) {
  53591. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53592. }
  53593. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53594. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53595. // Legacy browser patch
  53596. var join = this._defines.toString();
  53597. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53598. "vFogInfos", "vFogColor", "pointSize",
  53599. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53600. "mBones",
  53601. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53602. "depthValues",
  53603. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53604. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53605. "logarithmicDepthConstant",
  53606. "vSphericalX", "vSphericalY", "vSphericalZ",
  53607. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53608. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53609. "vMicrosurfaceTextureLods",
  53610. "vCameraInfos"
  53611. ];
  53612. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53613. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53614. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53615. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53616. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53617. }
  53618. if (!this._effect.isReady()) {
  53619. return false;
  53620. }
  53621. this._renderId = scene.getRenderId();
  53622. this._wasPreviouslyReady = true;
  53623. if (mesh) {
  53624. if (!mesh._materialDefines) {
  53625. mesh._materialDefines = new PBRMaterialDefines();
  53626. }
  53627. this._defines.cloneTo(mesh._materialDefines);
  53628. }
  53629. return true;
  53630. };
  53631. PBRMaterial.prototype.unbind = function () {
  53632. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53633. this._effect.setTexture("reflection2DSampler", null);
  53634. }
  53635. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53636. this._effect.setTexture("refraction2DSampler", null);
  53637. }
  53638. _super.prototype.unbind.call(this);
  53639. };
  53640. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53641. this._effect.setMatrix("world", world);
  53642. };
  53643. PBRMaterial.prototype.bind = function (world, mesh) {
  53644. this._myScene = this.getScene();
  53645. // Matrices
  53646. this.bindOnlyWorldMatrix(world);
  53647. // Bones
  53648. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53649. if (this._myScene.getCachedMaterial() !== this) {
  53650. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53651. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53652. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53653. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53654. }
  53655. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53656. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53657. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53658. }
  53659. }
  53660. // Textures
  53661. if (this._myScene.texturesEnabled) {
  53662. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53663. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53664. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53665. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53666. }
  53667. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53668. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53669. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53670. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53671. }
  53672. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53673. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53674. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53675. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53676. }
  53677. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53678. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53679. if (this.reflectionTexture.isCube) {
  53680. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53681. }
  53682. else {
  53683. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53684. }
  53685. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53686. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53687. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53688. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53689. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53690. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53691. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53692. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53693. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53694. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53695. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53696. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53697. }
  53698. }
  53699. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53700. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53701. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53702. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53703. }
  53704. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53705. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53706. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53707. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53708. }
  53709. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53710. if (this.metallicTexture) {
  53711. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53712. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53713. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53714. }
  53715. else if (this.reflectivityTexture) {
  53716. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53717. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53718. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53719. }
  53720. }
  53721. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53722. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53723. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53724. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53725. }
  53726. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53727. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53728. var depth = 1.0;
  53729. if (this.refractionTexture.isCube) {
  53730. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53731. }
  53732. else {
  53733. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53734. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53735. if (this.refractionTexture.depth) {
  53736. depth = this.refractionTexture.depth;
  53737. }
  53738. }
  53739. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53740. }
  53741. if ((this.reflectionTexture || this.refractionTexture)) {
  53742. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53743. }
  53744. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53745. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53746. }
  53747. }
  53748. // Clip plane
  53749. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53750. // Point size
  53751. if (this.pointsCloud) {
  53752. this._effect.setFloat("pointSize", this.pointSize);
  53753. }
  53754. // Colors
  53755. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53756. // GAMMA CORRECTION.
  53757. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53758. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53759. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53760. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53761. // GAMMA CORRECTION.
  53762. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53763. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53764. // GAMMA CORRECTION.
  53765. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53766. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53767. }
  53768. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53769. // GAMMA CORRECTION.
  53770. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53771. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53772. // Lights
  53773. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53774. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53775. }
  53776. // View
  53777. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53778. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53779. }
  53780. // Fog
  53781. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53782. this._lightingInfos.x = this.directIntensity;
  53783. this._lightingInfos.y = this.emissiveIntensity;
  53784. this._lightingInfos.z = this.environmentIntensity;
  53785. this._lightingInfos.w = this.specularIntensity;
  53786. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53787. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53788. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53789. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53790. this._cameraInfos.x = this.cameraExposure;
  53791. this._cameraInfos.y = this.cameraContrast;
  53792. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53793. if (this.cameraColorCurves) {
  53794. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53795. }
  53796. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53797. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53798. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53799. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53800. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53801. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53802. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53803. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53804. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53805. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53806. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53807. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53808. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53809. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53810. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53811. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53812. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53813. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53814. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53815. // Log. depth
  53816. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53817. }
  53818. _super.prototype.bind.call(this, world, mesh);
  53819. this._myScene = null;
  53820. };
  53821. PBRMaterial.prototype.getAnimatables = function () {
  53822. var results = [];
  53823. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53824. results.push(this.albedoTexture);
  53825. }
  53826. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53827. results.push(this.ambientTexture);
  53828. }
  53829. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53830. results.push(this.opacityTexture);
  53831. }
  53832. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53833. results.push(this.reflectionTexture);
  53834. }
  53835. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53836. results.push(this.emissiveTexture);
  53837. }
  53838. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  53839. results.push(this.metallicTexture);
  53840. }
  53841. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53842. results.push(this.reflectivityTexture);
  53843. }
  53844. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53845. results.push(this.bumpTexture);
  53846. }
  53847. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53848. results.push(this.lightmapTexture);
  53849. }
  53850. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53851. results.push(this.refractionTexture);
  53852. }
  53853. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53854. results.push(this.cameraColorGradingTexture);
  53855. }
  53856. return results;
  53857. };
  53858. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53859. if (forceDisposeTextures) {
  53860. if (this.albedoTexture) {
  53861. this.albedoTexture.dispose();
  53862. }
  53863. if (this.ambientTexture) {
  53864. this.ambientTexture.dispose();
  53865. }
  53866. if (this.opacityTexture) {
  53867. this.opacityTexture.dispose();
  53868. }
  53869. if (this.reflectionTexture) {
  53870. this.reflectionTexture.dispose();
  53871. }
  53872. if (this.emissiveTexture) {
  53873. this.emissiveTexture.dispose();
  53874. }
  53875. if (this.metallicTexture) {
  53876. this.metallicTexture.dispose();
  53877. }
  53878. if (this.reflectivityTexture) {
  53879. this.reflectivityTexture.dispose();
  53880. }
  53881. if (this.bumpTexture) {
  53882. this.bumpTexture.dispose();
  53883. }
  53884. if (this.lightmapTexture) {
  53885. this.lightmapTexture.dispose();
  53886. }
  53887. if (this.refractionTexture) {
  53888. this.refractionTexture.dispose();
  53889. }
  53890. if (this.cameraColorGradingTexture) {
  53891. this.cameraColorGradingTexture.dispose();
  53892. }
  53893. }
  53894. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53895. };
  53896. PBRMaterial.prototype.clone = function (name) {
  53897. var _this = this;
  53898. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53899. };
  53900. PBRMaterial.prototype.serialize = function () {
  53901. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53902. serializationObject.customType = "BABYLON.PBRMaterial";
  53903. return serializationObject;
  53904. };
  53905. // Statics
  53906. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53907. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53908. };
  53909. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53910. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53911. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53912. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53913. __decorate([
  53914. BABYLON.serialize()
  53915. ], PBRMaterial.prototype, "directIntensity", void 0);
  53916. __decorate([
  53917. BABYLON.serialize()
  53918. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53919. __decorate([
  53920. BABYLON.serialize()
  53921. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53922. __decorate([
  53923. BABYLON.serialize()
  53924. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53925. __decorate([
  53926. BABYLON.serialize()
  53927. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53928. __decorate([
  53929. BABYLON.serialize()
  53930. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53931. __decorate([
  53932. BABYLON.serialize()
  53933. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53934. __decorate([
  53935. BABYLON.serialize()
  53936. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53937. __decorate([
  53938. BABYLON.serialize()
  53939. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53940. __decorate([
  53941. BABYLON.serializeAsTexture()
  53942. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53943. __decorate([
  53944. BABYLON.serializeAsColorCurves()
  53945. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53946. __decorate([
  53947. BABYLON.serializeAsColor3()
  53948. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53949. __decorate([
  53950. BABYLON.serialize()
  53951. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53952. __decorate([
  53953. BABYLON.serializeAsColor3()
  53954. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53955. __decorate([
  53956. BABYLON.serialize()
  53957. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53958. __decorate([
  53959. BABYLON.serializeAsColor3()
  53960. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53961. __decorate([
  53962. BABYLON.serialize()
  53963. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53964. __decorate([
  53965. BABYLON.serializeAsColor3()
  53966. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  53967. __decorate([
  53968. BABYLON.serialize()
  53969. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  53970. __decorate([
  53971. BABYLON.serializeAsColor3()
  53972. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  53973. __decorate([
  53974. BABYLON.serialize()
  53975. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  53976. __decorate([
  53977. BABYLON.serialize()
  53978. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  53979. __decorate([
  53980. BABYLON.serialize()
  53981. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  53982. __decorate([
  53983. BABYLON.serializeAsTexture()
  53984. ], PBRMaterial.prototype, "albedoTexture", void 0);
  53985. __decorate([
  53986. BABYLON.serializeAsTexture()
  53987. ], PBRMaterial.prototype, "ambientTexture", void 0);
  53988. __decorate([
  53989. BABYLON.serialize()
  53990. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  53991. __decorate([
  53992. BABYLON.serializeAsTexture()
  53993. ], PBRMaterial.prototype, "opacityTexture", void 0);
  53994. __decorate([
  53995. BABYLON.serializeAsTexture()
  53996. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  53997. __decorate([
  53998. BABYLON.serializeAsTexture()
  53999. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54000. __decorate([
  54001. BABYLON.serializeAsTexture()
  54002. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54003. __decorate([
  54004. BABYLON.serializeAsTexture()
  54005. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54006. __decorate([
  54007. BABYLON.serializeAsTexture()
  54008. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54009. __decorate([
  54010. BABYLON.serializeAsTexture()
  54011. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54012. __decorate([
  54013. BABYLON.serializeAsTexture()
  54014. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54015. __decorate([
  54016. BABYLON.serializeAsColor3("ambient")
  54017. ], PBRMaterial.prototype, "ambientColor", void 0);
  54018. __decorate([
  54019. BABYLON.serializeAsColor3("albedo")
  54020. ], PBRMaterial.prototype, "albedoColor", void 0);
  54021. __decorate([
  54022. BABYLON.serializeAsColor3("reflectivity")
  54023. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54024. __decorate([
  54025. BABYLON.serializeAsColor3("reflection")
  54026. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54027. __decorate([
  54028. BABYLON.serializeAsColor3("emissive")
  54029. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54030. __decorate([
  54031. BABYLON.serialize()
  54032. ], PBRMaterial.prototype, "microSurface", void 0);
  54033. __decorate([
  54034. BABYLON.serialize()
  54035. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54036. __decorate([
  54037. BABYLON.serialize()
  54038. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54039. __decorate([
  54040. BABYLON.serializeAsFresnelParameters()
  54041. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54042. __decorate([
  54043. BABYLON.serializeAsFresnelParameters()
  54044. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54045. __decorate([
  54046. BABYLON.serialize()
  54047. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54048. __decorate([
  54049. BABYLON.serialize()
  54050. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54051. __decorate([
  54052. BABYLON.serialize()
  54053. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54054. __decorate([
  54055. BABYLON.serialize()
  54056. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54057. __decorate([
  54058. BABYLON.serialize()
  54059. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54060. __decorate([
  54061. BABYLON.serialize()
  54062. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54063. __decorate([
  54064. BABYLON.serialize()
  54065. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54066. __decorate([
  54067. BABYLON.serialize()
  54068. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54069. __decorate([
  54070. BABYLON.serialize()
  54071. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54072. __decorate([
  54073. BABYLON.serialize()
  54074. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54075. __decorate([
  54076. BABYLON.serialize()
  54077. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54078. __decorate([
  54079. BABYLON.serialize()
  54080. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54081. __decorate([
  54082. BABYLON.serialize()
  54083. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54084. __decorate([
  54085. BABYLON.serialize()
  54086. ], PBRMaterial.prototype, "useParallax", void 0);
  54087. __decorate([
  54088. BABYLON.serialize()
  54089. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54090. __decorate([
  54091. BABYLON.serialize()
  54092. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54093. __decorate([
  54094. BABYLON.serialize()
  54095. ], PBRMaterial.prototype, "disableLighting", void 0);
  54096. __decorate([
  54097. BABYLON.serialize()
  54098. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54099. __decorate([
  54100. BABYLON.serialize()
  54101. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54102. __decorate([
  54103. BABYLON.serialize()
  54104. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54105. __decorate([
  54106. BABYLON.serialize()
  54107. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54108. return PBRMaterial;
  54109. }(BABYLON.Material));
  54110. BABYLON.PBRMaterial = PBRMaterial;
  54111. })(BABYLON || (BABYLON = {}));
  54112. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54113. var BABYLON;
  54114. (function (BABYLON) {
  54115. var DebugLayer = (function () {
  54116. function DebugLayer(scene) {
  54117. this._scene = scene;
  54118. }
  54119. /** Creates the inspector window. */
  54120. DebugLayer.prototype._createInspector = function () {
  54121. if (!this._inspector) {
  54122. this._inspector = new INSPECTOR.Inspector(this._scene);
  54123. } // else nothing to do,; instance is already existing
  54124. };
  54125. DebugLayer.prototype.isVisible = function () {
  54126. return false;
  54127. };
  54128. DebugLayer.prototype.hide = function () {
  54129. if (this._inspector) {
  54130. this._inspector.dispose();
  54131. this._inspector = null;
  54132. }
  54133. };
  54134. DebugLayer.prototype.show = function () {
  54135. if (typeof INSPECTOR == 'undefined') {
  54136. // Load inspector and add it to the DOM
  54137. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this));
  54138. }
  54139. else {
  54140. // Otherwise creates the inspector
  54141. this._createInspector();
  54142. }
  54143. };
  54144. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54145. return DebugLayer;
  54146. }());
  54147. BABYLON.DebugLayer = DebugLayer;
  54148. })(BABYLON || (BABYLON = {}));
  54149. //# sourceMappingURL=babylon.debugLayer.js.map
  54150. var BABYLON;
  54151. (function (BABYLON) {
  54152. var StandardRenderingPipeline = (function (_super) {
  54153. __extends(StandardRenderingPipeline, _super);
  54154. /**
  54155. * @constructor
  54156. * @param {string} name - The rendering pipeline name
  54157. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54158. * @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)
  54159. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54160. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54161. */
  54162. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54163. var _this = this;
  54164. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54165. _super.call(this, scene.getEngine(), name);
  54166. this.downSampleX4PostProcess = null;
  54167. this.brightPassPostProcess = null;
  54168. this.gaussianBlurHPostProcesses = [];
  54169. this.gaussianBlurVPostProcesses = [];
  54170. this.textureAdderPostProcess = null;
  54171. this.textureAdderFinalPostProcess = null;
  54172. this.lensFlarePostProcess = null;
  54173. this.lensFlareComposePostProcess = null;
  54174. this.depthOfFieldPostProcess = null;
  54175. // Values
  54176. this.brightThreshold = 1.0;
  54177. this.blurWidth = 2.0;
  54178. this.gaussianCoefficient = 0.25;
  54179. this.gaussianMean = 1.0;
  54180. this.gaussianStandardDeviation = 1.0;
  54181. this.exposure = 1.0;
  54182. this.lensTexture = null;
  54183. this.lensColorTexture = null;
  54184. this.lensFlareStrength = 20.0;
  54185. this.lensFlareGhostDispersal = 1.4;
  54186. this.lensFlareHaloWidth = 0.7;
  54187. this.lensFlareDistortionStrength = 16.0;
  54188. this.lensStarTexture = null;
  54189. this.lensFlareDirtTexture = null;
  54190. this.depthOfFieldDistance = 10.0;
  54191. // IAnimatable
  54192. this.animations = [];
  54193. this._depthRenderer = null;
  54194. // Getters and setters
  54195. this._depthOfFieldEnabled = true;
  54196. this._lensFlareEnabled = true;
  54197. // Initialize
  54198. this._scene = scene;
  54199. // Create pass post-processe
  54200. if (!originalPostProcess) {
  54201. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54202. }
  54203. else {
  54204. this.originalPostProcess = originalPostProcess;
  54205. }
  54206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54207. // Create down sample X4 post-process
  54208. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54209. // Create bright pass post-process
  54210. this._createBrightPassPostProcess(scene, ratio / 2);
  54211. // Create gaussian blur post-processes (down sampling blurs)
  54212. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54213. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54214. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54215. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54216. // Create texture adder post-process
  54217. this._createTextureAdderPostProcess(scene, ratio);
  54218. // Create depth-of-field source post-process
  54219. 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);
  54220. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54221. // Create lens flare post-process
  54222. this._createLensFlarePostProcess(scene, ratio);
  54223. // Create gaussian blur used by depth-of-field
  54224. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54225. // Create depth-of-field post-process
  54226. this._createDepthOfFieldPostProcess(scene, ratio);
  54227. // Finish
  54228. scene.postProcessRenderPipelineManager.addPipeline(this);
  54229. if (cameras !== null) {
  54230. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54231. }
  54232. // Deactivate
  54233. this.LensFlareEnabled = false;
  54234. this.DepthOfFieldEnabled = false;
  54235. }
  54236. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54237. get: function () {
  54238. return this._depthOfFieldEnabled;
  54239. },
  54240. set: function (enabled) {
  54241. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54242. if (enabled && !this._depthOfFieldEnabled) {
  54243. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54244. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54245. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54246. this._depthRenderer = this._scene.enableDepthRenderer();
  54247. }
  54248. else if (!enabled && this._depthOfFieldEnabled) {
  54249. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54250. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54251. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54252. }
  54253. this._depthOfFieldEnabled = enabled;
  54254. },
  54255. enumerable: true,
  54256. configurable: true
  54257. });
  54258. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54259. get: function () {
  54260. return this._lensFlareEnabled;
  54261. },
  54262. set: function (enabled) {
  54263. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54264. if (enabled && !this._lensFlareEnabled) {
  54265. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54266. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54267. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54268. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54269. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54270. }
  54271. else if (!enabled && this._lensFlareEnabled) {
  54272. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54273. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54274. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54275. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54276. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54277. }
  54278. this._lensFlareEnabled = enabled;
  54279. },
  54280. enumerable: true,
  54281. configurable: true
  54282. });
  54283. // Down Sample X4 Post-Processs
  54284. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54285. var _this = this;
  54286. var downSampleX4Offsets = new Array(32);
  54287. 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);
  54288. this.downSampleX4PostProcess.onApply = function (effect) {
  54289. var id = 0;
  54290. for (var i = -2; i < 2; i++) {
  54291. for (var j = -2; j < 2; j++) {
  54292. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54293. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54294. id += 2;
  54295. }
  54296. }
  54297. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54298. };
  54299. // Add to pipeline
  54300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54301. };
  54302. // Brightpass Post-Process
  54303. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54304. var _this = this;
  54305. var brightOffsets = new Array(8);
  54306. 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);
  54307. this.brightPassPostProcess.onApply = function (effect) {
  54308. var sU = (1.0 / _this.brightPassPostProcess.width);
  54309. var sV = (1.0 / _this.brightPassPostProcess.height);
  54310. brightOffsets[0] = -0.5 * sU;
  54311. brightOffsets[1] = 0.5 * sV;
  54312. brightOffsets[2] = 0.5 * sU;
  54313. brightOffsets[3] = 0.5 * sV;
  54314. brightOffsets[4] = -0.5 * sU;
  54315. brightOffsets[5] = -0.5 * sV;
  54316. brightOffsets[6] = 0.5 * sU;
  54317. brightOffsets[7] = -0.5 * sV;
  54318. effect.setArray2("dsOffsets", brightOffsets);
  54319. effect.setFloat("brightThreshold", _this.brightThreshold);
  54320. };
  54321. // Add to pipeline
  54322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54323. };
  54324. // Create gaussian blur H&V post-processes
  54325. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54326. var _this = this;
  54327. var blurOffsets = new Array(9);
  54328. var blurWeights = new Array(9);
  54329. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54330. var callback = function (height) {
  54331. return function (effect) {
  54332. // Weights
  54333. var x = 0.0;
  54334. for (var i = 0; i < 9; i++) {
  54335. x = (i - 4.0) / 4.0;
  54336. blurWeights[i] =
  54337. _this.gaussianCoefficient
  54338. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54339. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54340. }
  54341. var lastOutputDimensions = {
  54342. width: scene.getEngine().getRenderWidth(),
  54343. height: scene.getEngine().getRenderHeight()
  54344. };
  54345. for (var i = 0; i < 9; i++) {
  54346. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54347. blurOffsets[i] = value;
  54348. }
  54349. effect.setArray("blurOffsets", blurOffsets);
  54350. effect.setArray("blurWeights", blurWeights);
  54351. effect.setFloat("blurWidth", _this.blurWidth);
  54352. };
  54353. };
  54354. // Create horizontal gaussian blur post-processes
  54355. 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);
  54356. gaussianBlurHPostProcess.onApply = callback(false);
  54357. // Create vertical gaussian blur post-process
  54358. 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);
  54359. gaussianBlurVPostProcess.onApply = callback(true);
  54360. // Add to pipeline
  54361. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54362. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54363. // Finish
  54364. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54365. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54366. };
  54367. // Create texture adder post-process
  54368. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54369. var _this = this;
  54370. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54371. 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);
  54372. this.textureAdderPostProcess.onApply = function (effect) {
  54373. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54374. effect.setTexture("lensSampler", _this.lensTexture);
  54375. effect.setFloat("exposure", _this.exposure);
  54376. };
  54377. // Add to pipeline
  54378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54379. };
  54380. // Create lens flare post-process
  54381. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54382. var _this = this;
  54383. 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);
  54384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54385. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54386. 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);
  54387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54388. var resolution = new BABYLON.Vector2(0, 0);
  54389. // Lens flare
  54390. this.lensFlarePostProcess.onApply = function (effect) {
  54391. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54392. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54393. effect.setFloat("strength", _this.lensFlareStrength);
  54394. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54395. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54396. // Shift
  54397. resolution.x = _this.lensFlarePostProcess.width;
  54398. resolution.y = _this.lensFlarePostProcess.height;
  54399. effect.setVector2("resolution", resolution);
  54400. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54401. };
  54402. // Compose
  54403. 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);
  54404. 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);
  54405. this.lensFlareComposePostProcess.onApply = function (effect) {
  54406. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54407. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54408. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54409. // Lens start rotation matrix
  54410. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54411. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54412. 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));
  54413. camRot *= 4.0;
  54414. 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);
  54415. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54416. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54417. };
  54418. };
  54419. // Create depth-of-field post-process
  54420. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54421. var _this = this;
  54422. 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);
  54423. this.depthOfFieldPostProcess.onApply = function (effect) {
  54424. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54425. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54426. effect.setFloat("distance", _this.depthOfFieldDistance);
  54427. };
  54428. // Add to pipeline
  54429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54430. };
  54431. // Dispose
  54432. StandardRenderingPipeline.prototype.dispose = function () {
  54433. for (var i = 0; i < this._scene.cameras.length; i++) {
  54434. var camera = this._scene.cameras[i];
  54435. this.originalPostProcess.dispose(camera);
  54436. this.downSampleX4PostProcess.dispose(camera);
  54437. this.brightPassPostProcess.dispose(camera);
  54438. this.textureAdderPostProcess.dispose(camera);
  54439. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54440. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54441. }
  54442. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54443. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54444. }
  54445. this.textureAdderFinalPostProcess.dispose(camera);
  54446. this.lensFlarePostProcess.dispose(camera);
  54447. this.lensFlareComposePostProcess.dispose(camera);
  54448. this.depthOfFieldPostProcess.dispose(camera);
  54449. }
  54450. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54451. _super.prototype.dispose.call(this);
  54452. };
  54453. return StandardRenderingPipeline;
  54454. }(BABYLON.PostProcessRenderPipeline));
  54455. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54456. })(BABYLON || (BABYLON = {}));
  54457. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54458. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nfloat metallic=surfaceMetallicColorMap.r; \n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallic);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallic);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmicroSurface=1.0-surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmicroSurface=1.0-surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  54459. 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"};
  54460. 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={}));";
  54461. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54462. module.exports = BABYLON;
  54463. };