babylon.max.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593
  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. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Returns the Color3 hexadecimal code as a string.
  236. */
  237. Color3.prototype.toHexString = function () {
  238. var intR = (this.r * 255) | 0;
  239. var intG = (this.g * 255) | 0;
  240. var intB = (this.b * 255) | 0;
  241. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  242. };
  243. /**
  244. * Returns a new Color3 converted to linear space.
  245. */
  246. Color3.prototype.toLinearSpace = function () {
  247. var convertedColor = new Color3();
  248. this.toLinearSpaceToRef(convertedColor);
  249. return convertedColor;
  250. };
  251. /**
  252. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  253. * Returns the unmodified Color3.
  254. */
  255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  259. return this;
  260. };
  261. /**
  262. * Returns a new Color3 converted to gamma space.
  263. */
  264. Color3.prototype.toGammaSpace = function () {
  265. var convertedColor = new Color3();
  266. this.toGammaSpaceToRef(convertedColor);
  267. return convertedColor;
  268. };
  269. /**
  270. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  271. * Returns the unmodified Color3.
  272. */
  273. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  274. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  275. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  276. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  277. return this;
  278. };
  279. // Statics
  280. /**
  281. * Creates a new Color3 from the string containing valid hexadecimal values.
  282. */
  283. Color3.FromHexString = function (hex) {
  284. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  285. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  286. return new Color3(0, 0, 0);
  287. }
  288. var r = parseInt(hex.substring(1, 3), 16);
  289. var g = parseInt(hex.substring(3, 5), 16);
  290. var b = parseInt(hex.substring(5, 7), 16);
  291. return Color3.FromInts(r, g, b);
  292. };
  293. /**
  294. * Creates a new Vector3 from the startind index of the passed array.
  295. */
  296. Color3.FromArray = function (array, offset) {
  297. if (offset === void 0) { offset = 0; }
  298. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  299. };
  300. /**
  301. * Creates a new Color3 from integer values ( < 256).
  302. */
  303. Color3.FromInts = function (r, g, b) {
  304. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  305. };
  306. /**
  307. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  308. */
  309. Color3.Lerp = function (start, end, amount) {
  310. var r = start.r + ((end.r - start.r) * amount);
  311. var g = start.g + ((end.g - start.g) * amount);
  312. var b = start.b + ((end.b - start.b) * amount);
  313. return new Color3(r, g, b);
  314. };
  315. Color3.Red = function () { return new Color3(1, 0, 0); };
  316. Color3.Green = function () { return new Color3(0, 1, 0); };
  317. Color3.Blue = function () { return new Color3(0, 0, 1); };
  318. Color3.Black = function () { return new Color3(0, 0, 0); };
  319. Color3.White = function () { return new Color3(1, 1, 1); };
  320. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  321. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  322. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  323. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  324. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  325. return Color3;
  326. }());
  327. BABYLON.Color3 = Color3;
  328. var Color4 = (function () {
  329. /**
  330. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  331. */
  332. function Color4(r, g, b, a) {
  333. this.r = r;
  334. this.g = g;
  335. this.b = b;
  336. this.a = a;
  337. }
  338. // Operators
  339. /**
  340. * Adds in place the passed Color4 values to the current Color4.
  341. * Returns the updated Color4.
  342. */
  343. Color4.prototype.addInPlace = function (right) {
  344. this.r += right.r;
  345. this.g += right.g;
  346. this.b += right.b;
  347. this.a += right.a;
  348. return this;
  349. };
  350. /**
  351. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  352. */
  353. Color4.prototype.asArray = function () {
  354. var result = [];
  355. this.toArray(result, 0);
  356. return result;
  357. };
  358. /**
  359. * Stores from the starting index in the passed array the Color4 successive values.
  360. * Returns the Color4.
  361. */
  362. Color4.prototype.toArray = function (array, index) {
  363. if (index === undefined) {
  364. index = 0;
  365. }
  366. array[index] = this.r;
  367. array[index + 1] = this.g;
  368. array[index + 2] = this.b;
  369. array[index + 3] = this.a;
  370. return this;
  371. };
  372. /**
  373. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  374. */
  375. Color4.prototype.add = function (right) {
  376. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  377. };
  378. /**
  379. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  380. */
  381. Color4.prototype.subtract = function (right) {
  382. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  383. };
  384. /**
  385. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  386. * Returns the Color4.
  387. */
  388. Color4.prototype.subtractToRef = function (right, result) {
  389. result.r = this.r - right.r;
  390. result.g = this.g - right.g;
  391. result.b = this.b - right.b;
  392. result.a = this.a - right.a;
  393. return this;
  394. };
  395. /**
  396. * Creates a new Color4 with the current Color4 values multiplied by scale.
  397. */
  398. Color4.prototype.scale = function (scale) {
  399. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  400. };
  401. /**
  402. * Multiplies the current Color4 values by scale and stores the result in "result".
  403. * Returns the Color4.
  404. */
  405. Color4.prototype.scaleToRef = function (scale, result) {
  406. result.r = this.r * scale;
  407. result.g = this.g * scale;
  408. result.b = this.b * scale;
  409. result.a = this.a * scale;
  410. return this;
  411. };
  412. /**
  413. * Multipy an RGBA Color4 value by another and return a new Color4 object
  414. * @param color The Color4 (RGBA) value to multiply by
  415. * @returns A new Color4.
  416. */
  417. Color4.prototype.multiply = function (color) {
  418. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  419. };
  420. /**
  421. * Multipy an RGBA Color4 value by another and push the result in a reference value
  422. * @param color The Color4 (RGBA) value to multiply by
  423. * @param result The Color4 (RGBA) to fill the result in
  424. * @returns the result Color4.
  425. */
  426. Color4.prototype.multiplyToRef = function (color, result) {
  427. result.r = this.r * color.r;
  428. result.g = this.g * color.g;
  429. result.b = this.b * color.b;
  430. result.a = this.a * color.a;
  431. return result;
  432. };
  433. /**
  434. * Returns a string with the Color4 values.
  435. */
  436. Color4.prototype.toString = function () {
  437. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  438. };
  439. /**
  440. * Returns the string "Color4"
  441. */
  442. Color4.prototype.getClassName = function () {
  443. return "Color4";
  444. };
  445. /**
  446. * Return the Color4 hash code as a number.
  447. */
  448. Color4.prototype.getHashCode = function () {
  449. var hash = this.r || 0;
  450. hash = (hash * 397) ^ (this.g || 0);
  451. hash = (hash * 397) ^ (this.b || 0);
  452. hash = (hash * 397) ^ (this.a || 0);
  453. return hash;
  454. };
  455. /**
  456. * Creates a new Color4 copied from the current one.
  457. */
  458. Color4.prototype.clone = function () {
  459. return new Color4(this.r, this.g, this.b, this.a);
  460. };
  461. /**
  462. * Copies the passed Color4 values into the current one.
  463. * Returns the updated Color4.
  464. */
  465. Color4.prototype.copyFrom = function (source) {
  466. this.r = source.r;
  467. this.g = source.g;
  468. this.b = source.b;
  469. this.a = source.a;
  470. return this;
  471. };
  472. /**
  473. * Returns a string containing the hexadecimal Color4 code.
  474. */
  475. Color4.prototype.toHexString = function () {
  476. var intR = (this.r * 255) | 0;
  477. var intG = (this.g * 255) | 0;
  478. var intB = (this.b * 255) | 0;
  479. var intA = (this.a * 255) | 0;
  480. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  481. };
  482. // Statics
  483. /**
  484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  485. */
  486. Color4.FromHexString = function (hex) {
  487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  489. return new Color4(0.0, 0.0, 0.0, 0.0);
  490. }
  491. var r = parseInt(hex.substring(1, 3), 16);
  492. var g = parseInt(hex.substring(3, 5), 16);
  493. var b = parseInt(hex.substring(5, 7), 16);
  494. var a = parseInt(hex.substring(7, 9), 16);
  495. return Color4.FromInts(r, g, b, a);
  496. };
  497. /**
  498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  499. */
  500. Color4.Lerp = function (left, right, amount) {
  501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  502. Color4.LerpToRef(left, right, amount, result);
  503. return result;
  504. };
  505. /**
  506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  507. */
  508. Color4.LerpToRef = function (left, right, amount, result) {
  509. result.r = left.r + (right.r - left.r) * amount;
  510. result.g = left.g + (right.g - left.g) * amount;
  511. result.b = left.b + (right.b - left.b) * amount;
  512. result.a = left.a + (right.a - left.a) * amount;
  513. };
  514. /**
  515. * Creates a new Color4 from the starting index element of the passed array.
  516. */
  517. Color4.FromArray = function (array, offset) {
  518. if (offset === void 0) { offset = 0; }
  519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  520. };
  521. /**
  522. * Creates a new Color4 from the passed integers ( < 256 ).
  523. */
  524. Color4.FromInts = function (r, g, b, a) {
  525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  526. };
  527. Color4.CheckColors4 = function (colors, count) {
  528. // Check if color3 was used
  529. if (colors.length === count * 3) {
  530. var colors4 = [];
  531. for (var index = 0; index < colors.length; index += 3) {
  532. var newIndex = (index / 3) * 4;
  533. colors4[newIndex] = colors[index];
  534. colors4[newIndex + 1] = colors[index + 1];
  535. colors4[newIndex + 2] = colors[index + 2];
  536. colors4[newIndex + 3] = 1.0;
  537. }
  538. return colors4;
  539. }
  540. return colors;
  541. };
  542. return Color4;
  543. }());
  544. BABYLON.Color4 = Color4;
  545. var Vector2 = (function () {
  546. /**
  547. * Creates a new Vector2 from the passed x and y coordinates.
  548. */
  549. function Vector2(x, y) {
  550. this.x = x;
  551. this.y = y;
  552. }
  553. /**
  554. * Returns a string with the Vector2 coordinates.
  555. */
  556. Vector2.prototype.toString = function () {
  557. return "{X: " + this.x + " Y:" + this.y + "}";
  558. };
  559. /**
  560. * Returns the string "Vector2"
  561. */
  562. Vector2.prototype.getClassName = function () {
  563. return "Vector2";
  564. };
  565. /**
  566. * Returns the Vector2 hash code as a number.
  567. */
  568. Vector2.prototype.getHashCode = function () {
  569. var hash = this.x || 0;
  570. hash = (hash * 397) ^ (this.y || 0);
  571. return hash;
  572. };
  573. // Operators
  574. /**
  575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  576. * Returns the Vector2.
  577. */
  578. Vector2.prototype.toArray = function (array, index) {
  579. if (index === void 0) { index = 0; }
  580. array[index] = this.x;
  581. array[index + 1] = this.y;
  582. return this;
  583. };
  584. /**
  585. * Returns a new array with 2 elements : the Vector2 coordinates.
  586. */
  587. Vector2.prototype.asArray = function () {
  588. var result = [];
  589. this.toArray(result, 0);
  590. return result;
  591. };
  592. /**
  593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  594. * Returns the updated Vector2.
  595. */
  596. Vector2.prototype.copyFrom = function (source) {
  597. this.x = source.x;
  598. this.y = source.y;
  599. return this;
  600. };
  601. /**
  602. * Sets the Vector2 coordinates with the passed floats.
  603. * Returns the updated Vector2.
  604. */
  605. Vector2.prototype.copyFromFloats = function (x, y) {
  606. this.x = x;
  607. this.y = y;
  608. return this;
  609. };
  610. /**
  611. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  612. */
  613. Vector2.prototype.add = function (otherVector) {
  614. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  615. };
  616. /**
  617. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  618. * Returns the Vector2.
  619. */
  620. Vector2.prototype.addToRef = function (otherVector, result) {
  621. result.x = this.x + otherVector.x;
  622. result.y = this.y + otherVector.y;
  623. return this;
  624. };
  625. /**
  626. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  627. * Returns the updated Vector2.
  628. */
  629. Vector2.prototype.addInPlace = function (otherVector) {
  630. this.x += otherVector.x;
  631. this.y += otherVector.y;
  632. return this;
  633. };
  634. /**
  635. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  636. */
  637. Vector2.prototype.addVector3 = function (otherVector) {
  638. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  639. };
  640. /**
  641. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  642. */
  643. Vector2.prototype.subtract = function (otherVector) {
  644. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  645. };
  646. /**
  647. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  648. * Returns the Vector2.
  649. */
  650. Vector2.prototype.subtractToRef = function (otherVector, result) {
  651. result.x = this.x - otherVector.x;
  652. result.y = this.y - otherVector.y;
  653. return this;
  654. };
  655. /**
  656. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  657. * Returns the updated Vector2.
  658. */
  659. Vector2.prototype.subtractInPlace = function (otherVector) {
  660. this.x -= otherVector.x;
  661. this.y -= otherVector.y;
  662. return this;
  663. };
  664. /**
  665. * Multiplies in place the current Vector2 coordinates by the passed ones.
  666. * Returns the updated Vector2.
  667. */
  668. Vector2.prototype.multiplyInPlace = function (otherVector) {
  669. this.x *= otherVector.x;
  670. this.y *= otherVector.y;
  671. return this;
  672. };
  673. /**
  674. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  675. */
  676. Vector2.prototype.multiply = function (otherVector) {
  677. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  678. };
  679. /**
  680. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  681. * Returns the Vector2.
  682. */
  683. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  684. result.x = this.x * otherVector.x;
  685. result.y = this.y * otherVector.y;
  686. return this;
  687. };
  688. /**
  689. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  690. */
  691. Vector2.prototype.multiplyByFloats = function (x, y) {
  692. return new Vector2(this.x * x, this.y * y);
  693. };
  694. /**
  695. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  696. */
  697. Vector2.prototype.divide = function (otherVector) {
  698. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  699. };
  700. /**
  701. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  702. * Returns the Vector2.
  703. */
  704. Vector2.prototype.divideToRef = function (otherVector, result) {
  705. result.x = this.x / otherVector.x;
  706. result.y = this.y / otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 with current Vector2 negated coordinates.
  711. */
  712. Vector2.prototype.negate = function () {
  713. return new Vector2(-this.x, -this.y);
  714. };
  715. /**
  716. * Multiply the Vector2 coordinates by scale.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.scaleInPlace = function (scale) {
  720. this.x *= scale;
  721. this.y *= scale;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  726. */
  727. Vector2.prototype.scale = function (scale) {
  728. return new Vector2(this.x * scale, this.y * scale);
  729. };
  730. /**
  731. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  732. */
  733. Vector2.prototype.equals = function (otherVector) {
  734. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  735. };
  736. /**
  737. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  738. */
  739. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  740. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  741. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  742. };
  743. // Properties
  744. /**
  745. * Returns the vector length (float).
  746. */
  747. Vector2.prototype.length = function () {
  748. return Math.sqrt(this.x * this.x + this.y * this.y);
  749. };
  750. /**
  751. * Returns the vector squared length (float);
  752. */
  753. Vector2.prototype.lengthSquared = function () {
  754. return (this.x * this.x + this.y * this.y);
  755. };
  756. // Methods
  757. /**
  758. * Normalize the vector.
  759. * Returns the updated Vector2.
  760. */
  761. Vector2.prototype.normalize = function () {
  762. var len = this.length();
  763. if (len === 0)
  764. return this;
  765. var num = 1.0 / len;
  766. this.x *= num;
  767. this.y *= num;
  768. return this;
  769. };
  770. /**
  771. * Returns a new Vector2 copied from the Vector2.
  772. */
  773. Vector2.prototype.clone = function () {
  774. return new Vector2(this.x, this.y);
  775. };
  776. // Statics
  777. /**
  778. * Returns a new Vector2(0, 0)
  779. */
  780. Vector2.Zero = function () {
  781. return new Vector2(0, 0);
  782. };
  783. /**
  784. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  785. */
  786. Vector2.FromArray = function (array, offset) {
  787. if (offset === void 0) { offset = 0; }
  788. return new Vector2(array[offset], array[offset + 1]);
  789. };
  790. /**
  791. * Sets "result" from the passed index element of the passed array or Float32Array.
  792. * Returns the Vector2.
  793. */
  794. Vector2.FromArrayToRef = function (array, offset, result) {
  795. result.x = array[offset];
  796. result.y = array[offset + 1];
  797. };
  798. /**
  799. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  800. */
  801. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  802. var squared = amount * amount;
  803. var cubed = amount * squared;
  804. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  805. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  806. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  807. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  808. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  809. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  810. return new Vector2(x, y);
  811. };
  812. /**
  813. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  814. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  815. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  816. */
  817. Vector2.Clamp = function (value, min, max) {
  818. var x = value.x;
  819. x = (x > max.x) ? max.x : x;
  820. x = (x < min.x) ? min.x : x;
  821. var y = value.y;
  822. y = (y > max.y) ? max.y : y;
  823. y = (y < min.y) ? min.y : y;
  824. return new Vector2(x, y);
  825. };
  826. /**
  827. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  828. */
  829. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  830. var squared = amount * amount;
  831. var cubed = amount * squared;
  832. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  833. var part2 = (-2.0 * cubed) + (3.0 * squared);
  834. var part3 = (cubed - (2.0 * squared)) + amount;
  835. var part4 = cubed - squared;
  836. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  837. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  838. return new Vector2(x, y);
  839. };
  840. /**
  841. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  842. */
  843. Vector2.Lerp = function (start, end, amount) {
  844. var x = start.x + ((end.x - start.x) * amount);
  845. var y = start.y + ((end.y - start.y) * amount);
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * Returns the dot product (float) of the vector "left" and the vector "right".
  850. */
  851. Vector2.Dot = function (left, right) {
  852. return left.x * right.x + left.y * right.y;
  853. };
  854. /**
  855. * Returns a new Vector2 equal to the normalized passed vector.
  856. */
  857. Vector2.Normalize = function (vector) {
  858. var newVector = vector.clone();
  859. newVector.normalize();
  860. return newVector;
  861. };
  862. /**
  863. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  864. */
  865. Vector2.Minimize = function (left, right) {
  866. var x = (left.x < right.x) ? left.x : right.x;
  867. var y = (left.y < right.y) ? left.y : right.y;
  868. return new Vector2(x, y);
  869. };
  870. /**
  871. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  872. */
  873. Vector2.Maximize = function (left, right) {
  874. var x = (left.x > right.x) ? left.x : right.x;
  875. var y = (left.y > right.y) ? left.y : right.y;
  876. return new Vector2(x, y);
  877. };
  878. /**
  879. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  880. */
  881. Vector2.Transform = function (vector, transformation) {
  882. var r = Vector2.Zero();
  883. Vector2.TransformToRef(vector, transformation, r);
  884. return r;
  885. };
  886. /**
  887. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  888. */
  889. Vector2.TransformToRef = function (vector, transformation, result) {
  890. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  891. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  892. result.x = x;
  893. result.y = y;
  894. };
  895. /**
  896. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  897. */
  898. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  899. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  900. var sign = a < 0 ? -1 : 1;
  901. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  902. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  903. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  904. };
  905. /**
  906. * Returns the distance (float) between the vectors "value1" and "value2".
  907. */
  908. Vector2.Distance = function (value1, value2) {
  909. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  910. };
  911. /**
  912. * Returns the squared distance (float) between the vectors "value1" and "value2".
  913. */
  914. Vector2.DistanceSquared = function (value1, value2) {
  915. var x = value1.x - value2.x;
  916. var y = value1.y - value2.y;
  917. return (x * x) + (y * y);
  918. };
  919. /**
  920. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  921. */
  922. Vector2.Center = function (value1, value2) {
  923. var center = value1.add(value2);
  924. center.scaleInPlace(0.5);
  925. return center;
  926. };
  927. /**
  928. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  929. */
  930. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  931. var l2 = Vector2.DistanceSquared(segA, segB);
  932. if (l2 === 0.0) {
  933. return Vector2.Distance(p, segA);
  934. }
  935. var v = segB.subtract(segA);
  936. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  937. var proj = segA.add(v.multiplyByFloats(t, t));
  938. return Vector2.Distance(p, proj);
  939. };
  940. return Vector2;
  941. }());
  942. BABYLON.Vector2 = Vector2;
  943. var Vector3 = (function () {
  944. /**
  945. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  946. * A Vector3 is the main object used in 3D geometry.
  947. * It can represent etiher the coordinates of a point the space, either a direction.
  948. */
  949. function Vector3(x, y, z) {
  950. this.x = x;
  951. this.y = y;
  952. this.z = z;
  953. }
  954. /**
  955. * Returns a string with the Vector3 coordinates.
  956. */
  957. Vector3.prototype.toString = function () {
  958. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  959. };
  960. /**
  961. * Returns the string "Vector3"
  962. */
  963. Vector3.prototype.getClassName = function () {
  964. return "Vector3";
  965. };
  966. /**
  967. * Returns the Vector hash code.
  968. */
  969. Vector3.prototype.getHashCode = function () {
  970. var hash = this.x || 0;
  971. hash = (hash * 397) ^ (this.y || 0);
  972. hash = (hash * 397) ^ (this.z || 0);
  973. return hash;
  974. };
  975. // Operators
  976. /**
  977. * Returns a new array with three elements : the coordinates the Vector3.
  978. */
  979. Vector3.prototype.asArray = function () {
  980. var result = [];
  981. this.toArray(result, 0);
  982. return result;
  983. };
  984. /**
  985. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  986. * Returns the Vector3.
  987. */
  988. Vector3.prototype.toArray = function (array, index) {
  989. if (index === void 0) { index = 0; }
  990. array[index] = this.x;
  991. array[index + 1] = this.y;
  992. array[index + 2] = this.z;
  993. return this;
  994. };
  995. /**
  996. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  997. */
  998. Vector3.prototype.toQuaternion = function () {
  999. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1000. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1001. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1002. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1003. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1004. var cosy = Math.cos(this.y * 0.5);
  1005. var siny = Math.sin(this.y * 0.5);
  1006. result.x = coszMinusx * siny;
  1007. result.y = -sinzMinusx * siny;
  1008. result.z = sinxPlusz * cosy;
  1009. result.w = cosxPlusz * cosy;
  1010. return result;
  1011. };
  1012. /**
  1013. * Adds the passed vector to the current Vector3.
  1014. * Returns the updated Vector3.
  1015. */
  1016. Vector3.prototype.addInPlace = function (otherVector) {
  1017. this.x += otherVector.x;
  1018. this.y += otherVector.y;
  1019. this.z += otherVector.z;
  1020. return this;
  1021. };
  1022. /**
  1023. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1024. */
  1025. Vector3.prototype.add = function (otherVector) {
  1026. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1027. };
  1028. /**
  1029. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1030. * Returns the current Vector3.
  1031. */
  1032. Vector3.prototype.addToRef = function (otherVector, result) {
  1033. result.x = this.x + otherVector.x;
  1034. result.y = this.y + otherVector.y;
  1035. result.z = this.z + otherVector.z;
  1036. return this;
  1037. };
  1038. /**
  1039. * Subtract the passed vector from the current Vector3.
  1040. * Returns the updated Vector3.
  1041. */
  1042. Vector3.prototype.subtractInPlace = function (otherVector) {
  1043. this.x -= otherVector.x;
  1044. this.y -= otherVector.y;
  1045. this.z -= otherVector.z;
  1046. return this;
  1047. };
  1048. /**
  1049. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1050. */
  1051. Vector3.prototype.subtract = function (otherVector) {
  1052. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1053. };
  1054. /**
  1055. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1056. * Returns the current Vector3.
  1057. */
  1058. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1059. result.x = this.x - otherVector.x;
  1060. result.y = this.y - otherVector.y;
  1061. result.z = this.z - otherVector.z;
  1062. return this;
  1063. };
  1064. /**
  1065. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1066. */
  1067. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1068. return new Vector3(this.x - x, this.y - y, this.z - z);
  1069. };
  1070. /**
  1071. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1072. * Returns the current Vector3.
  1073. */
  1074. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1075. result.x = this.x - x;
  1076. result.y = this.y - y;
  1077. result.z = this.z - z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1082. */
  1083. Vector3.prototype.negate = function () {
  1084. return new Vector3(-this.x, -this.y, -this.z);
  1085. };
  1086. /**
  1087. * Multiplies the Vector3 coordinates by the float "scale".
  1088. * Returns the updated Vector3.
  1089. */
  1090. Vector3.prototype.scaleInPlace = function (scale) {
  1091. this.x *= scale;
  1092. this.y *= scale;
  1093. this.z *= scale;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1098. */
  1099. Vector3.prototype.scale = function (scale) {
  1100. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1101. };
  1102. /**
  1103. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.scaleToRef = function (scale, result) {
  1107. result.x = this.x * scale;
  1108. result.y = this.y * scale;
  1109. result.z = this.z * scale;
  1110. return this;
  1111. };
  1112. /**
  1113. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1114. */
  1115. Vector3.prototype.equals = function (otherVector) {
  1116. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1117. };
  1118. /**
  1119. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1120. */
  1121. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1122. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1123. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1124. };
  1125. /**
  1126. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1127. */
  1128. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1129. return this.x === x && this.y === y && this.z === z;
  1130. };
  1131. /**
  1132. * Muliplies the current Vector3 coordinates by the passed ones.
  1133. * Returns the updated Vector3.
  1134. */
  1135. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1136. this.x *= otherVector.x;
  1137. this.y *= otherVector.y;
  1138. this.z *= otherVector.z;
  1139. return this;
  1140. };
  1141. /**
  1142. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1143. */
  1144. Vector3.prototype.multiply = function (otherVector) {
  1145. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1146. };
  1147. /**
  1148. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1149. * Returns the current Vector3.
  1150. */
  1151. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1152. result.x = this.x * otherVector.x;
  1153. result.y = this.y * otherVector.y;
  1154. result.z = this.z * otherVector.z;
  1155. return this;
  1156. };
  1157. /**
  1158. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1159. */
  1160. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1161. return new Vector3(this.x * x, this.y * y, this.z * z);
  1162. };
  1163. /**
  1164. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1165. */
  1166. Vector3.prototype.divide = function (otherVector) {
  1167. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1168. };
  1169. /**
  1170. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1171. * Returns the current Vector3.
  1172. */
  1173. Vector3.prototype.divideToRef = function (otherVector, result) {
  1174. result.x = this.x / otherVector.x;
  1175. result.y = this.y / otherVector.y;
  1176. result.z = this.z / otherVector.z;
  1177. return this;
  1178. };
  1179. /**
  1180. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1181. * Returns the updated Vector3.
  1182. */
  1183. Vector3.prototype.MinimizeInPlace = function (other) {
  1184. if (other.x < this.x)
  1185. this.x = other.x;
  1186. if (other.y < this.y)
  1187. this.y = other.y;
  1188. if (other.z < this.z)
  1189. this.z = other.z;
  1190. return this;
  1191. };
  1192. /**
  1193. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1194. * Returns the updated Vector3.
  1195. */
  1196. Vector3.prototype.MaximizeInPlace = function (other) {
  1197. if (other.x > this.x)
  1198. this.x = other.x;
  1199. if (other.y > this.y)
  1200. this.y = other.y;
  1201. if (other.z > this.z)
  1202. this.z = other.z;
  1203. return this;
  1204. };
  1205. // Properties
  1206. /**
  1207. * Returns the length of the Vector3 (float).
  1208. */
  1209. Vector3.prototype.length = function () {
  1210. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1211. };
  1212. /**
  1213. * Returns the squared length of the Vector3 (float).
  1214. */
  1215. Vector3.prototype.lengthSquared = function () {
  1216. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1217. };
  1218. // Methods
  1219. /**
  1220. * Normalize the current Vector3.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.normalize = function () {
  1224. var len = this.length();
  1225. if (len === 0 || len === 1.0)
  1226. return this;
  1227. var num = 1.0 / len;
  1228. this.x *= num;
  1229. this.y *= num;
  1230. this.z *= num;
  1231. return this;
  1232. };
  1233. /**
  1234. * Returns a new Vector3 copied from the current Vector3.
  1235. */
  1236. Vector3.prototype.clone = function () {
  1237. return new Vector3(this.x, this.y, this.z);
  1238. };
  1239. /**
  1240. * Copies the passed vector coordinates to the current Vector3 ones.
  1241. * Returns the updated Vector3.
  1242. */
  1243. Vector3.prototype.copyFrom = function (source) {
  1244. this.x = source.x;
  1245. this.y = source.y;
  1246. this.z = source.z;
  1247. return this;
  1248. };
  1249. /**
  1250. * Copies the passed floats to the current Vector3 coordinates.
  1251. * Returns the updated Vector3.
  1252. */
  1253. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1254. this.x = x;
  1255. this.y = y;
  1256. this.z = z;
  1257. return this;
  1258. };
  1259. // Statics
  1260. /**
  1261. *
  1262. */
  1263. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1264. var d0 = Vector3.Dot(vector0, axis) - size;
  1265. var d1 = Vector3.Dot(vector1, axis) - size;
  1266. var s = d0 / (d0 - d1);
  1267. return s;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1271. */
  1272. Vector3.FromArray = function (array, offset) {
  1273. if (!offset) {
  1274. offset = 0;
  1275. }
  1276. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1277. };
  1278. /**
  1279. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1280. */
  1281. Vector3.FromFloatArray = function (array, offset) {
  1282. if (!offset) {
  1283. offset = 0;
  1284. }
  1285. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1286. };
  1287. /**
  1288. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1289. */
  1290. Vector3.FromArrayToRef = function (array, offset, result) {
  1291. result.x = array[offset];
  1292. result.y = array[offset + 1];
  1293. result.z = array[offset + 2];
  1294. };
  1295. /**
  1296. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1297. */
  1298. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1299. result.x = array[offset];
  1300. result.y = array[offset + 1];
  1301. result.z = array[offset + 2];
  1302. };
  1303. /**
  1304. * Sets the passed vector "result" with the passed floats.
  1305. */
  1306. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1307. result.x = x;
  1308. result.y = y;
  1309. result.z = z;
  1310. };
  1311. /**
  1312. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1313. */
  1314. Vector3.Zero = function () {
  1315. return new Vector3(0.0, 0.0, 0.0);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1319. */
  1320. Vector3.Up = function () {
  1321. return new Vector3(0.0, 1.0, 0.0);
  1322. };
  1323. /**
  1324. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1325. */
  1326. Vector3.Forward = function () {
  1327. return new Vector3(0.0, 0.0, 1.0);
  1328. };
  1329. /**
  1330. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1331. */
  1332. Vector3.Right = function () {
  1333. return new Vector3(1.0, 0.0, 0.0);
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1337. */
  1338. Vector3.Left = function () {
  1339. return new Vector3(-1.0, 0.0, 0.0);
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1343. * This method computes tranformed coordinates only, not transformed direction vectors.
  1344. */
  1345. Vector3.TransformCoordinates = function (vector, transformation) {
  1346. var result = Vector3.Zero();
  1347. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1348. return result;
  1349. };
  1350. /**
  1351. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1352. * This method computes tranformed coordinates only, not transformed direction vectors.
  1353. */
  1354. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1355. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1356. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1357. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1358. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1359. result.x = x / w;
  1360. result.y = y / w;
  1361. result.z = z / w;
  1362. };
  1363. /**
  1364. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1365. * This method computes tranformed coordinates only, not transformed direction vectors.
  1366. */
  1367. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1368. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1369. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1370. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1371. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1372. result.x = rx / rw;
  1373. result.y = ry / rw;
  1374. result.z = rz / rw;
  1375. };
  1376. /**
  1377. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1378. * This methods computes transformed normalized direction vectors only.
  1379. */
  1380. Vector3.TransformNormal = function (vector, transformation) {
  1381. var result = Vector3.Zero();
  1382. Vector3.TransformNormalToRef(vector, transformation, result);
  1383. return result;
  1384. };
  1385. /**
  1386. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1387. * This methods computes transformed normalized direction vectors only.
  1388. */
  1389. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1390. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1391. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1392. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1393. result.x = x;
  1394. result.y = y;
  1395. result.z = z;
  1396. };
  1397. /**
  1398. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1399. * This methods computes transformed normalized direction vectors only.
  1400. */
  1401. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1402. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1403. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1404. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1405. };
  1406. /**
  1407. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1408. */
  1409. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1410. var squared = amount * amount;
  1411. var cubed = amount * squared;
  1412. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1413. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1414. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1415. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1416. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1417. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1418. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1419. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1420. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1421. return new Vector3(x, y, z);
  1422. };
  1423. /**
  1424. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1425. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1426. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1427. */
  1428. Vector3.Clamp = function (value, min, max) {
  1429. var x = value.x;
  1430. x = (x > max.x) ? max.x : x;
  1431. x = (x < min.x) ? min.x : x;
  1432. var y = value.y;
  1433. y = (y > max.y) ? max.y : y;
  1434. y = (y < min.y) ? min.y : y;
  1435. var z = value.z;
  1436. z = (z > max.z) ? max.z : z;
  1437. z = (z < min.z) ? min.z : z;
  1438. return new Vector3(x, y, z);
  1439. };
  1440. /**
  1441. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1442. */
  1443. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1444. var squared = amount * amount;
  1445. var cubed = amount * squared;
  1446. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1447. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1448. var part3 = (cubed - (2.0 * squared)) + amount;
  1449. var part4 = cubed - squared;
  1450. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1451. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1452. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1453. return new Vector3(x, y, z);
  1454. };
  1455. /**
  1456. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1457. */
  1458. Vector3.Lerp = function (start, end, amount) {
  1459. var result = new Vector3(0, 0, 0);
  1460. Vector3.LerpToRef(start, end, amount, result);
  1461. return result;
  1462. };
  1463. /**
  1464. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1465. */
  1466. Vector3.LerpToRef = function (start, end, amount, result) {
  1467. result.x = start.x + ((end.x - start.x) * amount);
  1468. result.y = start.y + ((end.y - start.y) * amount);
  1469. result.z = start.z + ((end.z - start.z) * amount);
  1470. };
  1471. /**
  1472. * Returns the dot product (float) between the vectors "left" and "right".
  1473. */
  1474. Vector3.Dot = function (left, right) {
  1475. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1476. };
  1477. /**
  1478. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1479. * The cross product is then orthogonal to both "left" and "right".
  1480. */
  1481. Vector3.Cross = function (left, right) {
  1482. var result = Vector3.Zero();
  1483. Vector3.CrossToRef(left, right, result);
  1484. return result;
  1485. };
  1486. /**
  1487. * Sets the passed vector "result" with the cross product of "left" and "right".
  1488. * The cross product is then orthogonal to both "left" and "right".
  1489. */
  1490. Vector3.CrossToRef = function (left, right, result) {
  1491. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1492. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1493. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1494. result.copyFrom(MathTmp.Vector3[0]);
  1495. };
  1496. /**
  1497. * Returns a new Vector3 as the normalization of the passed vector.
  1498. */
  1499. Vector3.Normalize = function (vector) {
  1500. var result = Vector3.Zero();
  1501. Vector3.NormalizeToRef(vector, result);
  1502. return result;
  1503. };
  1504. /**
  1505. * Sets the passed vector "result" with the normalization of the passed first vector.
  1506. */
  1507. Vector3.NormalizeToRef = function (vector, result) {
  1508. result.copyFrom(vector);
  1509. result.normalize();
  1510. };
  1511. Vector3.Project = function (vector, world, transform, viewport) {
  1512. var cw = viewport.width;
  1513. var ch = viewport.height;
  1514. var cx = viewport.x;
  1515. var cy = viewport.y;
  1516. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1517. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1518. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1519. world.multiplyToRef(transform, matrix);
  1520. matrix.multiplyToRef(viewportMatrix, matrix);
  1521. return Vector3.TransformCoordinates(vector, matrix);
  1522. };
  1523. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1524. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1525. world.multiplyToRef(transform, matrix);
  1526. matrix.invert();
  1527. source.x = source.x / viewportWidth * 2 - 1;
  1528. source.y = -(source.y / viewportHeight * 2 - 1);
  1529. var vector = Vector3.TransformCoordinates(source, matrix);
  1530. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1531. if (MathTools.WithinEpsilon(num, 1.0)) {
  1532. vector = vector.scale(1.0 / num);
  1533. }
  1534. return vector;
  1535. };
  1536. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1537. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1538. world.multiplyToRef(view, matrix);
  1539. matrix.multiplyToRef(projection, matrix);
  1540. matrix.invert();
  1541. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1542. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1543. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1544. if (MathTools.WithinEpsilon(num, 1.0)) {
  1545. vector = vector.scale(1.0 / num);
  1546. }
  1547. return vector;
  1548. };
  1549. Vector3.Minimize = function (left, right) {
  1550. var min = left.clone();
  1551. min.MinimizeInPlace(right);
  1552. return min;
  1553. };
  1554. Vector3.Maximize = function (left, right) {
  1555. var max = left.clone();
  1556. max.MaximizeInPlace(right);
  1557. return max;
  1558. };
  1559. /**
  1560. * Returns the distance (float) between the vectors "value1" and "value2".
  1561. */
  1562. Vector3.Distance = function (value1, value2) {
  1563. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1564. };
  1565. /**
  1566. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1567. */
  1568. Vector3.DistanceSquared = function (value1, value2) {
  1569. var x = value1.x - value2.x;
  1570. var y = value1.y - value2.y;
  1571. var z = value1.z - value2.z;
  1572. return (x * x) + (y * y) + (z * z);
  1573. };
  1574. /**
  1575. * Returns a new Vector3 located at the center between "value1" and "value2".
  1576. */
  1577. Vector3.Center = function (value1, value2) {
  1578. var center = value1.add(value2);
  1579. center.scaleInPlace(0.5);
  1580. return center;
  1581. };
  1582. /**
  1583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1585. * to something in order to rotate it from its local system to the given target system.
  1586. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1587. * Returns a new Vector3.
  1588. */
  1589. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1590. var rotation = Vector3.Zero();
  1591. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1592. return rotation;
  1593. };
  1594. /**
  1595. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1596. */
  1597. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1598. var quat = MathTmp.Quaternion[0];
  1599. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1600. quat.toEulerAnglesToRef(ref);
  1601. };
  1602. return Vector3;
  1603. }());
  1604. BABYLON.Vector3 = Vector3;
  1605. //Vector4 class created for EulerAngle class conversion to Quaternion
  1606. var Vector4 = (function () {
  1607. /**
  1608. * Creates a Vector4 object from the passed floats.
  1609. */
  1610. function Vector4(x, y, z, w) {
  1611. this.x = x;
  1612. this.y = y;
  1613. this.z = z;
  1614. this.w = w;
  1615. }
  1616. /**
  1617. * Returns the string with the Vector4 coordinates.
  1618. */
  1619. Vector4.prototype.toString = function () {
  1620. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1621. };
  1622. /**
  1623. * Returns the string "Vector4".
  1624. */
  1625. Vector4.prototype.getClassName = function () {
  1626. return "Vector4";
  1627. };
  1628. /**
  1629. * Returns the Vector4 hash code.
  1630. */
  1631. Vector4.prototype.getHashCode = function () {
  1632. var hash = this.x || 0;
  1633. hash = (hash * 397) ^ (this.y || 0);
  1634. hash = (hash * 397) ^ (this.z || 0);
  1635. hash = (hash * 397) ^ (this.w || 0);
  1636. return hash;
  1637. };
  1638. // Operators
  1639. /**
  1640. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1641. */
  1642. Vector4.prototype.asArray = function () {
  1643. var result = [];
  1644. this.toArray(result, 0);
  1645. return result;
  1646. };
  1647. /**
  1648. * Populates the passed array from the passed index with the Vector4 coordinates.
  1649. * Returns the Vector4.
  1650. */
  1651. Vector4.prototype.toArray = function (array, index) {
  1652. if (index === undefined) {
  1653. index = 0;
  1654. }
  1655. array[index] = this.x;
  1656. array[index + 1] = this.y;
  1657. array[index + 2] = this.z;
  1658. array[index + 3] = this.w;
  1659. return this;
  1660. };
  1661. /**
  1662. * Adds the passed vector to the current Vector4.
  1663. * Returns the updated Vector4.
  1664. */
  1665. Vector4.prototype.addInPlace = function (otherVector) {
  1666. this.x += otherVector.x;
  1667. this.y += otherVector.y;
  1668. this.z += otherVector.z;
  1669. this.w += otherVector.w;
  1670. return this;
  1671. };
  1672. /**
  1673. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1674. */
  1675. Vector4.prototype.add = function (otherVector) {
  1676. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1677. };
  1678. /**
  1679. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1680. * Returns the current Vector4.
  1681. */
  1682. Vector4.prototype.addToRef = function (otherVector, result) {
  1683. result.x = this.x + otherVector.x;
  1684. result.y = this.y + otherVector.y;
  1685. result.z = this.z + otherVector.z;
  1686. result.w = this.w + otherVector.w;
  1687. return this;
  1688. };
  1689. /**
  1690. * Subtract in place the passed vector from the current Vector4.
  1691. * Returns the updated Vector4.
  1692. */
  1693. Vector4.prototype.subtractInPlace = function (otherVector) {
  1694. this.x -= otherVector.x;
  1695. this.y -= otherVector.y;
  1696. this.z -= otherVector.z;
  1697. this.w -= otherVector.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1702. */
  1703. Vector4.prototype.subtract = function (otherVector) {
  1704. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1705. };
  1706. /**
  1707. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1708. * Returns the current Vector4.
  1709. */
  1710. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1711. result.x = this.x - otherVector.x;
  1712. result.y = this.y - otherVector.y;
  1713. result.z = this.z - otherVector.z;
  1714. result.w = this.w - otherVector.w;
  1715. return this;
  1716. };
  1717. /**
  1718. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1719. */
  1720. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1721. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1722. };
  1723. /**
  1724. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1725. * Returns the current Vector4.
  1726. */
  1727. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1728. result.x = this.x - x;
  1729. result.y = this.y - y;
  1730. result.z = this.z - z;
  1731. result.w = this.w - w;
  1732. return this;
  1733. };
  1734. /**
  1735. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1736. */
  1737. Vector4.prototype.negate = function () {
  1738. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1739. };
  1740. /**
  1741. * Multiplies the current Vector4 coordinates by scale (float).
  1742. * Returns the updated Vector4.
  1743. */
  1744. Vector4.prototype.scaleInPlace = function (scale) {
  1745. this.x *= scale;
  1746. this.y *= scale;
  1747. this.z *= scale;
  1748. this.w *= scale;
  1749. return this;
  1750. };
  1751. /**
  1752. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1753. */
  1754. Vector4.prototype.scale = function (scale) {
  1755. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1756. };
  1757. /**
  1758. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1759. * Returns the current Vector4.
  1760. */
  1761. Vector4.prototype.scaleToRef = function (scale, result) {
  1762. result.x = this.x * scale;
  1763. result.y = this.y * scale;
  1764. result.z = this.z * scale;
  1765. result.w = this.w * scale;
  1766. return this;
  1767. };
  1768. /**
  1769. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1770. */
  1771. Vector4.prototype.equals = function (otherVector) {
  1772. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1773. };
  1774. /**
  1775. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1776. */
  1777. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1779. return otherVector
  1780. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1781. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1782. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1783. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1784. };
  1785. /**
  1786. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1787. */
  1788. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1789. return this.x === x && this.y === y && this.z === z && this.w === w;
  1790. };
  1791. /**
  1792. * Multiplies in place the current Vector4 by the passed one.
  1793. * Returns the updated Vector4.
  1794. */
  1795. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1796. this.x *= otherVector.x;
  1797. this.y *= otherVector.y;
  1798. this.z *= otherVector.z;
  1799. this.w *= otherVector.w;
  1800. return this;
  1801. };
  1802. /**
  1803. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1804. */
  1805. Vector4.prototype.multiply = function (otherVector) {
  1806. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1807. };
  1808. /**
  1809. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1810. * Returns the current Vector4.
  1811. */
  1812. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1813. result.x = this.x * otherVector.x;
  1814. result.y = this.y * otherVector.y;
  1815. result.z = this.z * otherVector.z;
  1816. result.w = this.w * otherVector.w;
  1817. return this;
  1818. };
  1819. /**
  1820. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1821. */
  1822. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1823. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1824. };
  1825. /**
  1826. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1827. */
  1828. Vector4.prototype.divide = function (otherVector) {
  1829. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1830. };
  1831. /**
  1832. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1833. * Returns the current Vector4.
  1834. */
  1835. Vector4.prototype.divideToRef = function (otherVector, result) {
  1836. result.x = this.x / otherVector.x;
  1837. result.y = this.y / otherVector.y;
  1838. result.z = this.z / otherVector.z;
  1839. result.w = this.w / otherVector.w;
  1840. return this;
  1841. };
  1842. /**
  1843. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1844. */
  1845. Vector4.prototype.MinimizeInPlace = function (other) {
  1846. if (other.x < this.x)
  1847. this.x = other.x;
  1848. if (other.y < this.y)
  1849. this.y = other.y;
  1850. if (other.z < this.z)
  1851. this.z = other.z;
  1852. if (other.w < this.w)
  1853. this.w = other.w;
  1854. return this;
  1855. };
  1856. /**
  1857. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1858. */
  1859. Vector4.prototype.MaximizeInPlace = function (other) {
  1860. if (other.x > this.x)
  1861. this.x = other.x;
  1862. if (other.y > this.y)
  1863. this.y = other.y;
  1864. if (other.z > this.z)
  1865. this.z = other.z;
  1866. if (other.w > this.w)
  1867. this.w = other.w;
  1868. return this;
  1869. };
  1870. // Properties
  1871. /**
  1872. * Returns the Vector4 length (float).
  1873. */
  1874. Vector4.prototype.length = function () {
  1875. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1876. };
  1877. /**
  1878. * Returns the Vector4 squared length (float).
  1879. */
  1880. Vector4.prototype.lengthSquared = function () {
  1881. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1882. };
  1883. // Methods
  1884. /**
  1885. * Normalizes in place the Vector4.
  1886. * Returns the updated Vector4.
  1887. */
  1888. Vector4.prototype.normalize = function () {
  1889. var len = this.length();
  1890. if (len === 0)
  1891. return this;
  1892. var num = 1.0 / len;
  1893. this.x *= num;
  1894. this.y *= num;
  1895. this.z *= num;
  1896. this.w *= num;
  1897. return this;
  1898. };
  1899. /**
  1900. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1901. */
  1902. Vector4.prototype.toVector3 = function () {
  1903. return new Vector3(this.x, this.y, this.z);
  1904. };
  1905. /**
  1906. * Returns a new Vector4 copied from the current one.
  1907. */
  1908. Vector4.prototype.clone = function () {
  1909. return new Vector4(this.x, this.y, this.z, this.w);
  1910. };
  1911. /**
  1912. * Updates the current Vector4 with the passed one coordinates.
  1913. * Returns the updated Vector4.
  1914. */
  1915. Vector4.prototype.copyFrom = function (source) {
  1916. this.x = source.x;
  1917. this.y = source.y;
  1918. this.z = source.z;
  1919. this.w = source.w;
  1920. return this;
  1921. };
  1922. /**
  1923. * Updates the current Vector4 coordinates with the passed floats.
  1924. * Returns the updated Vector4.
  1925. */
  1926. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1927. this.x = x;
  1928. this.y = y;
  1929. this.z = z;
  1930. this.w = w;
  1931. return this;
  1932. };
  1933. // Statics
  1934. /**
  1935. * Returns a new Vector4 set from the starting index of the passed array.
  1936. */
  1937. Vector4.FromArray = function (array, offset) {
  1938. if (!offset) {
  1939. offset = 0;
  1940. }
  1941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1942. };
  1943. /**
  1944. * Updates the passed vector "result" from the starting index of the passed array.
  1945. */
  1946. Vector4.FromArrayToRef = function (array, offset, result) {
  1947. result.x = array[offset];
  1948. result.y = array[offset + 1];
  1949. result.z = array[offset + 2];
  1950. result.w = array[offset + 3];
  1951. };
  1952. /**
  1953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  1954. */
  1955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1956. result.x = array[offset];
  1957. result.y = array[offset + 1];
  1958. result.z = array[offset + 2];
  1959. result.w = array[offset + 3];
  1960. };
  1961. /**
  1962. * Updates the passed vector "result" coordinates from the passed floats.
  1963. */
  1964. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1965. result.x = x;
  1966. result.y = y;
  1967. result.z = z;
  1968. result.w = w;
  1969. };
  1970. /**
  1971. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  1972. */
  1973. Vector4.Zero = function () {
  1974. return new Vector4(0.0, 0.0, 0.0, 0.0);
  1975. };
  1976. /**
  1977. * Returns a new normalized Vector4 from the passed one.
  1978. */
  1979. Vector4.Normalize = function (vector) {
  1980. var result = Vector4.Zero();
  1981. Vector4.NormalizeToRef(vector, result);
  1982. return result;
  1983. };
  1984. /**
  1985. * Updates the passed vector "result" from the normalization of the passed one.
  1986. */
  1987. Vector4.NormalizeToRef = function (vector, result) {
  1988. result.copyFrom(vector);
  1989. result.normalize();
  1990. };
  1991. Vector4.Minimize = function (left, right) {
  1992. var min = left.clone();
  1993. min.MinimizeInPlace(right);
  1994. return min;
  1995. };
  1996. Vector4.Maximize = function (left, right) {
  1997. var max = left.clone();
  1998. max.MaximizeInPlace(right);
  1999. return max;
  2000. };
  2001. /**
  2002. * Returns the distance (float) between the vectors "value1" and "value2".
  2003. */
  2004. Vector4.Distance = function (value1, value2) {
  2005. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2006. };
  2007. Vector4.DistanceSquared = function (value1, value2) {
  2008. var x = value1.x - value2.x;
  2009. var y = value1.y - value2.y;
  2010. var z = value1.z - value2.z;
  2011. var w = value1.w - value2.w;
  2012. return (x * x) + (y * y) + (z * z) + (w * w);
  2013. };
  2014. /**
  2015. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2016. */
  2017. Vector4.Center = function (value1, value2) {
  2018. var center = value1.add(value2);
  2019. center.scaleInPlace(0.5);
  2020. return center;
  2021. };
  2022. return Vector4;
  2023. }());
  2024. BABYLON.Vector4 = Vector4;
  2025. var Size = (function () {
  2026. /**
  2027. * Creates a Size object from the passed width and height (floats).
  2028. */
  2029. function Size(width, height) {
  2030. this.width = width;
  2031. this.height = height;
  2032. }
  2033. // Returns a string with the Size width and height.
  2034. Size.prototype.toString = function () {
  2035. return "{W: " + this.width + ", H: " + this.height + "}";
  2036. };
  2037. /**
  2038. * Returns the string "Size"
  2039. */
  2040. Size.prototype.getClassName = function () {
  2041. return "Size";
  2042. };
  2043. /**
  2044. * Returns the Size hash code.
  2045. */
  2046. Size.prototype.getHashCode = function () {
  2047. var hash = this.width || 0;
  2048. hash = (hash * 397) ^ (this.height || 0);
  2049. return hash;
  2050. };
  2051. /**
  2052. * Updates the current size from the passed one.
  2053. * Returns the updated Size.
  2054. */
  2055. Size.prototype.copyFrom = function (src) {
  2056. this.width = src.width;
  2057. this.height = src.height;
  2058. };
  2059. /**
  2060. * Updates in place the current Size from the passed floats.
  2061. * Returns the updated Size.
  2062. */
  2063. Size.prototype.copyFromFloats = function (width, height) {
  2064. this.width = width;
  2065. this.height = height;
  2066. return this;
  2067. };
  2068. /**
  2069. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2070. */
  2071. Size.prototype.multiplyByFloats = function (w, h) {
  2072. return new Size(this.width * w, this.height * h);
  2073. };
  2074. /**
  2075. * Returns a new Size copied from the passed one.
  2076. */
  2077. Size.prototype.clone = function () {
  2078. return new Size(this.width, this.height);
  2079. };
  2080. /**
  2081. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2082. */
  2083. Size.prototype.equals = function (other) {
  2084. if (!other) {
  2085. return false;
  2086. }
  2087. return (this.width === other.width) && (this.height === other.height);
  2088. };
  2089. Object.defineProperty(Size.prototype, "surface", {
  2090. /**
  2091. * Returns the surface of the Size : width * height (float).
  2092. */
  2093. get: function () {
  2094. return this.width * this.height;
  2095. },
  2096. enumerable: true,
  2097. configurable: true
  2098. });
  2099. /**
  2100. * Returns a new Size set to (0.0, 0.0)
  2101. */
  2102. Size.Zero = function () {
  2103. return new Size(0.0, 0.0);
  2104. };
  2105. /**
  2106. * Returns a new Size set as the addition result of the current Size and the passed one.
  2107. */
  2108. Size.prototype.add = function (otherSize) {
  2109. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2110. return r;
  2111. };
  2112. /**
  2113. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2114. */
  2115. Size.prototype.subtract = function (otherSize) {
  2116. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2117. return r;
  2118. };
  2119. /**
  2120. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2121. */
  2122. Size.Lerp = function (start, end, amount) {
  2123. var w = start.width + ((end.width - start.width) * amount);
  2124. var h = start.height + ((end.height - start.height) * amount);
  2125. return new Size(w, h);
  2126. };
  2127. return Size;
  2128. }());
  2129. BABYLON.Size = Size;
  2130. var Quaternion = (function () {
  2131. /**
  2132. * Creates a new Quaternion from the passed floats.
  2133. */
  2134. function Quaternion(x, y, z, w) {
  2135. if (x === void 0) { x = 0.0; }
  2136. if (y === void 0) { y = 0.0; }
  2137. if (z === void 0) { z = 0.0; }
  2138. if (w === void 0) { w = 1.0; }
  2139. this.x = x;
  2140. this.y = y;
  2141. this.z = z;
  2142. this.w = w;
  2143. }
  2144. /**
  2145. * Returns a string with the Quaternion coordinates.
  2146. */
  2147. Quaternion.prototype.toString = function () {
  2148. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2149. };
  2150. /**
  2151. * Returns the string "Quaternion".
  2152. */
  2153. Quaternion.prototype.getClassName = function () {
  2154. return "Quaternion";
  2155. };
  2156. /**
  2157. * Returns the Quaternion hash code.
  2158. */
  2159. Quaternion.prototype.getHashCode = function () {
  2160. var hash = this.x || 0;
  2161. hash = (hash * 397) ^ (this.y || 0);
  2162. hash = (hash * 397) ^ (this.z || 0);
  2163. hash = (hash * 397) ^ (this.w || 0);
  2164. return hash;
  2165. };
  2166. /**
  2167. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2168. */
  2169. Quaternion.prototype.asArray = function () {
  2170. return [this.x, this.y, this.z, this.w];
  2171. };
  2172. /**
  2173. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2174. */
  2175. Quaternion.prototype.equals = function (otherQuaternion) {
  2176. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2177. };
  2178. /**
  2179. * Returns a new Quaternion copied from the current one.
  2180. */
  2181. Quaternion.prototype.clone = function () {
  2182. return new Quaternion(this.x, this.y, this.z, this.w);
  2183. };
  2184. /**
  2185. * Updates the current Quaternion from the passed one coordinates.
  2186. * Returns the updated Quaterion.
  2187. */
  2188. Quaternion.prototype.copyFrom = function (other) {
  2189. this.x = other.x;
  2190. this.y = other.y;
  2191. this.z = other.z;
  2192. this.w = other.w;
  2193. return this;
  2194. };
  2195. /**
  2196. * Updates the current Quaternion from the passed float coordinates.
  2197. * Returns the updated Quaterion.
  2198. */
  2199. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2200. this.x = x;
  2201. this.y = y;
  2202. this.z = z;
  2203. this.w = w;
  2204. return this;
  2205. };
  2206. /**
  2207. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2208. */
  2209. Quaternion.prototype.add = function (other) {
  2210. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2211. };
  2212. /**
  2213. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2214. */
  2215. Quaternion.prototype.subtract = function (other) {
  2216. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2217. };
  2218. /**
  2219. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2220. */
  2221. Quaternion.prototype.scale = function (value) {
  2222. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2223. };
  2224. /**
  2225. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2226. */
  2227. Quaternion.prototype.multiply = function (q1) {
  2228. var result = new Quaternion(0, 0, 0, 1.0);
  2229. this.multiplyToRef(q1, result);
  2230. return result;
  2231. };
  2232. /**
  2233. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2234. * Returns the current Quaternion.
  2235. */
  2236. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2237. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2238. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2239. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2240. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2241. result.copyFromFloats(x, y, z, w);
  2242. return this;
  2243. };
  2244. /**
  2245. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2246. * Returns the updated Quaternion.
  2247. */
  2248. Quaternion.prototype.multiplyInPlace = function (q1) {
  2249. this.multiplyToRef(q1, this);
  2250. return this;
  2251. };
  2252. /**
  2253. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2254. * Returns the current Quaternion.
  2255. */
  2256. Quaternion.prototype.conjugateToRef = function (ref) {
  2257. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2258. return this;
  2259. };
  2260. /**
  2261. * Conjugates in place the current Quaternion.
  2262. * Returns the updated Quaternion.
  2263. */
  2264. Quaternion.prototype.conjugateInPlace = function () {
  2265. this.x *= -1;
  2266. this.y *= -1;
  2267. this.z *= -1;
  2268. return this;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2272. */
  2273. Quaternion.prototype.conjugate = function () {
  2274. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2275. return result;
  2276. };
  2277. /**
  2278. * Returns the Quaternion length (float).
  2279. */
  2280. Quaternion.prototype.length = function () {
  2281. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2282. };
  2283. /**
  2284. * Normalize in place the current Quaternion.
  2285. * Returns the updated Quaternion.
  2286. */
  2287. Quaternion.prototype.normalize = function () {
  2288. var length = 1.0 / this.length();
  2289. this.x *= length;
  2290. this.y *= length;
  2291. this.z *= length;
  2292. this.w *= length;
  2293. return this;
  2294. };
  2295. /**
  2296. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2297. */
  2298. Quaternion.prototype.toEulerAngles = function (order) {
  2299. if (order === void 0) { order = "YZX"; }
  2300. var result = Vector3.Zero();
  2301. this.toEulerAnglesToRef(result, order);
  2302. return result;
  2303. };
  2304. /**
  2305. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2306. * Returns the current Quaternion.
  2307. */
  2308. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2309. if (order === void 0) { order = "YZX"; }
  2310. var qz = this.z;
  2311. var qx = this.x;
  2312. var qy = this.y;
  2313. var qw = this.w;
  2314. var sqw = qw * qw;
  2315. var sqz = qz * qz;
  2316. var sqx = qx * qx;
  2317. var sqy = qy * qy;
  2318. var zAxisY = qy * qz - qx * qw;
  2319. var limit = .4999999;
  2320. if (zAxisY < -limit) {
  2321. result.y = 2 * Math.atan2(qy, qw);
  2322. result.x = Math.PI / 2;
  2323. result.z = 0;
  2324. }
  2325. else if (zAxisY > limit) {
  2326. result.y = 2 * Math.atan2(qy, qw);
  2327. result.x = -Math.PI / 2;
  2328. result.z = 0;
  2329. }
  2330. else {
  2331. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2332. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2333. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2334. }
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates the passed rotation matrix with the current Quaternion values.
  2339. * Returns the current Quaternion.
  2340. */
  2341. Quaternion.prototype.toRotationMatrix = function (result) {
  2342. var xx = this.x * this.x;
  2343. var yy = this.y * this.y;
  2344. var zz = this.z * this.z;
  2345. var xy = this.x * this.y;
  2346. var zw = this.z * this.w;
  2347. var zx = this.z * this.x;
  2348. var yw = this.y * this.w;
  2349. var yz = this.y * this.z;
  2350. var xw = this.x * this.w;
  2351. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2352. result.m[1] = 2.0 * (xy + zw);
  2353. result.m[2] = 2.0 * (zx - yw);
  2354. result.m[3] = 0;
  2355. result.m[4] = 2.0 * (xy - zw);
  2356. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2357. result.m[6] = 2.0 * (yz + xw);
  2358. result.m[7] = 0;
  2359. result.m[8] = 2.0 * (zx + yw);
  2360. result.m[9] = 2.0 * (yz - xw);
  2361. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2362. result.m[11] = 0;
  2363. result.m[12] = 0;
  2364. result.m[13] = 0;
  2365. result.m[14] = 0;
  2366. result.m[15] = 1.0;
  2367. return this;
  2368. };
  2369. /**
  2370. * Updates the current Quaternion from the passed rotation matrix values.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2374. Quaternion.FromRotationMatrixToRef(matrix, this);
  2375. return this;
  2376. };
  2377. // Statics
  2378. /**
  2379. * Returns a new Quaternion set from the passed rotation matrix values.
  2380. */
  2381. Quaternion.FromRotationMatrix = function (matrix) {
  2382. var result = new Quaternion();
  2383. Quaternion.FromRotationMatrixToRef(matrix, result);
  2384. return result;
  2385. };
  2386. /**
  2387. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2388. */
  2389. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2390. var data = matrix.m;
  2391. var m11 = data[0], m12 = data[4], m13 = data[8];
  2392. var m21 = data[1], m22 = data[5], m23 = data[9];
  2393. var m31 = data[2], m32 = data[6], m33 = data[10];
  2394. var trace = m11 + m22 + m33;
  2395. var s;
  2396. if (trace > 0) {
  2397. s = 0.5 / Math.sqrt(trace + 1.0);
  2398. result.w = 0.25 / s;
  2399. result.x = (m32 - m23) * s;
  2400. result.y = (m13 - m31) * s;
  2401. result.z = (m21 - m12) * s;
  2402. }
  2403. else if (m11 > m22 && m11 > m33) {
  2404. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2405. result.w = (m32 - m23) / s;
  2406. result.x = 0.25 * s;
  2407. result.y = (m12 + m21) / s;
  2408. result.z = (m13 + m31) / s;
  2409. }
  2410. else if (m22 > m33) {
  2411. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2412. result.w = (m13 - m31) / s;
  2413. result.x = (m12 + m21) / s;
  2414. result.y = 0.25 * s;
  2415. result.z = (m23 + m32) / s;
  2416. }
  2417. else {
  2418. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2419. result.w = (m21 - m12) / s;
  2420. result.x = (m13 + m31) / s;
  2421. result.y = (m23 + m32) / s;
  2422. result.z = 0.25 * s;
  2423. }
  2424. };
  2425. /**
  2426. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2427. */
  2428. Quaternion.Zero = function () {
  2429. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2430. };
  2431. /**
  2432. * Returns a new Quaternion as the inverted current Quaternion.
  2433. */
  2434. Quaternion.Inverse = function (q) {
  2435. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2436. };
  2437. /**
  2438. * Returns the identity Quaternion.
  2439. */
  2440. Quaternion.Identity = function () {
  2441. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2442. };
  2443. /**
  2444. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2445. */
  2446. Quaternion.RotationAxis = function (axis, angle) {
  2447. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2448. };
  2449. /**
  2450. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2451. */
  2452. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2453. var sin = Math.sin(angle / 2);
  2454. axis.normalize();
  2455. result.w = Math.cos(angle / 2);
  2456. result.x = axis.x * sin;
  2457. result.y = axis.y * sin;
  2458. result.z = axis.z * sin;
  2459. return result;
  2460. };
  2461. /**
  2462. * Retuns a new Quaternion set from the starting index of the passed array.
  2463. */
  2464. Quaternion.FromArray = function (array, offset) {
  2465. if (!offset) {
  2466. offset = 0;
  2467. }
  2468. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2469. };
  2470. /**
  2471. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2472. */
  2473. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2474. var q = new Quaternion();
  2475. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2476. return q;
  2477. };
  2478. /**
  2479. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2480. */
  2481. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2482. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2483. var halfRoll = roll * 0.5;
  2484. var halfPitch = pitch * 0.5;
  2485. var halfYaw = yaw * 0.5;
  2486. var sinRoll = Math.sin(halfRoll);
  2487. var cosRoll = Math.cos(halfRoll);
  2488. var sinPitch = Math.sin(halfPitch);
  2489. var cosPitch = Math.cos(halfPitch);
  2490. var sinYaw = Math.sin(halfYaw);
  2491. var cosYaw = Math.cos(halfYaw);
  2492. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2493. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2494. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2495. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2496. };
  2497. /**
  2498. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2499. */
  2500. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2501. var result = new Quaternion();
  2502. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2503. return result;
  2504. };
  2505. /**
  2506. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2507. */
  2508. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2509. // Produces a quaternion from Euler angles in the z-x-z orientation
  2510. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2511. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2512. var halfBeta = beta * 0.5;
  2513. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2514. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2515. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2516. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2517. };
  2518. /**
  2519. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2520. * cf to Vector3.RotationFromAxis() documentation.
  2521. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2522. */
  2523. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2524. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2525. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2526. return quat;
  2527. };
  2528. /**
  2529. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2530. * cf to Vector3.RotationFromAxis() documentation.
  2531. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2532. */
  2533. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2534. var rotMat = MathTmp.Matrix[0];
  2535. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2536. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2537. };
  2538. Quaternion.Slerp = function (left, right, amount) {
  2539. var result = Quaternion.Identity();
  2540. Quaternion.SlerpToRef(left, right, amount, result);
  2541. return result;
  2542. };
  2543. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2544. var num2;
  2545. var num3;
  2546. var num = amount;
  2547. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2548. var flag = false;
  2549. if (num4 < 0) {
  2550. flag = true;
  2551. num4 = -num4;
  2552. }
  2553. if (num4 > 0.999999) {
  2554. num3 = 1 - num;
  2555. num2 = flag ? -num : num;
  2556. }
  2557. else {
  2558. var num5 = Math.acos(num4);
  2559. var num6 = (1.0 / Math.sin(num5));
  2560. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2561. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2562. }
  2563. result.x = (num3 * left.x) + (num2 * right.x);
  2564. result.y = (num3 * left.y) + (num2 * right.y);
  2565. result.z = (num3 * left.z) + (num2 * right.z);
  2566. result.w = (num3 * left.w) + (num2 * right.w);
  2567. };
  2568. return Quaternion;
  2569. }());
  2570. BABYLON.Quaternion = Quaternion;
  2571. var Matrix = (function () {
  2572. function Matrix() {
  2573. this.m = new Float32Array(16);
  2574. }
  2575. // Properties
  2576. /**
  2577. * Boolean : True is the matrix is the identity matrix
  2578. */
  2579. Matrix.prototype.isIdentity = function () {
  2580. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2581. return false;
  2582. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2583. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2584. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2585. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2586. return false;
  2587. return true;
  2588. };
  2589. /**
  2590. * Returns the matrix determinant (float).
  2591. */
  2592. Matrix.prototype.determinant = function () {
  2593. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2594. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2595. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2596. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2597. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2598. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2599. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2600. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2601. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2602. };
  2603. // Methods
  2604. /**
  2605. * Returns the matrix underlying array.
  2606. */
  2607. Matrix.prototype.toArray = function () {
  2608. return this.m;
  2609. };
  2610. /**
  2611. * Returns the matrix underlying array.
  2612. */
  2613. Matrix.prototype.asArray = function () {
  2614. return this.toArray();
  2615. };
  2616. /**
  2617. * Inverts in place the Matrix.
  2618. * Returns the Matrix inverted.
  2619. */
  2620. Matrix.prototype.invert = function () {
  2621. this.invertToRef(this);
  2622. return this;
  2623. };
  2624. /**
  2625. * Sets all the matrix elements to zero.
  2626. * Returns the Matrix.
  2627. */
  2628. Matrix.prototype.reset = function () {
  2629. for (var index = 0; index < 16; index++) {
  2630. this.m[index] = 0.0;
  2631. }
  2632. return this;
  2633. };
  2634. /**
  2635. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2636. */
  2637. Matrix.prototype.add = function (other) {
  2638. var result = new Matrix();
  2639. this.addToRef(other, result);
  2640. return result;
  2641. };
  2642. /**
  2643. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2644. * Returns the Matrix.
  2645. */
  2646. Matrix.prototype.addToRef = function (other, result) {
  2647. for (var index = 0; index < 16; index++) {
  2648. result.m[index] = this.m[index] + other.m[index];
  2649. }
  2650. return this;
  2651. };
  2652. /**
  2653. * Adds in place the passed matrix to the current Matrix.
  2654. * Returns the updated Matrix.
  2655. */
  2656. Matrix.prototype.addToSelf = function (other) {
  2657. for (var index = 0; index < 16; index++) {
  2658. this.m[index] += other.m[index];
  2659. }
  2660. return this;
  2661. };
  2662. /**
  2663. * Sets the passed matrix with the current inverted Matrix.
  2664. * Returns the unmodified current Matrix.
  2665. */
  2666. Matrix.prototype.invertToRef = function (other) {
  2667. var l1 = this.m[0];
  2668. var l2 = this.m[1];
  2669. var l3 = this.m[2];
  2670. var l4 = this.m[3];
  2671. var l5 = this.m[4];
  2672. var l6 = this.m[5];
  2673. var l7 = this.m[6];
  2674. var l8 = this.m[7];
  2675. var l9 = this.m[8];
  2676. var l10 = this.m[9];
  2677. var l11 = this.m[10];
  2678. var l12 = this.m[11];
  2679. var l13 = this.m[12];
  2680. var l14 = this.m[13];
  2681. var l15 = this.m[14];
  2682. var l16 = this.m[15];
  2683. var l17 = (l11 * l16) - (l12 * l15);
  2684. var l18 = (l10 * l16) - (l12 * l14);
  2685. var l19 = (l10 * l15) - (l11 * l14);
  2686. var l20 = (l9 * l16) - (l12 * l13);
  2687. var l21 = (l9 * l15) - (l11 * l13);
  2688. var l22 = (l9 * l14) - (l10 * l13);
  2689. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2690. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2691. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2692. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2693. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2694. var l28 = (l7 * l16) - (l8 * l15);
  2695. var l29 = (l6 * l16) - (l8 * l14);
  2696. var l30 = (l6 * l15) - (l7 * l14);
  2697. var l31 = (l5 * l16) - (l8 * l13);
  2698. var l32 = (l5 * l15) - (l7 * l13);
  2699. var l33 = (l5 * l14) - (l6 * l13);
  2700. var l34 = (l7 * l12) - (l8 * l11);
  2701. var l35 = (l6 * l12) - (l8 * l10);
  2702. var l36 = (l6 * l11) - (l7 * l10);
  2703. var l37 = (l5 * l12) - (l8 * l9);
  2704. var l38 = (l5 * l11) - (l7 * l9);
  2705. var l39 = (l5 * l10) - (l6 * l9);
  2706. other.m[0] = l23 * l27;
  2707. other.m[4] = l24 * l27;
  2708. other.m[8] = l25 * l27;
  2709. other.m[12] = l26 * l27;
  2710. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2711. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2712. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2713. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2714. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2715. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2716. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2717. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2718. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2719. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2720. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2721. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2722. return this;
  2723. };
  2724. /**
  2725. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2726. * Returns the updated Matrix.
  2727. */
  2728. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2729. this.m[12] = x;
  2730. this.m[13] = y;
  2731. this.m[14] = z;
  2732. return this;
  2733. };
  2734. /**
  2735. * Inserts the translation vector in the current Matrix.
  2736. * Returns the updated Matrix.
  2737. */
  2738. Matrix.prototype.setTranslation = function (vector3) {
  2739. this.m[12] = vector3.x;
  2740. this.m[13] = vector3.y;
  2741. this.m[14] = vector3.z;
  2742. return this;
  2743. };
  2744. /**
  2745. * Returns a new Vector3 as the extracted translation from the Matrix.
  2746. */
  2747. Matrix.prototype.getTranslation = function () {
  2748. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2749. };
  2750. /**
  2751. * Remove rotation and scaling part from the Matrix.
  2752. * Returns the updated Matrix.
  2753. */
  2754. Matrix.prototype.removeRotationAndScaling = function () {
  2755. this.setRowFromFloats(0, 1, 0, 0, 0);
  2756. this.setRowFromFloats(1, 0, 1, 0, 0);
  2757. this.setRowFromFloats(2, 0, 0, 1, 0);
  2758. return this;
  2759. };
  2760. /**
  2761. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2762. */
  2763. Matrix.prototype.multiply = function (other) {
  2764. var result = new Matrix();
  2765. this.multiplyToRef(other, result);
  2766. return result;
  2767. };
  2768. /**
  2769. * Updates the current Matrix from the passed one values.
  2770. * Returns the updated Matrix.
  2771. */
  2772. Matrix.prototype.copyFrom = function (other) {
  2773. for (var index = 0; index < 16; index++) {
  2774. this.m[index] = other.m[index];
  2775. }
  2776. return this;
  2777. };
  2778. /**
  2779. * Populates the passed array from the starting index with the Matrix values.
  2780. * Returns the Matrix.
  2781. */
  2782. Matrix.prototype.copyToArray = function (array, offset) {
  2783. if (offset === void 0) { offset = 0; }
  2784. for (var index = 0; index < 16; index++) {
  2785. array[offset + index] = this.m[index];
  2786. }
  2787. return this;
  2788. };
  2789. /**
  2790. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2791. */
  2792. Matrix.prototype.multiplyToRef = function (other, result) {
  2793. this.multiplyToArray(other, result.m, 0);
  2794. return this;
  2795. };
  2796. /**
  2797. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2798. */
  2799. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2800. var tm0 = this.m[0];
  2801. var tm1 = this.m[1];
  2802. var tm2 = this.m[2];
  2803. var tm3 = this.m[3];
  2804. var tm4 = this.m[4];
  2805. var tm5 = this.m[5];
  2806. var tm6 = this.m[6];
  2807. var tm7 = this.m[7];
  2808. var tm8 = this.m[8];
  2809. var tm9 = this.m[9];
  2810. var tm10 = this.m[10];
  2811. var tm11 = this.m[11];
  2812. var tm12 = this.m[12];
  2813. var tm13 = this.m[13];
  2814. var tm14 = this.m[14];
  2815. var tm15 = this.m[15];
  2816. var om0 = other.m[0];
  2817. var om1 = other.m[1];
  2818. var om2 = other.m[2];
  2819. var om3 = other.m[3];
  2820. var om4 = other.m[4];
  2821. var om5 = other.m[5];
  2822. var om6 = other.m[6];
  2823. var om7 = other.m[7];
  2824. var om8 = other.m[8];
  2825. var om9 = other.m[9];
  2826. var om10 = other.m[10];
  2827. var om11 = other.m[11];
  2828. var om12 = other.m[12];
  2829. var om13 = other.m[13];
  2830. var om14 = other.m[14];
  2831. var om15 = other.m[15];
  2832. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2833. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2834. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2835. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2836. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2837. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2838. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2839. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2840. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2841. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2842. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2843. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2844. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2845. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2846. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2847. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2848. return this;
  2849. };
  2850. /**
  2851. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2852. */
  2853. Matrix.prototype.equals = function (value) {
  2854. return value &&
  2855. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2856. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2857. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2858. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2859. };
  2860. /**
  2861. * Returns a new Matrix from the current Matrix.
  2862. */
  2863. Matrix.prototype.clone = function () {
  2864. 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]);
  2865. };
  2866. /**
  2867. * Returns the string "Matrix"
  2868. */
  2869. Matrix.prototype.getClassName = function () {
  2870. return "Matrix";
  2871. };
  2872. /**
  2873. * Returns the Matrix hash code.
  2874. */
  2875. Matrix.prototype.getHashCode = function () {
  2876. var hash = this.m[0] || 0;
  2877. for (var i = 1; i < 16; i++) {
  2878. hash = (hash * 397) ^ (this.m[i] || 0);
  2879. }
  2880. return hash;
  2881. };
  2882. /**
  2883. * Decomposes the current Matrix into :
  2884. * - a scale vector3 passed as a reference to update,
  2885. * - a rotation quaternion passed as a reference to update,
  2886. * - a translation vector3 passed as a reference to update.
  2887. * Returns the boolean `true`.
  2888. */
  2889. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2890. translation.x = this.m[12];
  2891. translation.y = this.m[13];
  2892. translation.z = this.m[14];
  2893. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  2894. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  2895. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  2896. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  2897. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  2898. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  2899. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  2900. rotation.x = 0;
  2901. rotation.y = 0;
  2902. rotation.z = 0;
  2903. rotation.w = 1;
  2904. return false;
  2905. }
  2906. 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, MathTmp.Matrix[0]);
  2907. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  2908. return true;
  2909. };
  2910. /**
  2911. * Returns a new Matrix as the extracted rotation matrix from the current one.
  2912. */
  2913. Matrix.prototype.getRotationMatrix = function () {
  2914. var result = Matrix.Identity();
  2915. this.getRotationMatrixToRef(result);
  2916. return result;
  2917. };
  2918. /**
  2919. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  2920. * Returns the current Matrix.
  2921. */
  2922. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2923. var m = this.m;
  2924. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2925. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2926. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2927. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2928. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2929. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2930. 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);
  2931. return this;
  2932. };
  2933. // Statics
  2934. /**
  2935. * Returns a new Matrix set from the starting index of the passed array.
  2936. */
  2937. Matrix.FromArray = function (array, offset) {
  2938. var result = new Matrix();
  2939. if (!offset) {
  2940. offset = 0;
  2941. }
  2942. Matrix.FromArrayToRef(array, offset, result);
  2943. return result;
  2944. };
  2945. /**
  2946. * Sets the passed "result" matrix from the starting index of the passed array.
  2947. */
  2948. Matrix.FromArrayToRef = function (array, offset, result) {
  2949. for (var index = 0; index < 16; index++) {
  2950. result.m[index] = array[index + offset];
  2951. }
  2952. };
  2953. /**
  2954. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  2955. */
  2956. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2957. for (var index = 0; index < 16; index++) {
  2958. result.m[index] = array[index + offset] * scale;
  2959. }
  2960. };
  2961. /**
  2962. * Sets the passed matrix "result" with the 16 passed floats.
  2963. */
  2964. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2965. result.m[0] = initialM11;
  2966. result.m[1] = initialM12;
  2967. result.m[2] = initialM13;
  2968. result.m[3] = initialM14;
  2969. result.m[4] = initialM21;
  2970. result.m[5] = initialM22;
  2971. result.m[6] = initialM23;
  2972. result.m[7] = initialM24;
  2973. result.m[8] = initialM31;
  2974. result.m[9] = initialM32;
  2975. result.m[10] = initialM33;
  2976. result.m[11] = initialM34;
  2977. result.m[12] = initialM41;
  2978. result.m[13] = initialM42;
  2979. result.m[14] = initialM43;
  2980. result.m[15] = initialM44;
  2981. };
  2982. /**
  2983. * Returns the index-th row of the current matrix as a new Vector4.
  2984. */
  2985. Matrix.prototype.getRow = function (index) {
  2986. if (index < 0 || index > 3) {
  2987. return null;
  2988. }
  2989. var i = index * 4;
  2990. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2991. };
  2992. /**
  2993. * Sets the index-th row of the current matrix with the passed Vector4 values.
  2994. * Returns the updated Matrix.
  2995. */
  2996. Matrix.prototype.setRow = function (index, row) {
  2997. if (index < 0 || index > 3) {
  2998. return this;
  2999. }
  3000. var i = index * 4;
  3001. this.m[i + 0] = row.x;
  3002. this.m[i + 1] = row.y;
  3003. this.m[i + 2] = row.z;
  3004. this.m[i + 3] = row.w;
  3005. return this;
  3006. };
  3007. /**
  3008. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3009. * Returns the updated Matrix.
  3010. */
  3011. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3012. if (index < 0 || index > 3) {
  3013. return this;
  3014. }
  3015. var i = index * 4;
  3016. this.m[i + 0] = x;
  3017. this.m[i + 1] = y;
  3018. this.m[i + 2] = z;
  3019. this.m[i + 3] = w;
  3020. return this;
  3021. };
  3022. /**
  3023. * Returns a new Matrix set from the 16 passed floats.
  3024. */
  3025. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3026. var result = new Matrix();
  3027. result.m[0] = initialM11;
  3028. result.m[1] = initialM12;
  3029. result.m[2] = initialM13;
  3030. result.m[3] = initialM14;
  3031. result.m[4] = initialM21;
  3032. result.m[5] = initialM22;
  3033. result.m[6] = initialM23;
  3034. result.m[7] = initialM24;
  3035. result.m[8] = initialM31;
  3036. result.m[9] = initialM32;
  3037. result.m[10] = initialM33;
  3038. result.m[11] = initialM34;
  3039. result.m[12] = initialM41;
  3040. result.m[13] = initialM42;
  3041. result.m[14] = initialM43;
  3042. result.m[15] = initialM44;
  3043. return result;
  3044. };
  3045. /**
  3046. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3047. */
  3048. Matrix.Compose = function (scale, rotation, translation) {
  3049. var result = Matrix.Identity();
  3050. Matrix.ComposeToRef(scale, rotation, translation, result);
  3051. return result;
  3052. };
  3053. /**
  3054. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3055. */
  3056. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3057. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3058. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3059. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3060. result.setTranslation(translation);
  3061. };
  3062. /**
  3063. * Returns a new indentity Matrix.
  3064. */
  3065. Matrix.Identity = function () {
  3066. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3067. };
  3068. /**
  3069. * Sets the passed "result" as an identity matrix.
  3070. */
  3071. Matrix.IdentityToRef = function (result) {
  3072. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3073. };
  3074. /**
  3075. * Returns a new zero Matrix.
  3076. */
  3077. Matrix.Zero = function () {
  3078. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3079. };
  3080. /**
  3081. * Returns a new rotation matrix for "angle" radians around the X axis.
  3082. */
  3083. Matrix.RotationX = function (angle) {
  3084. var result = new Matrix();
  3085. Matrix.RotationXToRef(angle, result);
  3086. return result;
  3087. };
  3088. /**
  3089. * Returns a new Matrix as the passed inverted one.
  3090. */
  3091. Matrix.Invert = function (source) {
  3092. var result = new Matrix();
  3093. source.invertToRef(result);
  3094. return result;
  3095. };
  3096. /**
  3097. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3098. */
  3099. Matrix.RotationXToRef = function (angle, result) {
  3100. var s = Math.sin(angle);
  3101. var c = Math.cos(angle);
  3102. result.m[0] = 1.0;
  3103. result.m[15] = 1.0;
  3104. result.m[5] = c;
  3105. result.m[10] = c;
  3106. result.m[9] = -s;
  3107. result.m[6] = s;
  3108. result.m[1] = 0.0;
  3109. result.m[2] = 0.0;
  3110. result.m[3] = 0.0;
  3111. result.m[4] = 0.0;
  3112. result.m[7] = 0.0;
  3113. result.m[8] = 0.0;
  3114. result.m[11] = 0.0;
  3115. result.m[12] = 0.0;
  3116. result.m[13] = 0.0;
  3117. result.m[14] = 0.0;
  3118. };
  3119. /**
  3120. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3121. */
  3122. Matrix.RotationY = function (angle) {
  3123. var result = new Matrix();
  3124. Matrix.RotationYToRef(angle, result);
  3125. return result;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3129. */
  3130. Matrix.RotationYToRef = function (angle, result) {
  3131. var s = Math.sin(angle);
  3132. var c = Math.cos(angle);
  3133. result.m[5] = 1.0;
  3134. result.m[15] = 1.0;
  3135. result.m[0] = c;
  3136. result.m[2] = -s;
  3137. result.m[8] = s;
  3138. result.m[10] = c;
  3139. result.m[1] = 0.0;
  3140. result.m[3] = 0.0;
  3141. result.m[4] = 0.0;
  3142. result.m[6] = 0.0;
  3143. result.m[7] = 0.0;
  3144. result.m[9] = 0.0;
  3145. result.m[11] = 0.0;
  3146. result.m[12] = 0.0;
  3147. result.m[13] = 0.0;
  3148. result.m[14] = 0.0;
  3149. };
  3150. /**
  3151. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3152. */
  3153. Matrix.RotationZ = function (angle) {
  3154. var result = new Matrix();
  3155. Matrix.RotationZToRef(angle, result);
  3156. return result;
  3157. };
  3158. /**
  3159. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3160. */
  3161. Matrix.RotationZToRef = function (angle, result) {
  3162. var s = Math.sin(angle);
  3163. var c = Math.cos(angle);
  3164. result.m[10] = 1.0;
  3165. result.m[15] = 1.0;
  3166. result.m[0] = c;
  3167. result.m[1] = s;
  3168. result.m[4] = -s;
  3169. result.m[5] = c;
  3170. result.m[2] = 0.0;
  3171. result.m[3] = 0.0;
  3172. result.m[6] = 0.0;
  3173. result.m[7] = 0.0;
  3174. result.m[8] = 0.0;
  3175. result.m[9] = 0.0;
  3176. result.m[11] = 0.0;
  3177. result.m[12] = 0.0;
  3178. result.m[13] = 0.0;
  3179. result.m[14] = 0.0;
  3180. };
  3181. /**
  3182. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3183. */
  3184. Matrix.RotationAxis = function (axis, angle) {
  3185. var result = Matrix.Zero();
  3186. Matrix.RotationAxisToRef(axis, angle, result);
  3187. return result;
  3188. };
  3189. /**
  3190. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3191. */
  3192. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3193. var s = Math.sin(-angle);
  3194. var c = Math.cos(-angle);
  3195. var c1 = 1 - c;
  3196. axis.normalize();
  3197. result.m[0] = (axis.x * axis.x) * c1 + c;
  3198. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3199. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3200. result.m[3] = 0.0;
  3201. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3202. result.m[5] = (axis.y * axis.y) * c1 + c;
  3203. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3204. result.m[7] = 0.0;
  3205. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3206. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3207. result.m[10] = (axis.z * axis.z) * c1 + c;
  3208. result.m[11] = 0.0;
  3209. result.m[15] = 1.0;
  3210. };
  3211. /**
  3212. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3213. */
  3214. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3215. var result = new Matrix();
  3216. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3217. return result;
  3218. };
  3219. /**
  3220. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3221. */
  3222. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3223. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3224. this._tempQuaternion.toRotationMatrix(result);
  3225. };
  3226. /**
  3227. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3228. */
  3229. Matrix.Scaling = function (x, y, z) {
  3230. var result = Matrix.Zero();
  3231. Matrix.ScalingToRef(x, y, z, result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3236. */
  3237. Matrix.ScalingToRef = function (x, y, z, result) {
  3238. result.m[0] = x;
  3239. result.m[1] = 0.0;
  3240. result.m[2] = 0.0;
  3241. result.m[3] = 0.0;
  3242. result.m[4] = 0.0;
  3243. result.m[5] = y;
  3244. result.m[6] = 0.0;
  3245. result.m[7] = 0.0;
  3246. result.m[8] = 0.0;
  3247. result.m[9] = 0.0;
  3248. result.m[10] = z;
  3249. result.m[11] = 0.0;
  3250. result.m[12] = 0.0;
  3251. result.m[13] = 0.0;
  3252. result.m[14] = 0.0;
  3253. result.m[15] = 1.0;
  3254. };
  3255. /**
  3256. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3257. */
  3258. Matrix.Translation = function (x, y, z) {
  3259. var result = Matrix.Identity();
  3260. Matrix.TranslationToRef(x, y, z, result);
  3261. return result;
  3262. };
  3263. /**
  3264. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3265. */
  3266. Matrix.TranslationToRef = function (x, y, z, result) {
  3267. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3268. };
  3269. /**
  3270. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3271. */
  3272. Matrix.Lerp = function (startValue, endValue, gradient) {
  3273. var result = Matrix.Zero();
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3276. }
  3277. return result;
  3278. };
  3279. /**
  3280. * Returns a new Matrix whose values are computed by :
  3281. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3282. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3283. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3284. */
  3285. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3286. var startScale = new Vector3(0, 0, 0);
  3287. var startRotation = new Quaternion();
  3288. var startTranslation = new Vector3(0, 0, 0);
  3289. startValue.decompose(startScale, startRotation, startTranslation);
  3290. var endScale = new Vector3(0, 0, 0);
  3291. var endRotation = new Quaternion();
  3292. var endTranslation = new Vector3(0, 0, 0);
  3293. endValue.decompose(endScale, endRotation, endTranslation);
  3294. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3295. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3296. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3297. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3298. };
  3299. /**
  3300. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3301. * This methods works for a Left-Handed system.
  3302. */
  3303. Matrix.LookAtLH = function (eye, target, up) {
  3304. var result = Matrix.Zero();
  3305. Matrix.LookAtLHToRef(eye, target, up, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3310. * This methods works for a Left-Handed system.
  3311. */
  3312. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3313. // Z axis
  3314. target.subtractToRef(eye, this._zAxis);
  3315. this._zAxis.normalize();
  3316. // X axis
  3317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3318. if (this._xAxis.lengthSquared() === 0) {
  3319. this._xAxis.x = 1.0;
  3320. }
  3321. else {
  3322. this._xAxis.normalize();
  3323. }
  3324. // Y axis
  3325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3326. this._yAxis.normalize();
  3327. // Eye angles
  3328. var ex = -Vector3.Dot(this._xAxis, eye);
  3329. var ey = -Vector3.Dot(this._yAxis, eye);
  3330. var ez = -Vector3.Dot(this._zAxis, eye);
  3331. 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);
  3332. };
  3333. /**
  3334. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3335. * This methods works for a Right-Handed system.
  3336. */
  3337. Matrix.LookAtRH = function (eye, target, up) {
  3338. var result = Matrix.Zero();
  3339. Matrix.LookAtRHToRef(eye, target, up, result);
  3340. return result;
  3341. };
  3342. /**
  3343. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3344. * This methods works for a Left-Handed system.
  3345. */
  3346. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3347. // Z axis
  3348. eye.subtractToRef(target, this._zAxis);
  3349. this._zAxis.normalize();
  3350. // X axis
  3351. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3352. if (this._xAxis.lengthSquared() === 0) {
  3353. this._xAxis.x = 1.0;
  3354. }
  3355. else {
  3356. this._xAxis.normalize();
  3357. }
  3358. // Y axis
  3359. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3360. this._yAxis.normalize();
  3361. // Eye angles
  3362. var ex = -Vector3.Dot(this._xAxis, eye);
  3363. var ey = -Vector3.Dot(this._yAxis, eye);
  3364. var ez = -Vector3.Dot(this._zAxis, eye);
  3365. 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);
  3366. };
  3367. /**
  3368. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3369. */
  3370. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3371. var matrix = Matrix.Zero();
  3372. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3373. return matrix;
  3374. };
  3375. /**
  3376. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3377. */
  3378. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3379. var n = znear;
  3380. var f = zfar;
  3381. var a = 2.0 / width;
  3382. var b = 2.0 / height;
  3383. var c = 2.0 / (f - n);
  3384. var d = -(f + n) / (f - n);
  3385. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3386. };
  3387. /**
  3388. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3389. */
  3390. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3391. var matrix = Matrix.Zero();
  3392. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3393. return matrix;
  3394. };
  3395. /**
  3396. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3397. */
  3398. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3399. var n = znear;
  3400. var f = zfar;
  3401. var a = 2.0 / (right - left);
  3402. var b = 2.0 / (top - bottom);
  3403. var c = 2.0 / (f - n);
  3404. var d = -(f + n) / (f - n);
  3405. var i0 = (left + right) / (left - right);
  3406. var i1 = (top + bottom) / (bottom - top);
  3407. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3408. };
  3409. /**
  3410. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3411. */
  3412. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3413. var matrix = Matrix.Zero();
  3414. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3415. return matrix;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3419. */
  3420. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3421. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3422. result.m[10] *= -1.0;
  3423. };
  3424. /**
  3425. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3426. */
  3427. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3428. var matrix = Matrix.Zero();
  3429. var n = znear;
  3430. var f = zfar;
  3431. var a = 2.0 * n / width;
  3432. var b = 2.0 * n / height;
  3433. var c = (f + n) / (f - n);
  3434. var d = -2.0 * f * n / (f - n);
  3435. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3436. return matrix;
  3437. };
  3438. /**
  3439. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3440. */
  3441. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3442. var matrix = Matrix.Zero();
  3443. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3444. return matrix;
  3445. };
  3446. /**
  3447. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3448. */
  3449. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3450. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3451. var n = znear;
  3452. var f = zfar;
  3453. var t = 1.0 / (Math.tan(fov * 0.5));
  3454. var a = isVerticalFovFixed ? (t / aspect) : t;
  3455. var b = isVerticalFovFixed ? t : (t * aspect);
  3456. var c = (f + n) / (f - n);
  3457. var d = -2.0 * f * n / (f - n);
  3458. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3459. };
  3460. /**
  3461. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3462. */
  3463. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3464. var matrix = Matrix.Zero();
  3465. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3466. return matrix;
  3467. };
  3468. /**
  3469. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3470. */
  3471. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3472. //alternatively this could be expressed as:
  3473. // m = PerspectiveFovLHToRef
  3474. // m[10] *= -1.0;
  3475. // m[11] *= -1.0;
  3476. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3477. var n = znear;
  3478. var f = zfar;
  3479. var t = 1.0 / (Math.tan(fov * 0.5));
  3480. var a = isVerticalFovFixed ? (t / aspect) : t;
  3481. var b = isVerticalFovFixed ? t : (t * aspect);
  3482. var c = -(f + n) / (f - n);
  3483. var d = -2 * f * n / (f - n);
  3484. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3485. };
  3486. /**
  3487. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3488. */
  3489. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  3490. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3491. //left handed
  3492. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3493. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3494. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3495. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3496. var xScale = 2.0 / (leftTan + rightTan);
  3497. var yScale = 2.0 / (upTan + downTan);
  3498. result.m[0] = xScale;
  3499. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3500. result.m[5] = yScale;
  3501. result.m[6] = result.m[7] = 0.0;
  3502. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  3503. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  3504. result.m[10] = -(znear + zfar) / (zfar - znear);
  3505. // result.m[10] = -zfar / (znear - zfar);
  3506. result.m[11] = 1.0;
  3507. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3508. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3509. // result.m[14] = (znear * zfar) / (znear - zfar);
  3510. };
  3511. /**
  3512. * Returns the final transformation matrix : world * view * projection * viewport
  3513. */
  3514. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3515. var cw = viewport.width;
  3516. var ch = viewport.height;
  3517. var cx = viewport.x;
  3518. var cy = viewport.y;
  3519. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3520. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3521. };
  3522. /**
  3523. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3524. */
  3525. Matrix.GetAsMatrix2x2 = function (matrix) {
  3526. return new Float32Array([
  3527. matrix.m[0], matrix.m[1],
  3528. matrix.m[4], matrix.m[5]
  3529. ]);
  3530. };
  3531. /**
  3532. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3533. */
  3534. Matrix.GetAsMatrix3x3 = function (matrix) {
  3535. return new Float32Array([
  3536. matrix.m[0], matrix.m[1], matrix.m[2],
  3537. matrix.m[4], matrix.m[5], matrix.m[6],
  3538. matrix.m[8], matrix.m[9], matrix.m[10]
  3539. ]);
  3540. };
  3541. /**
  3542. * Compute the transpose of the passed Matrix.
  3543. * Returns a new Matrix.
  3544. */
  3545. Matrix.Transpose = function (matrix) {
  3546. var result = new Matrix();
  3547. result.m[0] = matrix.m[0];
  3548. result.m[1] = matrix.m[4];
  3549. result.m[2] = matrix.m[8];
  3550. result.m[3] = matrix.m[12];
  3551. result.m[4] = matrix.m[1];
  3552. result.m[5] = matrix.m[5];
  3553. result.m[6] = matrix.m[9];
  3554. result.m[7] = matrix.m[13];
  3555. result.m[8] = matrix.m[2];
  3556. result.m[9] = matrix.m[6];
  3557. result.m[10] = matrix.m[10];
  3558. result.m[11] = matrix.m[14];
  3559. result.m[12] = matrix.m[3];
  3560. result.m[13] = matrix.m[7];
  3561. result.m[14] = matrix.m[11];
  3562. result.m[15] = matrix.m[15];
  3563. return result;
  3564. };
  3565. /**
  3566. * Returns a new Matrix as the reflection matrix across the passed plane.
  3567. */
  3568. Matrix.Reflection = function (plane) {
  3569. var matrix = new Matrix();
  3570. Matrix.ReflectionToRef(plane, matrix);
  3571. return matrix;
  3572. };
  3573. /**
  3574. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3575. */
  3576. Matrix.ReflectionToRef = function (plane, result) {
  3577. plane.normalize();
  3578. var x = plane.normal.x;
  3579. var y = plane.normal.y;
  3580. var z = plane.normal.z;
  3581. var temp = -2 * x;
  3582. var temp2 = -2 * y;
  3583. var temp3 = -2 * z;
  3584. result.m[0] = (temp * x) + 1;
  3585. result.m[1] = temp2 * x;
  3586. result.m[2] = temp3 * x;
  3587. result.m[3] = 0.0;
  3588. result.m[4] = temp * y;
  3589. result.m[5] = (temp2 * y) + 1;
  3590. result.m[6] = temp3 * y;
  3591. result.m[7] = 0.0;
  3592. result.m[8] = temp * z;
  3593. result.m[9] = temp2 * z;
  3594. result.m[10] = (temp3 * z) + 1;
  3595. result.m[11] = 0.0;
  3596. result.m[12] = temp * plane.d;
  3597. result.m[13] = temp2 * plane.d;
  3598. result.m[14] = temp3 * plane.d;
  3599. result.m[15] = 1.0;
  3600. };
  3601. /**
  3602. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3603. */
  3604. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3605. mat.m[0] = xaxis.x;
  3606. mat.m[1] = xaxis.y;
  3607. mat.m[2] = xaxis.z;
  3608. mat.m[3] = 0.0;
  3609. mat.m[4] = yaxis.x;
  3610. mat.m[5] = yaxis.y;
  3611. mat.m[6] = yaxis.z;
  3612. mat.m[7] = 0.0;
  3613. mat.m[8] = zaxis.x;
  3614. mat.m[9] = zaxis.y;
  3615. mat.m[10] = zaxis.z;
  3616. mat.m[11] = 0.0;
  3617. mat.m[12] = 0.0;
  3618. mat.m[13] = 0.0;
  3619. mat.m[14] = 0.0;
  3620. mat.m[15] = 1.0;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3624. */
  3625. Matrix.FromQuaternionToRef = function (quat, result) {
  3626. var xx = quat.x * quat.x;
  3627. var yy = quat.y * quat.y;
  3628. var zz = quat.z * quat.z;
  3629. var xy = quat.x * quat.y;
  3630. var zw = quat.z * quat.w;
  3631. var zx = quat.z * quat.x;
  3632. var yw = quat.y * quat.w;
  3633. var yz = quat.y * quat.z;
  3634. var xw = quat.x * quat.w;
  3635. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3636. result.m[1] = 2.0 * (xy + zw);
  3637. result.m[2] = 2.0 * (zx - yw);
  3638. result.m[3] = 0.0;
  3639. result.m[4] = 2.0 * (xy - zw);
  3640. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3641. result.m[6] = 2.0 * (yz + xw);
  3642. result.m[7] = 0.0;
  3643. result.m[8] = 2.0 * (zx + yw);
  3644. result.m[9] = 2.0 * (yz - xw);
  3645. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3646. result.m[11] = 0.0;
  3647. result.m[12] = 0.0;
  3648. result.m[13] = 0.0;
  3649. result.m[14] = 0.0;
  3650. result.m[15] = 1.0;
  3651. };
  3652. return Matrix;
  3653. }());
  3654. Matrix._tempQuaternion = new Quaternion();
  3655. Matrix._xAxis = Vector3.Zero();
  3656. Matrix._yAxis = Vector3.Zero();
  3657. Matrix._zAxis = Vector3.Zero();
  3658. BABYLON.Matrix = Matrix;
  3659. var Plane = (function () {
  3660. /**
  3661. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3662. */
  3663. function Plane(a, b, c, d) {
  3664. this.normal = new Vector3(a, b, c);
  3665. this.d = d;
  3666. }
  3667. /**
  3668. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3669. */
  3670. Plane.prototype.asArray = function () {
  3671. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3672. };
  3673. // Methods
  3674. /**
  3675. * Returns a new plane copied from the current Plane.
  3676. */
  3677. Plane.prototype.clone = function () {
  3678. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3679. };
  3680. /**
  3681. * Returns the string "Plane".
  3682. */
  3683. Plane.prototype.getClassName = function () {
  3684. return "Plane";
  3685. };
  3686. /**
  3687. * Returns the Plane hash code.
  3688. */
  3689. Plane.prototype.getHashCode = function () {
  3690. var hash = this.normal.getHashCode();
  3691. hash = (hash * 397) ^ (this.d || 0);
  3692. return hash;
  3693. };
  3694. /**
  3695. * Normalize the current Plane in place.
  3696. * Returns the updated Plane.
  3697. */
  3698. Plane.prototype.normalize = function () {
  3699. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3700. var magnitude = 0.0;
  3701. if (norm !== 0) {
  3702. magnitude = 1.0 / norm;
  3703. }
  3704. this.normal.x *= magnitude;
  3705. this.normal.y *= magnitude;
  3706. this.normal.z *= magnitude;
  3707. this.d *= magnitude;
  3708. return this;
  3709. };
  3710. /**
  3711. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3712. */
  3713. Plane.prototype.transform = function (transformation) {
  3714. var transposedMatrix = Matrix.Transpose(transformation);
  3715. var x = this.normal.x;
  3716. var y = this.normal.y;
  3717. var z = this.normal.z;
  3718. var d = this.d;
  3719. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3720. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3721. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3722. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3723. return new Plane(normalX, normalY, normalZ, finalD);
  3724. };
  3725. /**
  3726. * Returns the dot product (float) of the point coordinates and the plane normal.
  3727. */
  3728. Plane.prototype.dotCoordinate = function (point) {
  3729. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3730. };
  3731. /**
  3732. * Updates the current Plane from the plane defined by the three passed points.
  3733. * Returns the updated Plane.
  3734. */
  3735. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3736. var x1 = point2.x - point1.x;
  3737. var y1 = point2.y - point1.y;
  3738. var z1 = point2.z - point1.z;
  3739. var x2 = point3.x - point1.x;
  3740. var y2 = point3.y - point1.y;
  3741. var z2 = point3.z - point1.z;
  3742. var yz = (y1 * z2) - (z1 * y2);
  3743. var xz = (z1 * x2) - (x1 * z2);
  3744. var xy = (x1 * y2) - (y1 * x2);
  3745. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3746. var invPyth;
  3747. if (pyth !== 0) {
  3748. invPyth = 1.0 / pyth;
  3749. }
  3750. else {
  3751. invPyth = 0.0;
  3752. }
  3753. this.normal.x = yz * invPyth;
  3754. this.normal.y = xz * invPyth;
  3755. this.normal.z = xy * invPyth;
  3756. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3757. return this;
  3758. };
  3759. /**
  3760. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3761. */
  3762. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3763. var dot = Vector3.Dot(this.normal, direction);
  3764. return (dot <= epsilon);
  3765. };
  3766. /**
  3767. * Returns the signed distance (float) from the passed point to the Plane.
  3768. */
  3769. Plane.prototype.signedDistanceTo = function (point) {
  3770. return Vector3.Dot(point, this.normal) + this.d;
  3771. };
  3772. // Statics
  3773. /**
  3774. * Returns a new Plane from the passed array.
  3775. */
  3776. Plane.FromArray = function (array) {
  3777. return new Plane(array[0], array[1], array[2], array[3]);
  3778. };
  3779. /**
  3780. * Returns a new Plane defined by the three passed points.
  3781. */
  3782. Plane.FromPoints = function (point1, point2, point3) {
  3783. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3784. result.copyFromPoints(point1, point2, point3);
  3785. return result;
  3786. };
  3787. /**
  3788. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3789. * Note : the vector "normal" is updated because normalized.
  3790. */
  3791. Plane.FromPositionAndNormal = function (origin, normal) {
  3792. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3793. normal.normalize();
  3794. result.normal = normal;
  3795. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3796. return result;
  3797. };
  3798. /**
  3799. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3800. */
  3801. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3802. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3803. return Vector3.Dot(point, normal) + d;
  3804. };
  3805. return Plane;
  3806. }());
  3807. BABYLON.Plane = Plane;
  3808. var Viewport = (function () {
  3809. /**
  3810. * Creates a Viewport object located at (x, y) and sized (width, height).
  3811. */
  3812. function Viewport(x, y, width, height) {
  3813. this.x = x;
  3814. this.y = y;
  3815. this.width = width;
  3816. this.height = height;
  3817. }
  3818. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3819. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3820. };
  3821. /**
  3822. * Returns a new Viewport copied from the current one.
  3823. */
  3824. Viewport.prototype.clone = function () {
  3825. return new Viewport(this.x, this.y, this.width, this.height);
  3826. };
  3827. return Viewport;
  3828. }());
  3829. BABYLON.Viewport = Viewport;
  3830. var Frustum = (function () {
  3831. function Frustum() {
  3832. }
  3833. /**
  3834. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3835. */
  3836. Frustum.GetPlanes = function (transform) {
  3837. var frustumPlanes = [];
  3838. for (var index = 0; index < 6; index++) {
  3839. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3840. }
  3841. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3842. return frustumPlanes;
  3843. };
  3844. /**
  3845. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3846. */
  3847. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3848. // Near
  3849. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3850. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3851. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3852. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3853. frustumPlanes[0].normalize();
  3854. // Far
  3855. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3856. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3857. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3858. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3859. frustumPlanes[1].normalize();
  3860. // Left
  3861. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3862. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3863. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3864. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3865. frustumPlanes[2].normalize();
  3866. // Right
  3867. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3868. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3869. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3870. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3871. frustumPlanes[3].normalize();
  3872. // Top
  3873. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3874. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3875. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3876. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3877. frustumPlanes[4].normalize();
  3878. // Bottom
  3879. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3880. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3881. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3882. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3883. frustumPlanes[5].normalize();
  3884. };
  3885. return Frustum;
  3886. }());
  3887. BABYLON.Frustum = Frustum;
  3888. var Space;
  3889. (function (Space) {
  3890. Space[Space["LOCAL"] = 0] = "LOCAL";
  3891. Space[Space["WORLD"] = 1] = "WORLD";
  3892. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  3893. var Axis = (function () {
  3894. function Axis() {
  3895. }
  3896. return Axis;
  3897. }());
  3898. Axis.X = new Vector3(1.0, 0.0, 0.0);
  3899. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  3900. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  3901. BABYLON.Axis = Axis;
  3902. ;
  3903. var BezierCurve = (function () {
  3904. function BezierCurve() {
  3905. }
  3906. /**
  3907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  3908. */
  3909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  3910. // Extract X (which is equal to time here)
  3911. var f0 = 1 - 3 * x2 + 3 * x1;
  3912. var f1 = 3 * x2 - 6 * x1;
  3913. var f2 = 3 * x1;
  3914. var refinedT = t;
  3915. for (var i = 0; i < 5; i++) {
  3916. var refinedT2 = refinedT * refinedT;
  3917. var refinedT3 = refinedT2 * refinedT;
  3918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  3919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  3920. refinedT -= (x - t) * slope;
  3921. refinedT = Math.min(1, Math.max(0, refinedT));
  3922. }
  3923. // Resolve cubic bezier for the given x
  3924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  3925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  3926. Math.pow(refinedT, 3);
  3927. };
  3928. return BezierCurve;
  3929. }());
  3930. BABYLON.BezierCurve = BezierCurve;
  3931. var Orientation;
  3932. (function (Orientation) {
  3933. Orientation[Orientation["CW"] = 0] = "CW";
  3934. Orientation[Orientation["CCW"] = 1] = "CCW";
  3935. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  3936. var Angle = (function () {
  3937. /**
  3938. * Creates an Angle object of "radians" radians (float).
  3939. */
  3940. function Angle(radians) {
  3941. var _this = this;
  3942. /**
  3943. * Returns the Angle value in degrees (float).
  3944. */
  3945. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  3946. /**
  3947. * Returns the Angle value in radians (float).
  3948. */
  3949. this.radians = function () { return _this._radians; };
  3950. this._radians = radians;
  3951. if (this._radians < 0.0)
  3952. this._radians += (2.0 * Math.PI);
  3953. }
  3954. /**
  3955. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  3956. */
  3957. Angle.BetweenTwoPoints = function (a, b) {
  3958. var delta = b.subtract(a);
  3959. var theta = Math.atan2(delta.y, delta.x);
  3960. return new Angle(theta);
  3961. };
  3962. /**
  3963. * Returns a new Angle object from the passed float in radians.
  3964. */
  3965. Angle.FromRadians = function (radians) {
  3966. return new Angle(radians);
  3967. };
  3968. /**
  3969. * Returns a new Angle object from the passed float in degrees.
  3970. */
  3971. Angle.FromDegrees = function (degrees) {
  3972. return new Angle(degrees * Math.PI / 180.0);
  3973. };
  3974. return Angle;
  3975. }());
  3976. BABYLON.Angle = Angle;
  3977. var Arc2 = (function () {
  3978. /**
  3979. * Creates an Arc object from the three passed points : start, middle and end.
  3980. */
  3981. function Arc2(startPoint, midPoint, endPoint) {
  3982. this.startPoint = startPoint;
  3983. this.midPoint = midPoint;
  3984. this.endPoint = endPoint;
  3985. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  3986. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  3987. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  3988. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  3989. 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);
  3990. this.radius = this.centerPoint.subtract(this.startPoint).length();
  3991. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  3992. var a1 = this.startAngle.degrees();
  3993. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  3994. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  3995. // angles correction
  3996. if (a2 - a1 > +180.0)
  3997. a2 -= 360.0;
  3998. if (a2 - a1 < -180.0)
  3999. a2 += 360.0;
  4000. if (a3 - a2 > +180.0)
  4001. a3 -= 360.0;
  4002. if (a3 - a2 < -180.0)
  4003. a3 += 360.0;
  4004. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4005. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4006. }
  4007. return Arc2;
  4008. }());
  4009. BABYLON.Arc2 = Arc2;
  4010. var Path2 = (function () {
  4011. /**
  4012. * Creates a Path2 object from the starting 2D coordinates x and y.
  4013. */
  4014. function Path2(x, y) {
  4015. this._points = new Array();
  4016. this._length = 0.0;
  4017. this.closed = false;
  4018. this._points.push(new Vector2(x, y));
  4019. }
  4020. /**
  4021. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4022. * Returns the updated Path2.
  4023. */
  4024. Path2.prototype.addLineTo = function (x, y) {
  4025. if (closed) {
  4026. //Tools.Error("cannot add lines to closed paths");
  4027. return this;
  4028. }
  4029. var newPoint = new Vector2(x, y);
  4030. var previousPoint = this._points[this._points.length - 1];
  4031. this._points.push(newPoint);
  4032. this._length += newPoint.subtract(previousPoint).length();
  4033. return this;
  4034. };
  4035. /**
  4036. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4037. * Returns the updated Path2.
  4038. */
  4039. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4040. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4041. if (closed) {
  4042. //Tools.Error("cannot add arcs to closed paths");
  4043. return this;
  4044. }
  4045. var startPoint = this._points[this._points.length - 1];
  4046. var midPoint = new Vector2(midX, midY);
  4047. var endPoint = new Vector2(endX, endY);
  4048. var arc = new Arc2(startPoint, midPoint, endPoint);
  4049. var increment = arc.angle.radians() / numberOfSegments;
  4050. if (arc.orientation === Orientation.CW)
  4051. increment *= -1;
  4052. var currentAngle = arc.startAngle.radians() + increment;
  4053. for (var i = 0; i < numberOfSegments; i++) {
  4054. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4055. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4056. this.addLineTo(x, y);
  4057. currentAngle += increment;
  4058. }
  4059. return this;
  4060. };
  4061. /**
  4062. * Closes the Path2.
  4063. * Returns the Path2.
  4064. */
  4065. Path2.prototype.close = function () {
  4066. this.closed = true;
  4067. return this;
  4068. };
  4069. /**
  4070. * Returns the Path2 total length (float).
  4071. */
  4072. Path2.prototype.length = function () {
  4073. var result = this._length;
  4074. if (!this.closed) {
  4075. var lastPoint = this._points[this._points.length - 1];
  4076. var firstPoint = this._points[0];
  4077. result += (firstPoint.subtract(lastPoint).length());
  4078. }
  4079. return result;
  4080. };
  4081. /**
  4082. * Returns the Path2 internal array of points.
  4083. */
  4084. Path2.prototype.getPoints = function () {
  4085. return this._points;
  4086. };
  4087. /**
  4088. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4089. */
  4090. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4091. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4092. //Tools.Error("normalized length position should be between 0 and 1.");
  4093. return Vector2.Zero();
  4094. }
  4095. var lengthPosition = normalizedLengthPosition * this.length();
  4096. var previousOffset = 0;
  4097. for (var i = 0; i < this._points.length; i++) {
  4098. var j = (i + 1) % this._points.length;
  4099. var a = this._points[i];
  4100. var b = this._points[j];
  4101. var bToA = b.subtract(a);
  4102. var nextOffset = (bToA.length() + previousOffset);
  4103. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4104. var dir = bToA.normalize();
  4105. var localOffset = lengthPosition - previousOffset;
  4106. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4107. }
  4108. previousOffset = nextOffset;
  4109. }
  4110. //Tools.Error("internal error");
  4111. return Vector2.Zero();
  4112. };
  4113. /**
  4114. * Returns a new Path2 starting at the coordinates (x, y).
  4115. */
  4116. Path2.StartingAt = function (x, y) {
  4117. return new Path2(x, y);
  4118. };
  4119. return Path2;
  4120. }());
  4121. BABYLON.Path2 = Path2;
  4122. var Path3D = (function () {
  4123. /**
  4124. * new Path3D(path, normal, raw)
  4125. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4126. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4127. * path : an array of Vector3, the curve axis of the Path3D
  4128. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4129. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4130. */
  4131. function Path3D(path, firstNormal, raw) {
  4132. this.path = path;
  4133. this._curve = new Array();
  4134. this._distances = new Array();
  4135. this._tangents = new Array();
  4136. this._normals = new Array();
  4137. this._binormals = new Array();
  4138. for (var p = 0; p < path.length; p++) {
  4139. this._curve[p] = path[p].clone(); // hard copy
  4140. }
  4141. this._raw = raw || false;
  4142. this._compute(firstNormal);
  4143. }
  4144. /**
  4145. * Returns the Path3D array of successive Vector3 designing its curve.
  4146. */
  4147. Path3D.prototype.getCurve = function () {
  4148. return this._curve;
  4149. };
  4150. /**
  4151. * Returns an array populated with tangent vectors on each Path3D curve point.
  4152. */
  4153. Path3D.prototype.getTangents = function () {
  4154. return this._tangents;
  4155. };
  4156. /**
  4157. * Returns an array populated with normal vectors on each Path3D curve point.
  4158. */
  4159. Path3D.prototype.getNormals = function () {
  4160. return this._normals;
  4161. };
  4162. /**
  4163. * Returns an array populated with binormal vectors on each Path3D curve point.
  4164. */
  4165. Path3D.prototype.getBinormals = function () {
  4166. return this._binormals;
  4167. };
  4168. /**
  4169. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4170. */
  4171. Path3D.prototype.getDistances = function () {
  4172. return this._distances;
  4173. };
  4174. /**
  4175. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4176. * Returns the same object updated.
  4177. */
  4178. Path3D.prototype.update = function (path, firstNormal) {
  4179. for (var p = 0; p < path.length; p++) {
  4180. this._curve[p].x = path[p].x;
  4181. this._curve[p].y = path[p].y;
  4182. this._curve[p].z = path[p].z;
  4183. }
  4184. this._compute(firstNormal);
  4185. return this;
  4186. };
  4187. // private function compute() : computes tangents, normals and binormals
  4188. Path3D.prototype._compute = function (firstNormal) {
  4189. var l = this._curve.length;
  4190. // first and last tangents
  4191. this._tangents[0] = this._getFirstNonNullVector(0);
  4192. if (!this._raw) {
  4193. this._tangents[0].normalize();
  4194. }
  4195. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4196. if (!this._raw) {
  4197. this._tangents[l - 1].normalize();
  4198. }
  4199. // normals and binormals at first point : arbitrary vector with _normalVector()
  4200. var tg0 = this._tangents[0];
  4201. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4202. this._normals[0] = pp0;
  4203. if (!this._raw) {
  4204. this._normals[0].normalize();
  4205. }
  4206. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4207. if (!this._raw) {
  4208. this._binormals[0].normalize();
  4209. }
  4210. this._distances[0] = 0.0;
  4211. // normals and binormals : next points
  4212. var prev; // previous vector (segment)
  4213. var cur; // current vector (segment)
  4214. var curTang; // current tangent
  4215. // previous normal
  4216. var prevBinor; // previous binormal
  4217. for (var i = 1; i < l; i++) {
  4218. // tangents
  4219. prev = this._getLastNonNullVector(i);
  4220. if (i < l - 1) {
  4221. cur = this._getFirstNonNullVector(i);
  4222. this._tangents[i] = prev.add(cur);
  4223. this._tangents[i].normalize();
  4224. }
  4225. this._distances[i] = this._distances[i - 1] + prev.length();
  4226. // normals and binormals
  4227. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4228. curTang = this._tangents[i];
  4229. prevBinor = this._binormals[i - 1];
  4230. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4231. if (!this._raw) {
  4232. this._normals[i].normalize();
  4233. }
  4234. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4235. if (!this._raw) {
  4236. this._binormals[i].normalize();
  4237. }
  4238. }
  4239. };
  4240. // private function getFirstNonNullVector(index)
  4241. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4242. Path3D.prototype._getFirstNonNullVector = function (index) {
  4243. var i = 1;
  4244. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4245. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4246. i++;
  4247. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4248. }
  4249. return nNVector;
  4250. };
  4251. // private function getLastNonNullVector(index)
  4252. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4253. Path3D.prototype._getLastNonNullVector = function (index) {
  4254. var i = 1;
  4255. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4256. while (nLVector.length() === 0 && index > i + 1) {
  4257. i++;
  4258. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4259. }
  4260. return nLVector;
  4261. };
  4262. // private function normalVector(v0, vt, va) :
  4263. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4264. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4265. Path3D.prototype._normalVector = function (v0, vt, va) {
  4266. var normal0;
  4267. var tgl = vt.length();
  4268. if (tgl === 0.0) {
  4269. tgl = 1.0;
  4270. }
  4271. if (va === undefined || va === null) {
  4272. var point;
  4273. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4274. point = new Vector3(0.0, -1.0, 0.0);
  4275. }
  4276. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4277. point = new Vector3(1.0, 0.0, 0.0);
  4278. }
  4279. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4280. point = new Vector3(0.0, 0.0, 1.0);
  4281. }
  4282. normal0 = Vector3.Cross(vt, point);
  4283. }
  4284. else {
  4285. normal0 = Vector3.Cross(vt, va);
  4286. Vector3.CrossToRef(normal0, vt, normal0);
  4287. }
  4288. normal0.normalize();
  4289. return normal0;
  4290. };
  4291. return Path3D;
  4292. }());
  4293. BABYLON.Path3D = Path3D;
  4294. var Curve3 = (function () {
  4295. /**
  4296. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4297. * A Curve3 is designed from a series of successive Vector3.
  4298. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4299. */
  4300. function Curve3(points) {
  4301. this._length = 0.0;
  4302. this._points = points;
  4303. this._length = this._computeLength(points);
  4304. }
  4305. /**
  4306. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4307. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4308. * @param v1 (Vector3) the control point
  4309. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4310. * @param nbPoints (integer) the wanted number of points in the curve
  4311. */
  4312. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4313. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4314. var bez = new Array();
  4315. var equation = function (t, val0, val1, val2) {
  4316. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4317. return res;
  4318. };
  4319. for (var i = 0; i <= nbPoints; i++) {
  4320. 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)));
  4321. }
  4322. return new Curve3(bez);
  4323. };
  4324. /**
  4325. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4326. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4327. * @param v1 (Vector3) the first control point
  4328. * @param v2 (Vector3) the second control point
  4329. * @param v3 (Vector3) the end point of the Cubic Bezier
  4330. * @param nbPoints (integer) the wanted number of points in the curve
  4331. */
  4332. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4333. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4334. var bez = new Array();
  4335. var equation = function (t, val0, val1, val2, val3) {
  4336. 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;
  4337. return res;
  4338. };
  4339. for (var i = 0; i <= nbPoints; i++) {
  4340. 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)));
  4341. }
  4342. return new Curve3(bez);
  4343. };
  4344. /**
  4345. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4346. * @param p1 (Vector3) the origin point of the Hermite Spline
  4347. * @param t1 (Vector3) the tangent vector at the origin point
  4348. * @param p2 (Vector3) the end point of the Hermite Spline
  4349. * @param t2 (Vector3) the tangent vector at the end point
  4350. * @param nbPoints (integer) the wanted number of points in the curve
  4351. */
  4352. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4353. var hermite = new Array();
  4354. var step = 1.0 / nbPoints;
  4355. for (var i = 0; i <= nbPoints; i++) {
  4356. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4357. }
  4358. return new Curve3(hermite);
  4359. };
  4360. /**
  4361. * Returns a Curve3 object along a CatmullRom Spline curve :
  4362. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4363. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4364. */
  4365. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4366. var totalPoints = new Array();
  4367. totalPoints.push(points[0].clone());
  4368. Array.prototype.push.apply(totalPoints, points);
  4369. totalPoints.push(points[points.length - 1].clone());
  4370. var catmullRom = new Array();
  4371. var step = 1.0 / nbPoints;
  4372. for (var i = 0; i < totalPoints.length - 3; i++) {
  4373. var amount = 0.0;
  4374. for (var c = 0; c < nbPoints; c++) {
  4375. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4376. amount += step;
  4377. }
  4378. }
  4379. i--;
  4380. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4381. return new Curve3(catmullRom);
  4382. };
  4383. /**
  4384. * Returns the Curve3 stored array of successive Vector3
  4385. */
  4386. Curve3.prototype.getPoints = function () {
  4387. return this._points;
  4388. };
  4389. /**
  4390. * Returns the computed length (float) of the curve.
  4391. */
  4392. Curve3.prototype.length = function () {
  4393. return this._length;
  4394. };
  4395. /**
  4396. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4397. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4398. * curveA and curveB keep unchanged.
  4399. */
  4400. Curve3.prototype.continue = function (curve) {
  4401. var lastPoint = this._points[this._points.length - 1];
  4402. var continuedPoints = this._points.slice();
  4403. var curvePoints = curve.getPoints();
  4404. for (var i = 1; i < curvePoints.length; i++) {
  4405. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4406. }
  4407. var continuedCurve = new Curve3(continuedPoints);
  4408. return continuedCurve;
  4409. };
  4410. Curve3.prototype._computeLength = function (path) {
  4411. var l = 0;
  4412. for (var i = 1; i < path.length; i++) {
  4413. l += (path[i].subtract(path[i - 1])).length();
  4414. }
  4415. return l;
  4416. };
  4417. return Curve3;
  4418. }());
  4419. BABYLON.Curve3 = Curve3;
  4420. // SphericalHarmonics
  4421. var SphericalHarmonics = (function () {
  4422. function SphericalHarmonics() {
  4423. this.L00 = Vector3.Zero();
  4424. this.L1_1 = Vector3.Zero();
  4425. this.L10 = Vector3.Zero();
  4426. this.L11 = Vector3.Zero();
  4427. this.L2_2 = Vector3.Zero();
  4428. this.L2_1 = Vector3.Zero();
  4429. this.L20 = Vector3.Zero();
  4430. this.L21 = Vector3.Zero();
  4431. this.L22 = Vector3.Zero();
  4432. }
  4433. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4434. var colorVector = new Vector3(color.r, color.g, color.b);
  4435. var c = colorVector.scale(deltaSolidAngle);
  4436. this.L00 = this.L00.add(c.scale(0.282095));
  4437. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4438. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4439. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4440. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4441. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4442. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4443. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4444. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4445. };
  4446. SphericalHarmonics.prototype.scale = function (scale) {
  4447. this.L00 = this.L00.scale(scale);
  4448. this.L1_1 = this.L1_1.scale(scale);
  4449. this.L10 = this.L10.scale(scale);
  4450. this.L11 = this.L11.scale(scale);
  4451. this.L2_2 = this.L2_2.scale(scale);
  4452. this.L2_1 = this.L2_1.scale(scale);
  4453. this.L20 = this.L20.scale(scale);
  4454. this.L21 = this.L21.scale(scale);
  4455. this.L22 = this.L22.scale(scale);
  4456. };
  4457. return SphericalHarmonics;
  4458. }());
  4459. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4460. // SphericalPolynomial
  4461. var SphericalPolynomial = (function () {
  4462. function SphericalPolynomial() {
  4463. this.x = Vector3.Zero();
  4464. this.y = Vector3.Zero();
  4465. this.z = Vector3.Zero();
  4466. this.xx = Vector3.Zero();
  4467. this.yy = Vector3.Zero();
  4468. this.zz = Vector3.Zero();
  4469. this.xy = Vector3.Zero();
  4470. this.yz = Vector3.Zero();
  4471. this.zx = Vector3.Zero();
  4472. }
  4473. SphericalPolynomial.prototype.addAmbient = function (color) {
  4474. var colorVector = new Vector3(color.r, color.g, color.b);
  4475. this.xx = this.xx.add(colorVector);
  4476. this.yy = this.yy.add(colorVector);
  4477. this.zz = this.zz.add(colorVector);
  4478. };
  4479. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4480. var result = new SphericalPolynomial();
  4481. result.x = harmonics.L11.scale(1.02333);
  4482. result.y = harmonics.L1_1.scale(1.02333);
  4483. result.z = harmonics.L10.scale(1.02333);
  4484. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4485. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4486. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4487. result.yz = harmonics.L2_1.scale(0.858086);
  4488. result.zx = harmonics.L21.scale(0.858086);
  4489. result.xy = harmonics.L2_2.scale(0.858086);
  4490. return result;
  4491. };
  4492. return SphericalPolynomial;
  4493. }());
  4494. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4495. // Vertex formats
  4496. var PositionNormalVertex = (function () {
  4497. function PositionNormalVertex(position, normal) {
  4498. if (position === void 0) { position = Vector3.Zero(); }
  4499. if (normal === void 0) { normal = Vector3.Up(); }
  4500. this.position = position;
  4501. this.normal = normal;
  4502. }
  4503. PositionNormalVertex.prototype.clone = function () {
  4504. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4505. };
  4506. return PositionNormalVertex;
  4507. }());
  4508. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4509. var PositionNormalTextureVertex = (function () {
  4510. function PositionNormalTextureVertex(position, normal, uv) {
  4511. if (position === void 0) { position = Vector3.Zero(); }
  4512. if (normal === void 0) { normal = Vector3.Up(); }
  4513. if (uv === void 0) { uv = Vector2.Zero(); }
  4514. this.position = position;
  4515. this.normal = normal;
  4516. this.uv = uv;
  4517. }
  4518. PositionNormalTextureVertex.prototype.clone = function () {
  4519. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4520. };
  4521. return PositionNormalTextureVertex;
  4522. }());
  4523. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4524. // Temporary pre-allocated objects for engine internal use
  4525. // usage in any internal function :
  4526. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4527. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4528. var Tmp = (function () {
  4529. function Tmp() {
  4530. }
  4531. return Tmp;
  4532. }());
  4533. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4534. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4535. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4536. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4537. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4538. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4539. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4540. Matrix.Zero(), Matrix.Zero(),
  4541. Matrix.Zero(), Matrix.Zero(),
  4542. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4543. BABYLON.Tmp = Tmp;
  4544. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4545. var MathTmp = (function () {
  4546. function MathTmp() {
  4547. }
  4548. return MathTmp;
  4549. }());
  4550. MathTmp.Vector3 = [Vector3.Zero()];
  4551. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4552. MathTmp.Quaternion = [Quaternion.Zero()];
  4553. })(BABYLON || (BABYLON = {}));
  4554. //# sourceMappingURL=babylon.math.js.map
  4555. //# sourceMappingURL=babylon.mixins.js.map
  4556. var BABYLON;
  4557. (function (BABYLON) {
  4558. function generateSerializableMember(type, sourceName) {
  4559. return function (target, propertyKey) {
  4560. if (!target.__serializableMembers) {
  4561. target.__serializableMembers = {};
  4562. }
  4563. if (!target.__serializableMembers[propertyKey]) {
  4564. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4565. }
  4566. };
  4567. }
  4568. function serialize(sourceName) {
  4569. return generateSerializableMember(0, sourceName); // value member
  4570. }
  4571. BABYLON.serialize = serialize;
  4572. function serializeAsTexture(sourceName) {
  4573. return generateSerializableMember(1, sourceName); // texture member
  4574. }
  4575. BABYLON.serializeAsTexture = serializeAsTexture;
  4576. function serializeAsColor3(sourceName) {
  4577. return generateSerializableMember(2, sourceName); // color3 member
  4578. }
  4579. BABYLON.serializeAsColor3 = serializeAsColor3;
  4580. function serializeAsFresnelParameters(sourceName) {
  4581. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4582. }
  4583. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4584. function serializeAsVector2(sourceName) {
  4585. return generateSerializableMember(4, sourceName); // vector2 member
  4586. }
  4587. BABYLON.serializeAsVector2 = serializeAsVector2;
  4588. function serializeAsVector3(sourceName) {
  4589. return generateSerializableMember(5, sourceName); // vector3 member
  4590. }
  4591. BABYLON.serializeAsVector3 = serializeAsVector3;
  4592. function serializeAsMeshReference(sourceName) {
  4593. return generateSerializableMember(6, sourceName); // mesh reference member
  4594. }
  4595. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4596. function serializeAsColorCurves(sourceName) {
  4597. return generateSerializableMember(7, sourceName); // color curves
  4598. }
  4599. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4600. var SerializationHelper = (function () {
  4601. function SerializationHelper() {
  4602. }
  4603. SerializationHelper.Serialize = function (entity, serializationObject) {
  4604. if (!serializationObject) {
  4605. serializationObject = {};
  4606. }
  4607. // Tags
  4608. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4609. // Properties
  4610. for (var property in entity.__serializableMembers) {
  4611. var propertyDescriptor = entity.__serializableMembers[property];
  4612. var targetPropertyName = propertyDescriptor.sourceName || property;
  4613. var propertyType = propertyDescriptor.type;
  4614. var sourceProperty = entity[property];
  4615. if (sourceProperty !== undefined && sourceProperty !== null) {
  4616. switch (propertyType) {
  4617. case 0:
  4618. serializationObject[targetPropertyName] = sourceProperty;
  4619. break;
  4620. case 1:
  4621. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4622. break;
  4623. case 2:
  4624. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4625. break;
  4626. case 3:
  4627. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4628. break;
  4629. case 4:
  4630. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4631. break;
  4632. case 5:
  4633. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4634. break;
  4635. case 6:
  4636. serializationObject[targetPropertyName] = sourceProperty.id;
  4637. break;
  4638. case 7:
  4639. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4640. break;
  4641. }
  4642. }
  4643. }
  4644. return serializationObject;
  4645. };
  4646. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4647. var destination = creationFunction();
  4648. // Tags
  4649. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4650. // Properties
  4651. for (var property in destination.__serializableMembers) {
  4652. var propertyDescriptor = destination.__serializableMembers[property];
  4653. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4654. var propertyType = propertyDescriptor.type;
  4655. if (sourceProperty !== undefined && sourceProperty !== null) {
  4656. switch (propertyType) {
  4657. case 0:
  4658. destination[property] = sourceProperty;
  4659. break;
  4660. case 1:
  4661. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4662. break;
  4663. case 2:
  4664. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4665. break;
  4666. case 3:
  4667. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4668. break;
  4669. case 4:
  4670. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4671. break;
  4672. case 5:
  4673. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4674. break;
  4675. case 6:
  4676. destination[property] = scene.getLastMeshByID(sourceProperty);
  4677. break;
  4678. case 7:
  4679. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4680. break;
  4681. }
  4682. }
  4683. }
  4684. return destination;
  4685. };
  4686. SerializationHelper.Clone = function (creationFunction, source) {
  4687. var destination = creationFunction();
  4688. // Tags
  4689. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4690. // Properties
  4691. for (var property in destination.__serializableMembers) {
  4692. var propertyDescriptor = destination.__serializableMembers[property];
  4693. var sourceProperty = source[property];
  4694. var propertyType = propertyDescriptor.type;
  4695. if (sourceProperty !== undefined && sourceProperty !== null) {
  4696. switch (propertyType) {
  4697. case 0: // Value
  4698. case 6:
  4699. destination[property] = sourceProperty;
  4700. break;
  4701. case 1: // Texture
  4702. case 2: // Color3
  4703. case 3: // FresnelParameters
  4704. case 4: // Vector2
  4705. case 5: // Vector3
  4706. case 7:
  4707. destination[property] = sourceProperty.clone();
  4708. break;
  4709. }
  4710. }
  4711. }
  4712. return destination;
  4713. };
  4714. return SerializationHelper;
  4715. }());
  4716. BABYLON.SerializationHelper = SerializationHelper;
  4717. })(BABYLON || (BABYLON = {}));
  4718. //# sourceMappingURL=babylon.decorators.js.map
  4719. var BABYLON;
  4720. (function (BABYLON) {
  4721. /**
  4722. * A class serves as a medium between the observable and its observers
  4723. */
  4724. var EventState = (function () {
  4725. /**
  4726. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4727. */
  4728. function EventState(mask, skipNextObservers) {
  4729. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4730. this.initalize(mask, skipNextObservers);
  4731. }
  4732. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4733. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4734. this.mask = mask;
  4735. this.skipNextObservers = skipNextObservers;
  4736. return this;
  4737. };
  4738. return EventState;
  4739. }());
  4740. BABYLON.EventState = EventState;
  4741. /**
  4742. * Represent an Observer registered to a given Observable object.
  4743. */
  4744. var Observer = (function () {
  4745. function Observer(callback, mask) {
  4746. this.callback = callback;
  4747. this.mask = mask;
  4748. }
  4749. return Observer;
  4750. }());
  4751. BABYLON.Observer = Observer;
  4752. /**
  4753. * The Observable class is a simple implementation of the Observable pattern.
  4754. * 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.
  4755. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4756. * 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).
  4757. * 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.
  4758. */
  4759. var Observable = (function () {
  4760. function Observable() {
  4761. this._observers = new Array();
  4762. this._eventState = new EventState(0);
  4763. }
  4764. /**
  4765. * Create a new Observer with the specified callback
  4766. * @param callback the callback that will be executed for that Observer
  4767. * @param mask the mask used to filter observers
  4768. * @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.
  4769. */
  4770. Observable.prototype.add = function (callback, mask, insertFirst) {
  4771. if (mask === void 0) { mask = -1; }
  4772. if (insertFirst === void 0) { insertFirst = false; }
  4773. if (!callback) {
  4774. return null;
  4775. }
  4776. var observer = new Observer(callback, mask);
  4777. if (insertFirst) {
  4778. this._observers.unshift(observer);
  4779. }
  4780. else {
  4781. this._observers.push(observer);
  4782. }
  4783. return observer;
  4784. };
  4785. /**
  4786. * Remove an Observer from the Observable object
  4787. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4788. */
  4789. Observable.prototype.remove = function (observer) {
  4790. var index = this._observers.indexOf(observer);
  4791. if (index !== -1) {
  4792. this._observers.splice(index, 1);
  4793. return true;
  4794. }
  4795. return false;
  4796. };
  4797. /**
  4798. * Remove a callback from the Observable object
  4799. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4800. */
  4801. Observable.prototype.removeCallback = function (callback) {
  4802. for (var index = 0; index < this._observers.length; index++) {
  4803. if (this._observers[index].callback === callback) {
  4804. this._observers.splice(index, 1);
  4805. return true;
  4806. }
  4807. }
  4808. return false;
  4809. };
  4810. /**
  4811. * Notify all Observers by calling their respective callback with the given data
  4812. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4813. * @param eventData
  4814. * @param mask
  4815. */
  4816. Observable.prototype.notifyObservers = function (eventData, mask) {
  4817. if (mask === void 0) { mask = -1; }
  4818. var state = this._eventState;
  4819. state.mask = mask;
  4820. state.skipNextObservers = false;
  4821. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4822. var obs = _a[_i];
  4823. if (obs.mask & mask) {
  4824. obs.callback(eventData, state);
  4825. }
  4826. if (state.skipNextObservers) {
  4827. return false;
  4828. }
  4829. }
  4830. return true;
  4831. };
  4832. /**
  4833. * return true is the Observable has at least one Observer registered
  4834. */
  4835. Observable.prototype.hasObservers = function () {
  4836. return this._observers.length > 0;
  4837. };
  4838. /**
  4839. * Clear the list of observers
  4840. */
  4841. Observable.prototype.clear = function () {
  4842. this._observers = new Array();
  4843. };
  4844. /**
  4845. * Clone the current observable
  4846. */
  4847. Observable.prototype.clone = function () {
  4848. var result = new Observable();
  4849. result._observers = this._observers.slice(0);
  4850. return result;
  4851. };
  4852. return Observable;
  4853. }());
  4854. BABYLON.Observable = Observable;
  4855. })(BABYLON || (BABYLON = {}));
  4856. //# sourceMappingURL=babylon.observable.js.map
  4857. var BABYLON;
  4858. (function (BABYLON) {
  4859. var Database = (function () {
  4860. function Database(urlToScene, callbackManifestChecked) {
  4861. // Handling various flavors of prefixed version of IndexedDB
  4862. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4863. this.callbackManifestChecked = callbackManifestChecked;
  4864. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4865. this.db = null;
  4866. this.enableSceneOffline = false;
  4867. this.enableTexturesOffline = false;
  4868. this.manifestVersionFound = 0;
  4869. this.mustUpdateRessources = false;
  4870. this.hasReachedQuota = false;
  4871. if (!Database.IDBStorageEnabled) {
  4872. this.callbackManifestChecked(true);
  4873. }
  4874. else {
  4875. this.checkManifestFile();
  4876. }
  4877. }
  4878. Database.prototype.checkManifestFile = function () {
  4879. var _this = this;
  4880. function noManifestFile() {
  4881. that.enableSceneOffline = false;
  4882. that.enableTexturesOffline = false;
  4883. that.callbackManifestChecked(false);
  4884. }
  4885. var that = this;
  4886. var timeStampUsed = false;
  4887. var manifestURL = this.currentSceneUrl + ".manifest";
  4888. var xhr = new XMLHttpRequest();
  4889. if (navigator.onLine) {
  4890. // Adding a timestamp to by-pass browsers' cache
  4891. timeStampUsed = true;
  4892. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  4893. }
  4894. xhr.open("GET", manifestURL, true);
  4895. xhr.addEventListener("load", function () {
  4896. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  4897. try {
  4898. var manifestFile = JSON.parse(xhr.response);
  4899. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  4900. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  4901. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  4902. _this.manifestVersionFound = manifestFile.version;
  4903. }
  4904. if (_this.callbackManifestChecked) {
  4905. _this.callbackManifestChecked(true);
  4906. }
  4907. }
  4908. catch (ex) {
  4909. noManifestFile();
  4910. }
  4911. }
  4912. else {
  4913. noManifestFile();
  4914. }
  4915. }, false);
  4916. xhr.addEventListener("error", function (event) {
  4917. if (timeStampUsed) {
  4918. timeStampUsed = false;
  4919. // Let's retry without the timeStamp
  4920. // It could fail when coupled with HTML5 Offline API
  4921. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  4922. xhr.open("GET", retryManifestURL, true);
  4923. xhr.send();
  4924. }
  4925. else {
  4926. noManifestFile();
  4927. }
  4928. }, false);
  4929. try {
  4930. xhr.send();
  4931. }
  4932. catch (ex) {
  4933. BABYLON.Tools.Error("Error on XHR send request.");
  4934. that.callbackManifestChecked(false);
  4935. }
  4936. };
  4937. Database.prototype.openAsync = function (successCallback, errorCallback) {
  4938. var _this = this;
  4939. function handleError() {
  4940. that.isSupported = false;
  4941. if (errorCallback)
  4942. errorCallback();
  4943. }
  4944. var that = this;
  4945. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  4946. // Your browser doesn't support IndexedDB
  4947. this.isSupported = false;
  4948. if (errorCallback)
  4949. errorCallback();
  4950. }
  4951. else {
  4952. // If the DB hasn't been opened or created yet
  4953. if (!this.db) {
  4954. this.hasReachedQuota = false;
  4955. this.isSupported = true;
  4956. var request = this.idbFactory.open("babylonjs", 1);
  4957. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  4958. request.onerror = function (event) {
  4959. handleError();
  4960. };
  4961. // executes when a version change transaction cannot complete due to other active transactions
  4962. request.onblocked = function (event) {
  4963. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  4964. handleError();
  4965. };
  4966. // DB has been opened successfully
  4967. request.onsuccess = function (event) {
  4968. _this.db = request.result;
  4969. successCallback();
  4970. };
  4971. // Initialization of the DB. Creating Scenes & Textures stores
  4972. request.onupgradeneeded = function (event) {
  4973. _this.db = (event.target).result;
  4974. try {
  4975. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  4976. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  4977. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  4978. }
  4979. catch (ex) {
  4980. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  4981. handleError();
  4982. }
  4983. };
  4984. }
  4985. else {
  4986. if (successCallback)
  4987. successCallback();
  4988. }
  4989. }
  4990. };
  4991. Database.prototype.loadImageFromDB = function (url, image) {
  4992. var _this = this;
  4993. var completeURL = Database.ReturnFullUrlLocation(url);
  4994. var saveAndLoadImage = function () {
  4995. if (!_this.hasReachedQuota && _this.db !== null) {
  4996. // the texture is not yet in the DB, let's try to save it
  4997. _this._saveImageIntoDBAsync(completeURL, image);
  4998. }
  4999. else {
  5000. image.src = url;
  5001. }
  5002. };
  5003. if (!this.mustUpdateRessources) {
  5004. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5005. }
  5006. else {
  5007. saveAndLoadImage();
  5008. }
  5009. };
  5010. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5011. if (this.isSupported && this.db !== null) {
  5012. var texture;
  5013. var transaction = this.db.transaction(["textures"]);
  5014. transaction.onabort = function (event) {
  5015. image.src = url;
  5016. };
  5017. transaction.oncomplete = function (event) {
  5018. var blobTextureURL;
  5019. if (texture) {
  5020. var URL = window.URL || window.webkitURL;
  5021. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5022. image.onerror = function () {
  5023. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5024. image.src = url;
  5025. };
  5026. image.src = blobTextureURL;
  5027. }
  5028. else {
  5029. notInDBCallback();
  5030. }
  5031. };
  5032. var getRequest = transaction.objectStore("textures").get(url);
  5033. getRequest.onsuccess = function (event) {
  5034. texture = (event.target).result;
  5035. };
  5036. getRequest.onerror = function (event) {
  5037. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5038. image.src = url;
  5039. };
  5040. }
  5041. else {
  5042. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5043. image.src = url;
  5044. }
  5045. };
  5046. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5047. var _this = this;
  5048. if (this.isSupported) {
  5049. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5050. var generateBlobUrl = function () {
  5051. var blobTextureURL;
  5052. if (blob) {
  5053. var URL = window.URL || window.webkitURL;
  5054. try {
  5055. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5056. }
  5057. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5058. catch (ex) {
  5059. blobTextureURL = URL.createObjectURL(blob);
  5060. }
  5061. }
  5062. image.src = blobTextureURL;
  5063. };
  5064. if (Database.IsUASupportingBlobStorage) {
  5065. var xhr = new XMLHttpRequest(), blob;
  5066. xhr.open("GET", url, true);
  5067. xhr.responseType = "blob";
  5068. xhr.addEventListener("load", function () {
  5069. if (xhr.status === 200) {
  5070. // Blob as response (XHR2)
  5071. blob = xhr.response;
  5072. var transaction = _this.db.transaction(["textures"], "readwrite");
  5073. // the transaction could abort because of a QuotaExceededError error
  5074. transaction.onabort = function (event) {
  5075. try {
  5076. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5077. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5078. _this.hasReachedQuota = true;
  5079. }
  5080. }
  5081. catch (ex) { }
  5082. generateBlobUrl();
  5083. };
  5084. transaction.oncomplete = function (event) {
  5085. generateBlobUrl();
  5086. };
  5087. var newTexture = { textureUrl: url, data: blob };
  5088. try {
  5089. // Put the blob into the dabase
  5090. var addRequest = transaction.objectStore("textures").put(newTexture);
  5091. addRequest.onsuccess = function (event) {
  5092. };
  5093. addRequest.onerror = function (event) {
  5094. generateBlobUrl();
  5095. };
  5096. }
  5097. catch (ex) {
  5098. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5099. if (ex.code === 25) {
  5100. Database.IsUASupportingBlobStorage = false;
  5101. }
  5102. image.src = url;
  5103. }
  5104. }
  5105. else {
  5106. image.src = url;
  5107. }
  5108. }, false);
  5109. xhr.addEventListener("error", function (event) {
  5110. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5111. image.src = url;
  5112. }, false);
  5113. xhr.send();
  5114. }
  5115. else {
  5116. image.src = url;
  5117. }
  5118. }
  5119. else {
  5120. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5121. image.src = url;
  5122. }
  5123. };
  5124. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5125. var _this = this;
  5126. var updateVersion = function (event) {
  5127. // the version is not yet in the DB or we need to update it
  5128. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5129. };
  5130. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5131. };
  5132. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5133. var _this = this;
  5134. if (this.isSupported) {
  5135. var version;
  5136. try {
  5137. var transaction = this.db.transaction(["versions"]);
  5138. transaction.oncomplete = function (event) {
  5139. if (version) {
  5140. // If the version in the JSON file is > than the version in DB
  5141. if (_this.manifestVersionFound > version.data) {
  5142. _this.mustUpdateRessources = true;
  5143. updateInDBCallback();
  5144. }
  5145. else {
  5146. callback(version.data);
  5147. }
  5148. }
  5149. else {
  5150. _this.mustUpdateRessources = true;
  5151. updateInDBCallback();
  5152. }
  5153. };
  5154. transaction.onabort = function (event) {
  5155. callback(-1);
  5156. };
  5157. var getRequest = transaction.objectStore("versions").get(url);
  5158. getRequest.onsuccess = function (event) {
  5159. version = (event.target).result;
  5160. };
  5161. getRequest.onerror = function (event) {
  5162. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5163. callback(-1);
  5164. };
  5165. }
  5166. catch (ex) {
  5167. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5168. callback(-1);
  5169. }
  5170. }
  5171. else {
  5172. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5173. callback(-1);
  5174. }
  5175. };
  5176. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5177. var _this = this;
  5178. if (this.isSupported && !this.hasReachedQuota) {
  5179. try {
  5180. // Open a transaction to the database
  5181. var transaction = this.db.transaction(["versions"], "readwrite");
  5182. // the transaction could abort because of a QuotaExceededError error
  5183. transaction.onabort = function (event) {
  5184. try {
  5185. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5186. _this.hasReachedQuota = true;
  5187. }
  5188. }
  5189. catch (ex) { }
  5190. callback(-1);
  5191. };
  5192. transaction.oncomplete = function (event) {
  5193. callback(_this.manifestVersionFound);
  5194. };
  5195. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5196. // Put the scene into the database
  5197. var addRequest = transaction.objectStore("versions").put(newVersion);
  5198. addRequest.onsuccess = function (event) {
  5199. };
  5200. addRequest.onerror = function (event) {
  5201. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5202. };
  5203. }
  5204. catch (ex) {
  5205. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5206. callback(-1);
  5207. }
  5208. }
  5209. else {
  5210. callback(-1);
  5211. }
  5212. };
  5213. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5214. var _this = this;
  5215. var completeUrl = Database.ReturnFullUrlLocation(url);
  5216. var saveAndLoadFile = function (event) {
  5217. // the scene is not yet in the DB, let's try to save it
  5218. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5219. };
  5220. this._checkVersionFromDB(completeUrl, function (version) {
  5221. if (version !== -1) {
  5222. if (!_this.mustUpdateRessources) {
  5223. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5224. }
  5225. else {
  5226. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5227. }
  5228. }
  5229. else {
  5230. errorCallback();
  5231. }
  5232. });
  5233. };
  5234. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5235. if (this.isSupported) {
  5236. var targetStore;
  5237. if (url.indexOf(".babylon") !== -1) {
  5238. targetStore = "scenes";
  5239. }
  5240. else {
  5241. targetStore = "textures";
  5242. }
  5243. var file;
  5244. var transaction = this.db.transaction([targetStore]);
  5245. transaction.oncomplete = function (event) {
  5246. if (file) {
  5247. callback(file.data);
  5248. }
  5249. else {
  5250. notInDBCallback();
  5251. }
  5252. };
  5253. transaction.onabort = function (event) {
  5254. notInDBCallback();
  5255. };
  5256. var getRequest = transaction.objectStore(targetStore).get(url);
  5257. getRequest.onsuccess = function (event) {
  5258. file = (event.target).result;
  5259. };
  5260. getRequest.onerror = function (event) {
  5261. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5262. notInDBCallback();
  5263. };
  5264. }
  5265. else {
  5266. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5267. callback();
  5268. }
  5269. };
  5270. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5271. var _this = this;
  5272. if (this.isSupported) {
  5273. var targetStore;
  5274. if (url.indexOf(".babylon") !== -1) {
  5275. targetStore = "scenes";
  5276. }
  5277. else {
  5278. targetStore = "textures";
  5279. }
  5280. // Create XHR
  5281. var xhr = new XMLHttpRequest(), fileData;
  5282. xhr.open("GET", url, true);
  5283. if (useArrayBuffer) {
  5284. xhr.responseType = "arraybuffer";
  5285. }
  5286. xhr.onprogress = progressCallback;
  5287. xhr.addEventListener("load", function () {
  5288. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5289. // Blob as response (XHR2)
  5290. //fileData = xhr.responseText;
  5291. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5292. if (!_this.hasReachedQuota) {
  5293. // Open a transaction to the database
  5294. var transaction = _this.db.transaction([targetStore], "readwrite");
  5295. // the transaction could abort because of a QuotaExceededError error
  5296. transaction.onabort = function (event) {
  5297. try {
  5298. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5299. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5300. _this.hasReachedQuota = true;
  5301. }
  5302. }
  5303. catch (ex) { }
  5304. callback(fileData);
  5305. };
  5306. transaction.oncomplete = function (event) {
  5307. callback(fileData);
  5308. };
  5309. var newFile;
  5310. if (targetStore === "scenes") {
  5311. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5312. }
  5313. else {
  5314. newFile = { textureUrl: url, data: fileData };
  5315. }
  5316. try {
  5317. // Put the scene into the database
  5318. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5319. addRequest.onsuccess = function (event) {
  5320. };
  5321. addRequest.onerror = function (event) {
  5322. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5323. };
  5324. }
  5325. catch (ex) {
  5326. callback(fileData);
  5327. }
  5328. }
  5329. else {
  5330. callback(fileData);
  5331. }
  5332. }
  5333. else {
  5334. callback();
  5335. }
  5336. }, false);
  5337. xhr.addEventListener("error", function (event) {
  5338. BABYLON.Tools.Error("error on XHR request.");
  5339. callback();
  5340. }, false);
  5341. xhr.send();
  5342. }
  5343. else {
  5344. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5345. callback();
  5346. }
  5347. };
  5348. return Database;
  5349. }());
  5350. Database.IsUASupportingBlobStorage = true;
  5351. Database.IDBStorageEnabled = true;
  5352. Database.parseURL = function (url) {
  5353. var a = document.createElement('a');
  5354. a.href = url;
  5355. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5356. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5357. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5358. return absLocation;
  5359. };
  5360. Database.ReturnFullUrlLocation = function (url) {
  5361. if (url.indexOf("http:/") === -1) {
  5362. return (Database.parseURL(window.location.href) + url);
  5363. }
  5364. else {
  5365. return url;
  5366. }
  5367. };
  5368. BABYLON.Database = Database;
  5369. })(BABYLON || (BABYLON = {}));
  5370. //# sourceMappingURL=babylon.database.js.map
  5371. var BABYLON;
  5372. (function (BABYLON) {
  5373. var Internals;
  5374. (function (Internals) {
  5375. /*
  5376. * Based on jsTGALoader - Javascript loader for TGA file
  5377. * By Vincent Thibault
  5378. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5379. */
  5380. var TGATools = (function () {
  5381. function TGATools() {
  5382. }
  5383. TGATools.GetTGAHeader = function (data) {
  5384. var offset = 0;
  5385. var header = {
  5386. id_length: data[offset++],
  5387. colormap_type: data[offset++],
  5388. image_type: data[offset++],
  5389. colormap_index: data[offset++] | data[offset++] << 8,
  5390. colormap_length: data[offset++] | data[offset++] << 8,
  5391. colormap_size: data[offset++],
  5392. origin: [
  5393. data[offset++] | data[offset++] << 8,
  5394. data[offset++] | data[offset++] << 8
  5395. ],
  5396. width: data[offset++] | data[offset++] << 8,
  5397. height: data[offset++] | data[offset++] << 8,
  5398. pixel_size: data[offset++],
  5399. flags: data[offset++]
  5400. };
  5401. return header;
  5402. };
  5403. TGATools.UploadContent = function (gl, data) {
  5404. // Not enough data to contain header ?
  5405. if (data.length < 19) {
  5406. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5407. return;
  5408. }
  5409. // Read Header
  5410. var offset = 18;
  5411. var header = TGATools.GetTGAHeader(data);
  5412. // Assume it's a valid Targa file.
  5413. if (header.id_length + offset > data.length) {
  5414. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5415. return;
  5416. }
  5417. // Skip not needed data
  5418. offset += header.id_length;
  5419. var use_rle = false;
  5420. var use_pal = false;
  5421. var use_rgb = false;
  5422. var use_grey = false;
  5423. // Get some informations.
  5424. switch (header.image_type) {
  5425. case TGATools._TYPE_RLE_INDEXED:
  5426. use_rle = true;
  5427. case TGATools._TYPE_INDEXED:
  5428. use_pal = true;
  5429. break;
  5430. case TGATools._TYPE_RLE_RGB:
  5431. use_rle = true;
  5432. case TGATools._TYPE_RGB:
  5433. use_rgb = true;
  5434. break;
  5435. case TGATools._TYPE_RLE_GREY:
  5436. use_rle = true;
  5437. case TGATools._TYPE_GREY:
  5438. use_grey = true;
  5439. break;
  5440. }
  5441. var pixel_data;
  5442. var numAlphaBits = header.flags & 0xf;
  5443. var pixel_size = header.pixel_size >> 3;
  5444. var pixel_total = header.width * header.height * pixel_size;
  5445. // Read palettes
  5446. var palettes;
  5447. if (use_pal) {
  5448. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5449. }
  5450. // Read LRE
  5451. if (use_rle) {
  5452. pixel_data = new Uint8Array(pixel_total);
  5453. var c, count, i;
  5454. var localOffset = 0;
  5455. var pixels = new Uint8Array(pixel_size);
  5456. while (offset < pixel_total && localOffset < pixel_total) {
  5457. c = data[offset++];
  5458. count = (c & 0x7f) + 1;
  5459. // RLE pixels
  5460. if (c & 0x80) {
  5461. // Bind pixel tmp array
  5462. for (i = 0; i < pixel_size; ++i) {
  5463. pixels[i] = data[offset++];
  5464. }
  5465. // Copy pixel array
  5466. for (i = 0; i < count; ++i) {
  5467. pixel_data.set(pixels, localOffset + i * pixel_size);
  5468. }
  5469. localOffset += pixel_size * count;
  5470. }
  5471. else {
  5472. count *= pixel_size;
  5473. for (i = 0; i < count; ++i) {
  5474. pixel_data[localOffset + i] = data[offset++];
  5475. }
  5476. localOffset += count;
  5477. }
  5478. }
  5479. }
  5480. else {
  5481. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5482. }
  5483. // Load to texture
  5484. var x_start, y_start, x_step, y_step, y_end, x_end;
  5485. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5486. default:
  5487. case TGATools._ORIGIN_UL:
  5488. x_start = 0;
  5489. x_step = 1;
  5490. x_end = header.width;
  5491. y_start = 0;
  5492. y_step = 1;
  5493. y_end = header.height;
  5494. break;
  5495. case TGATools._ORIGIN_BL:
  5496. x_start = 0;
  5497. x_step = 1;
  5498. x_end = header.width;
  5499. y_start = header.height - 1;
  5500. y_step = -1;
  5501. y_end = -1;
  5502. break;
  5503. case TGATools._ORIGIN_UR:
  5504. x_start = header.width - 1;
  5505. x_step = -1;
  5506. x_end = -1;
  5507. y_start = 0;
  5508. y_step = 1;
  5509. y_end = header.height;
  5510. break;
  5511. case TGATools._ORIGIN_BR:
  5512. x_start = header.width - 1;
  5513. x_step = -1;
  5514. x_end = -1;
  5515. y_start = header.height - 1;
  5516. y_step = -1;
  5517. y_end = -1;
  5518. break;
  5519. }
  5520. // Load the specify method
  5521. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5522. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5523. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5524. };
  5525. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5526. var image = pixel_data, colormap = palettes;
  5527. var width = header.width, height = header.height;
  5528. var color, i = 0, x, y;
  5529. var imageData = new Uint8Array(width * height * 4);
  5530. for (y = y_start; y !== y_end; y += y_step) {
  5531. for (x = x_start; x !== x_end; x += x_step, i++) {
  5532. color = image[i];
  5533. imageData[(x + width * y) * 4 + 3] = 255;
  5534. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5535. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5536. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5537. }
  5538. }
  5539. return imageData;
  5540. };
  5541. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5542. var image = pixel_data;
  5543. var width = header.width, height = header.height;
  5544. var color, i = 0, x, y;
  5545. var imageData = new Uint8Array(width * height * 4);
  5546. for (y = y_start; y !== y_end; y += y_step) {
  5547. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5548. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5549. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5550. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5551. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5552. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5553. }
  5554. }
  5555. return imageData;
  5556. };
  5557. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5558. var image = pixel_data;
  5559. var width = header.width, height = header.height;
  5560. var i = 0, x, y;
  5561. var imageData = new Uint8Array(width * height * 4);
  5562. for (y = y_start; y !== y_end; y += y_step) {
  5563. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5564. imageData[(x + width * y) * 4 + 3] = 255;
  5565. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5566. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5567. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5568. }
  5569. }
  5570. return imageData;
  5571. };
  5572. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5573. var image = pixel_data;
  5574. var width = header.width, height = header.height;
  5575. var i = 0, x, y;
  5576. var imageData = new Uint8Array(width * height * 4);
  5577. for (y = y_start; y !== y_end; y += y_step) {
  5578. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5579. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5580. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5581. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5582. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5583. }
  5584. }
  5585. return imageData;
  5586. };
  5587. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5588. var image = pixel_data;
  5589. var width = header.width, height = header.height;
  5590. var color, i = 0, x, y;
  5591. var imageData = new Uint8Array(width * height * 4);
  5592. for (y = y_start; y !== y_end; y += y_step) {
  5593. for (x = x_start; x !== x_end; x += x_step, i++) {
  5594. color = image[i];
  5595. imageData[(x + width * y) * 4 + 0] = color;
  5596. imageData[(x + width * y) * 4 + 1] = color;
  5597. imageData[(x + width * y) * 4 + 2] = color;
  5598. imageData[(x + width * y) * 4 + 3] = 255;
  5599. }
  5600. }
  5601. return imageData;
  5602. };
  5603. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5604. var image = pixel_data;
  5605. var width = header.width, height = header.height;
  5606. var i = 0, x, y;
  5607. var imageData = new Uint8Array(width * height * 4);
  5608. for (y = y_start; y !== y_end; y += y_step) {
  5609. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5610. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5611. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5612. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5613. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5614. }
  5615. }
  5616. return imageData;
  5617. };
  5618. return TGATools;
  5619. }());
  5620. TGATools._TYPE_NO_DATA = 0;
  5621. TGATools._TYPE_INDEXED = 1;
  5622. TGATools._TYPE_RGB = 2;
  5623. TGATools._TYPE_GREY = 3;
  5624. TGATools._TYPE_RLE_INDEXED = 9;
  5625. TGATools._TYPE_RLE_RGB = 10;
  5626. TGATools._TYPE_RLE_GREY = 11;
  5627. TGATools._ORIGIN_MASK = 0x30;
  5628. TGATools._ORIGIN_SHIFT = 0x04;
  5629. TGATools._ORIGIN_BL = 0x00;
  5630. TGATools._ORIGIN_BR = 0x01;
  5631. TGATools._ORIGIN_UL = 0x02;
  5632. TGATools._ORIGIN_UR = 0x03;
  5633. Internals.TGATools = TGATools;
  5634. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5635. })(BABYLON || (BABYLON = {}));
  5636. //# sourceMappingURL=babylon.tools.tga.js.map
  5637. var BABYLON;
  5638. (function (BABYLON) {
  5639. var SmartArray = (function () {
  5640. function SmartArray(capacity) {
  5641. this.length = 0;
  5642. this._duplicateId = 0;
  5643. this.data = new Array(capacity);
  5644. this._id = SmartArray._GlobalId++;
  5645. }
  5646. SmartArray.prototype.push = function (value) {
  5647. this.data[this.length++] = value;
  5648. if (this.length > this.data.length) {
  5649. this.data.length *= 2;
  5650. }
  5651. if (!value.__smartArrayFlags) {
  5652. value.__smartArrayFlags = {};
  5653. }
  5654. value.__smartArrayFlags[this._id] = this._duplicateId;
  5655. };
  5656. SmartArray.prototype.pushNoDuplicate = function (value) {
  5657. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5658. return false;
  5659. }
  5660. this.push(value);
  5661. return true;
  5662. };
  5663. SmartArray.prototype.sort = function (compareFn) {
  5664. this.data.sort(compareFn);
  5665. };
  5666. SmartArray.prototype.reset = function () {
  5667. this.length = 0;
  5668. this._duplicateId++;
  5669. };
  5670. SmartArray.prototype.concat = function (array) {
  5671. if (array.length === 0) {
  5672. return;
  5673. }
  5674. if (this.length + array.length > this.data.length) {
  5675. this.data.length = (this.length + array.length) * 2;
  5676. }
  5677. for (var index = 0; index < array.length; index++) {
  5678. this.data[this.length++] = (array.data || array)[index];
  5679. }
  5680. };
  5681. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5682. if (array.length === 0) {
  5683. return;
  5684. }
  5685. if (this.length + array.length > this.data.length) {
  5686. this.data.length = (this.length + array.length) * 2;
  5687. }
  5688. for (var index = 0; index < array.length; index++) {
  5689. var item = (array.data || array)[index];
  5690. this.pushNoDuplicate(item);
  5691. }
  5692. };
  5693. SmartArray.prototype.indexOf = function (value) {
  5694. var position = this.data.indexOf(value);
  5695. if (position >= this.length) {
  5696. return -1;
  5697. }
  5698. return position;
  5699. };
  5700. return SmartArray;
  5701. }());
  5702. // Statics
  5703. SmartArray._GlobalId = 0;
  5704. BABYLON.SmartArray = SmartArray;
  5705. })(BABYLON || (BABYLON = {}));
  5706. //# sourceMappingURL=babylon.smartArray.js.map
  5707. var BABYLON;
  5708. (function (BABYLON) {
  5709. /**
  5710. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5711. * The underlying implementation relies on an associative array to ensure the best performances.
  5712. * The value can be anything including 'null' but except 'undefined'
  5713. */
  5714. var StringDictionary = (function () {
  5715. function StringDictionary() {
  5716. this._count = 0;
  5717. this._data = {};
  5718. }
  5719. /**
  5720. * This will clear this dictionary and copy the content from the 'source' one.
  5721. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5722. * @param source the dictionary to take the content from and copy to this dictionary
  5723. */
  5724. StringDictionary.prototype.copyFrom = function (source) {
  5725. var _this = this;
  5726. this.clear();
  5727. source.forEach(function (t, v) { return _this.add(t, v); });
  5728. };
  5729. /**
  5730. * Get a value based from its key
  5731. * @param key the given key to get the matching value from
  5732. * @return the value if found, otherwise undefined is returned
  5733. */
  5734. StringDictionary.prototype.get = function (key) {
  5735. var val = this._data[key];
  5736. if (val !== undefined) {
  5737. return val;
  5738. }
  5739. return undefined;
  5740. };
  5741. /**
  5742. * Get a value from its key or add it if it doesn't exist.
  5743. * This method will ensure you that a given key/data will be present in the dictionary.
  5744. * @param key the given key to get the matching value from
  5745. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5746. * The factory will only be invoked if there's no data for the given key.
  5747. * @return the value corresponding to the key.
  5748. */
  5749. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5750. var val = this.get(key);
  5751. if (val !== undefined) {
  5752. return val;
  5753. }
  5754. val = factory(key);
  5755. if (val) {
  5756. this.add(key, val);
  5757. }
  5758. return val;
  5759. };
  5760. /**
  5761. * Get a value from its key if present in the dictionary otherwise add it
  5762. * @param key the key to get the value from
  5763. * @param val if there's no such key/value pair in the dictionary add it with this value
  5764. * @return the value corresponding to the key
  5765. */
  5766. StringDictionary.prototype.getOrAdd = function (key, val) {
  5767. var curVal = this.get(key);
  5768. if (curVal !== undefined) {
  5769. return curVal;
  5770. }
  5771. this.add(key, val);
  5772. return val;
  5773. };
  5774. /**
  5775. * Check if there's a given key in the dictionary
  5776. * @param key the key to check for
  5777. * @return true if the key is present, false otherwise
  5778. */
  5779. StringDictionary.prototype.contains = function (key) {
  5780. return this._data[key] !== undefined;
  5781. };
  5782. /**
  5783. * Add a new key and its corresponding value
  5784. * @param key the key to add
  5785. * @param value the value corresponding to the key
  5786. * @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
  5787. */
  5788. StringDictionary.prototype.add = function (key, value) {
  5789. if (this._data[key] !== undefined) {
  5790. return false;
  5791. }
  5792. this._data[key] = value;
  5793. ++this._count;
  5794. return true;
  5795. };
  5796. StringDictionary.prototype.set = function (key, value) {
  5797. if (this._data[key] === undefined) {
  5798. return false;
  5799. }
  5800. this._data[key] = value;
  5801. return true;
  5802. };
  5803. /**
  5804. * Get the element of the given key and remove it from the dictionary
  5805. * @param key
  5806. */
  5807. StringDictionary.prototype.getAndRemove = function (key) {
  5808. var val = this.get(key);
  5809. if (val !== undefined) {
  5810. delete this._data[key];
  5811. --this._count;
  5812. return val;
  5813. }
  5814. return null;
  5815. };
  5816. /**
  5817. * Remove a key/value from the dictionary.
  5818. * @param key the key to remove
  5819. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5820. */
  5821. StringDictionary.prototype.remove = function (key) {
  5822. if (this.contains(key)) {
  5823. delete this._data[key];
  5824. --this._count;
  5825. return true;
  5826. }
  5827. return false;
  5828. };
  5829. /**
  5830. * Clear the whole content of the dictionary
  5831. */
  5832. StringDictionary.prototype.clear = function () {
  5833. this._data = {};
  5834. this._count = 0;
  5835. };
  5836. Object.defineProperty(StringDictionary.prototype, "count", {
  5837. get: function () {
  5838. return this._count;
  5839. },
  5840. enumerable: true,
  5841. configurable: true
  5842. });
  5843. /**
  5844. * Execute a callback on each key/val of the dictionary.
  5845. * Note that you can remove any element in this dictionary in the callback implementation
  5846. * @param callback the callback to execute on a given key/value pair
  5847. */
  5848. StringDictionary.prototype.forEach = function (callback) {
  5849. for (var cur in this._data) {
  5850. var val = this._data[cur];
  5851. callback(cur, val);
  5852. }
  5853. };
  5854. /**
  5855. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5856. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5857. * Note that you can remove any element in this dictionary in the callback implementation
  5858. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5859. */
  5860. StringDictionary.prototype.first = function (callback) {
  5861. for (var cur in this._data) {
  5862. var val = this._data[cur];
  5863. var res = callback(cur, val);
  5864. if (res) {
  5865. return res;
  5866. }
  5867. }
  5868. return null;
  5869. };
  5870. return StringDictionary;
  5871. }());
  5872. BABYLON.StringDictionary = StringDictionary;
  5873. })(BABYLON || (BABYLON = {}));
  5874. //# sourceMappingURL=babylon.stringDictionary.js.map
  5875. var BABYLON;
  5876. (function (BABYLON) {
  5877. // Screenshots
  5878. var screenshotCanvas;
  5879. var cloneValue = function (source, destinationObject) {
  5880. if (!source)
  5881. return null;
  5882. if (source instanceof BABYLON.Mesh) {
  5883. return null;
  5884. }
  5885. if (source instanceof BABYLON.SubMesh) {
  5886. return source.clone(destinationObject);
  5887. }
  5888. else if (source.clone) {
  5889. return source.clone();
  5890. }
  5891. return null;
  5892. };
  5893. var Tools = (function () {
  5894. function Tools() {
  5895. }
  5896. ;
  5897. Tools.Instantiate = function (className) {
  5898. var arr = className.split(".");
  5899. var fn = (window || this);
  5900. for (var i = 0, len = arr.length; i < len; i++) {
  5901. fn = fn[arr[i]];
  5902. }
  5903. if (typeof fn !== "function") {
  5904. return null;
  5905. }
  5906. return fn;
  5907. };
  5908. Tools.SetImmediate = function (action) {
  5909. if (window.setImmediate) {
  5910. window.setImmediate(action);
  5911. }
  5912. else {
  5913. setTimeout(action, 1);
  5914. }
  5915. };
  5916. Tools.IsExponentOfTwo = function (value) {
  5917. var count = 1;
  5918. do {
  5919. count *= 2;
  5920. } while (count < value);
  5921. return count === value;
  5922. };
  5923. Tools.GetExponentOfTwo = function (value, max) {
  5924. var count = 1;
  5925. do {
  5926. count *= 2;
  5927. } while (count < value);
  5928. if (count > max)
  5929. count = max;
  5930. return count;
  5931. };
  5932. Tools.GetFilename = function (path) {
  5933. var index = path.lastIndexOf("/");
  5934. if (index < 0)
  5935. return path;
  5936. return path.substring(index + 1);
  5937. };
  5938. Tools.GetDOMTextContent = function (element) {
  5939. var result = "";
  5940. var child = element.firstChild;
  5941. while (child) {
  5942. if (child.nodeType === 3) {
  5943. result += child.textContent;
  5944. }
  5945. child = child.nextSibling;
  5946. }
  5947. return result;
  5948. };
  5949. Tools.ToDegrees = function (angle) {
  5950. return angle * 180 / Math.PI;
  5951. };
  5952. Tools.ToRadians = function (angle) {
  5953. return angle * Math.PI / 180;
  5954. };
  5955. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5956. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5957. var output = "";
  5958. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5959. var i = 0;
  5960. var bytes = new Uint8Array(buffer);
  5961. while (i < bytes.length) {
  5962. chr1 = bytes[i++];
  5963. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5964. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5965. enc1 = chr1 >> 2;
  5966. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5967. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5968. enc4 = chr3 & 63;
  5969. if (isNaN(chr2)) {
  5970. enc3 = enc4 = 64;
  5971. }
  5972. else if (isNaN(chr3)) {
  5973. enc4 = 64;
  5974. }
  5975. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5976. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5977. }
  5978. return "data:image/png;base64," + output;
  5979. };
  5980. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5981. if (bias === void 0) { bias = null; }
  5982. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5983. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5984. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5985. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5986. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5987. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5988. }
  5989. if (bias) {
  5990. minimum.x -= minimum.x * bias.x + bias.y;
  5991. minimum.y -= minimum.y * bias.x + bias.y;
  5992. minimum.z -= minimum.z * bias.x + bias.y;
  5993. maximum.x += maximum.x * bias.x + bias.y;
  5994. maximum.y += maximum.y * bias.x + bias.y;
  5995. maximum.z += maximum.z * bias.x + bias.y;
  5996. }
  5997. return {
  5998. minimum: minimum,
  5999. maximum: maximum
  6000. };
  6001. };
  6002. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6003. if (bias === void 0) { bias = null; }
  6004. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6005. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6006. if (!stride) {
  6007. stride = 3;
  6008. }
  6009. for (var index = start; index < start + count; index++) {
  6010. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6011. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6012. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6013. }
  6014. if (bias) {
  6015. minimum.x -= minimum.x * bias.x + bias.y;
  6016. minimum.y -= minimum.y * bias.x + bias.y;
  6017. minimum.z -= minimum.z * bias.x + bias.y;
  6018. maximum.x += maximum.x * bias.x + bias.y;
  6019. maximum.y += maximum.y * bias.x + bias.y;
  6020. maximum.z += maximum.z * bias.x + bias.y;
  6021. }
  6022. return {
  6023. minimum: minimum,
  6024. maximum: maximum
  6025. };
  6026. };
  6027. Tools.Vector2ArrayFeeder = function (array) {
  6028. return function (index) {
  6029. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6030. var length = isFloatArray ? array.length / 2 : array.length;
  6031. if (index >= length) {
  6032. return null;
  6033. }
  6034. if (isFloatArray) {
  6035. var fa = array;
  6036. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6037. }
  6038. var a = array;
  6039. return a[index];
  6040. };
  6041. };
  6042. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6043. if (bias === void 0) { bias = null; }
  6044. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6045. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6046. var i = 0;
  6047. var cur = feeder(i++);
  6048. while (cur) {
  6049. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6050. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6051. cur = feeder(i++);
  6052. }
  6053. if (bias) {
  6054. minimum.x -= minimum.x * bias.x + bias.y;
  6055. minimum.y -= minimum.y * bias.x + bias.y;
  6056. maximum.x += maximum.x * bias.x + bias.y;
  6057. maximum.y += maximum.y * bias.x + bias.y;
  6058. }
  6059. return {
  6060. minimum: minimum,
  6061. maximum: maximum
  6062. };
  6063. };
  6064. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6065. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6066. return undefined;
  6067. return Array.isArray(obj) ? obj : [obj];
  6068. };
  6069. // Misc.
  6070. Tools.GetPointerPrefix = function () {
  6071. var eventPrefix = "pointer";
  6072. // Check if pointer events are supported
  6073. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6074. eventPrefix = "mouse";
  6075. }
  6076. return eventPrefix;
  6077. };
  6078. /**
  6079. * @param func - the function to be called
  6080. * @param requester - the object that will request the next frame. Falls back to window.
  6081. */
  6082. Tools.QueueNewFrame = function (func, requester) {
  6083. if (requester === void 0) { requester = window; }
  6084. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6085. /*if(requester.isPresenting) {
  6086. return;
  6087. } else*/ if (requester.requestAnimationFrame)
  6088. requester.requestAnimationFrame(func);
  6089. else if (requester.msRequestAnimationFrame)
  6090. requester.msRequestAnimationFrame(func);
  6091. else if (requester.webkitRequestAnimationFrame)
  6092. requester.webkitRequestAnimationFrame(func);
  6093. else if (requester.mozRequestAnimationFrame)
  6094. requester.mozRequestAnimationFrame(func);
  6095. else if (requester.oRequestAnimationFrame)
  6096. requester.oRequestAnimationFrame(func);
  6097. else {
  6098. window.setTimeout(func, 16);
  6099. }
  6100. };
  6101. Tools.RequestFullscreen = function (element) {
  6102. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6103. if (!requestFunction)
  6104. return;
  6105. requestFunction.call(element);
  6106. };
  6107. Tools.ExitFullscreen = function () {
  6108. if (document.exitFullscreen) {
  6109. document.exitFullscreen();
  6110. }
  6111. else if (document.mozCancelFullScreen) {
  6112. document.mozCancelFullScreen();
  6113. }
  6114. else if (document.webkitCancelFullScreen) {
  6115. document.webkitCancelFullScreen();
  6116. }
  6117. else if (document.msCancelFullScreen) {
  6118. document.msCancelFullScreen();
  6119. }
  6120. };
  6121. Tools.SetCorsBehavior = function (url, img) {
  6122. if (Tools.CorsBehavior) {
  6123. switch (typeof (Tools.CorsBehavior)) {
  6124. case "function":
  6125. var result = Tools.CorsBehavior(url);
  6126. if (result) {
  6127. return result;
  6128. }
  6129. break;
  6130. case "string":
  6131. default:
  6132. img.crossOrigin = Tools.CorsBehavior;
  6133. break;
  6134. }
  6135. }
  6136. };
  6137. // External files
  6138. Tools.CleanUrl = function (url) {
  6139. url = url.replace(/#/mg, "%23");
  6140. return url;
  6141. };
  6142. Tools.LoadImage = function (url, onload, onerror, database) {
  6143. if (url instanceof ArrayBuffer) {
  6144. url = Tools.EncodeArrayBufferTobase64(url);
  6145. }
  6146. url = Tools.CleanUrl(url);
  6147. var img = new Image();
  6148. if (url.substr(0, 5) !== "data:") {
  6149. Tools.SetCorsBehavior(url, img);
  6150. }
  6151. img.onload = function () {
  6152. onload(img);
  6153. };
  6154. img.onerror = function (err) {
  6155. Tools.Error("Error while trying to load image: " + url);
  6156. if (Tools.UseFallbackTexture) {
  6157. img.src = Tools.fallbackTexture;
  6158. onload(img);
  6159. }
  6160. else {
  6161. onerror();
  6162. }
  6163. };
  6164. var noIndexedDB = function () {
  6165. img.src = url;
  6166. };
  6167. var loadFromIndexedDB = function () {
  6168. database.loadImageFromDB(url, img);
  6169. };
  6170. //ANY database to do!
  6171. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6172. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6173. }
  6174. else {
  6175. if (url.indexOf("file:") === -1) {
  6176. noIndexedDB();
  6177. }
  6178. else {
  6179. var textureName = url.substring(5).toLowerCase();
  6180. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6181. try {
  6182. var blobURL;
  6183. try {
  6184. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6185. }
  6186. catch (ex) {
  6187. // Chrome doesn't support oneTimeOnly parameter
  6188. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6189. }
  6190. img.src = blobURL;
  6191. }
  6192. catch (e) {
  6193. img.src = null;
  6194. }
  6195. }
  6196. else {
  6197. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6198. img.src = Tools.fallbackTexture;
  6199. }
  6200. }
  6201. }
  6202. return img;
  6203. };
  6204. //ANY
  6205. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6206. url = Tools.CleanUrl(url);
  6207. var noIndexedDB = function () {
  6208. var request = new XMLHttpRequest();
  6209. var loadUrl = Tools.BaseUrl + url;
  6210. request.open('GET', loadUrl, true);
  6211. if (useArrayBuffer) {
  6212. request.responseType = "arraybuffer";
  6213. }
  6214. request.onprogress = progressCallBack;
  6215. request.onreadystatechange = function () {
  6216. if (request.readyState === 4) {
  6217. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6218. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6219. callback(!useArrayBuffer ? request.responseText : request.response);
  6220. }
  6221. else {
  6222. if (onError) {
  6223. onError();
  6224. }
  6225. else {
  6226. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6227. }
  6228. }
  6229. }
  6230. };
  6231. request.send(null);
  6232. };
  6233. var loadFromIndexedDB = function () {
  6234. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6235. };
  6236. if (url.indexOf("file:") !== -1) {
  6237. var fileName = url.substring(5).toLowerCase();
  6238. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6239. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6240. }
  6241. else {
  6242. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6243. }
  6244. }
  6245. else {
  6246. // Caching all files
  6247. if (database && database.enableSceneOffline) {
  6248. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6249. }
  6250. else {
  6251. noIndexedDB();
  6252. }
  6253. }
  6254. };
  6255. /**
  6256. * Load a script (identified by an url). When the url returns, the
  6257. * content of this file is added into a new script element, attached to the DOM (body element)
  6258. */
  6259. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6260. var head = document.getElementsByTagName('head')[0];
  6261. var script = document.createElement('script');
  6262. script.type = 'text/javascript';
  6263. script.src = scriptUrl;
  6264. var self = this;
  6265. script.onload = function () {
  6266. if (onSuccess) {
  6267. onSuccess();
  6268. }
  6269. };
  6270. script.onerror = function () {
  6271. if (onError) {
  6272. onError();
  6273. }
  6274. };
  6275. head.appendChild(script);
  6276. };
  6277. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6278. var reader = new FileReader();
  6279. reader.onload = function (e) {
  6280. //target doesn't have result from ts 1.3
  6281. callback(e.target['result']);
  6282. };
  6283. reader.onprogress = progressCallback;
  6284. reader.readAsDataURL(fileToLoad);
  6285. };
  6286. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6287. var reader = new FileReader();
  6288. reader.onerror = function (e) {
  6289. Tools.Log("Error while reading file: " + fileToLoad.name);
  6290. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6291. };
  6292. reader.onload = function (e) {
  6293. //target doesn't have result from ts 1.3
  6294. callback(e.target['result']);
  6295. };
  6296. reader.onprogress = progressCallBack;
  6297. if (!useArrayBuffer) {
  6298. // Asynchronous read
  6299. reader.readAsText(fileToLoad);
  6300. }
  6301. else {
  6302. reader.readAsArrayBuffer(fileToLoad);
  6303. }
  6304. };
  6305. //returns a downloadable url to a file content.
  6306. Tools.FileAsURL = function (content) {
  6307. var fileBlob = new Blob([content]);
  6308. var url = window.URL || window.webkitURL;
  6309. var link = url.createObjectURL(fileBlob);
  6310. return link;
  6311. };
  6312. // Misc.
  6313. Tools.Format = function (value, decimals) {
  6314. if (decimals === void 0) { decimals = 2; }
  6315. return value.toFixed(decimals);
  6316. };
  6317. Tools.CheckExtends = function (v, min, max) {
  6318. if (v.x < min.x)
  6319. min.x = v.x;
  6320. if (v.y < min.y)
  6321. min.y = v.y;
  6322. if (v.z < min.z)
  6323. min.z = v.z;
  6324. if (v.x > max.x)
  6325. max.x = v.x;
  6326. if (v.y > max.y)
  6327. max.y = v.y;
  6328. if (v.z > max.z)
  6329. max.z = v.z;
  6330. };
  6331. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6332. for (var prop in source) {
  6333. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6334. continue;
  6335. }
  6336. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6337. continue;
  6338. }
  6339. var sourceValue = source[prop];
  6340. var typeOfSourceValue = typeof sourceValue;
  6341. if (typeOfSourceValue === "function") {
  6342. continue;
  6343. }
  6344. if (typeOfSourceValue === "object") {
  6345. if (sourceValue instanceof Array) {
  6346. destination[prop] = [];
  6347. if (sourceValue.length > 0) {
  6348. if (typeof sourceValue[0] == "object") {
  6349. for (var index = 0; index < sourceValue.length; index++) {
  6350. var clonedValue = cloneValue(sourceValue[index], destination);
  6351. if (destination[prop].indexOf(clonedValue) === -1) {
  6352. destination[prop].push(clonedValue);
  6353. }
  6354. }
  6355. }
  6356. else {
  6357. destination[prop] = sourceValue.slice(0);
  6358. }
  6359. }
  6360. }
  6361. else {
  6362. destination[prop] = cloneValue(sourceValue, destination);
  6363. }
  6364. }
  6365. else {
  6366. destination[prop] = sourceValue;
  6367. }
  6368. }
  6369. };
  6370. Tools.IsEmpty = function (obj) {
  6371. for (var i in obj) {
  6372. return false;
  6373. }
  6374. return true;
  6375. };
  6376. Tools.RegisterTopRootEvents = function (events) {
  6377. for (var index = 0; index < events.length; index++) {
  6378. var event = events[index];
  6379. window.addEventListener(event.name, event.handler, false);
  6380. try {
  6381. if (window.parent) {
  6382. window.parent.addEventListener(event.name, event.handler, false);
  6383. }
  6384. }
  6385. catch (e) {
  6386. }
  6387. }
  6388. };
  6389. Tools.UnregisterTopRootEvents = function (events) {
  6390. for (var index = 0; index < events.length; index++) {
  6391. var event = events[index];
  6392. window.removeEventListener(event.name, event.handler);
  6393. try {
  6394. if (window.parent) {
  6395. window.parent.removeEventListener(event.name, event.handler);
  6396. }
  6397. }
  6398. catch (e) {
  6399. }
  6400. }
  6401. };
  6402. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6403. if (mimeType === void 0) { mimeType = "image/png"; }
  6404. // Read the contents of the framebuffer
  6405. var numberOfChannelsByLine = width * 4;
  6406. var halfHeight = height / 2;
  6407. //Reading datas from WebGL
  6408. var data = engine.readPixels(0, 0, width, height);
  6409. //To flip image on Y axis.
  6410. for (var i = 0; i < halfHeight; i++) {
  6411. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6412. var currentCell = j + i * numberOfChannelsByLine;
  6413. var targetLine = height - i - 1;
  6414. var targetCell = j + targetLine * numberOfChannelsByLine;
  6415. var temp = data[currentCell];
  6416. data[currentCell] = data[targetCell];
  6417. data[targetCell] = temp;
  6418. }
  6419. }
  6420. // Create a 2D canvas to store the result
  6421. if (!screenshotCanvas) {
  6422. screenshotCanvas = document.createElement('canvas');
  6423. }
  6424. screenshotCanvas.width = width;
  6425. screenshotCanvas.height = height;
  6426. var context = screenshotCanvas.getContext('2d');
  6427. // Copy the pixels to a 2D canvas
  6428. var imageData = context.createImageData(width, height);
  6429. var castData = (imageData.data);
  6430. castData.set(data);
  6431. context.putImageData(imageData, 0, 0);
  6432. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6433. };
  6434. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6435. if (mimeType === void 0) { mimeType = "image/png"; }
  6436. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6437. if (successCallback) {
  6438. successCallback(base64Image);
  6439. }
  6440. else {
  6441. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6442. if (("download" in document.createElement("a"))) {
  6443. var a = window.document.createElement("a");
  6444. a.href = base64Image;
  6445. var date = new Date();
  6446. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6447. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6448. window.document.body.appendChild(a);
  6449. a.addEventListener("click", function () {
  6450. a.parentElement.removeChild(a);
  6451. });
  6452. a.click();
  6453. }
  6454. else {
  6455. var newWindow = window.open("");
  6456. var img = newWindow.document.createElement("img");
  6457. img.src = base64Image;
  6458. newWindow.document.body.appendChild(img);
  6459. }
  6460. }
  6461. };
  6462. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6463. if (mimeType === void 0) { mimeType = "image/png"; }
  6464. var width;
  6465. var height;
  6466. // If a precision value is specified
  6467. if (size.precision) {
  6468. width = Math.round(engine.getRenderWidth() * size.precision);
  6469. height = Math.round(width / engine.getAspectRatio(camera));
  6470. }
  6471. else if (size.width && size.height) {
  6472. width = size.width;
  6473. height = size.height;
  6474. }
  6475. else if (size.width && !size.height) {
  6476. width = size.width;
  6477. height = Math.round(width / engine.getAspectRatio(camera));
  6478. }
  6479. else if (size.height && !size.width) {
  6480. height = size.height;
  6481. width = Math.round(height * engine.getAspectRatio(camera));
  6482. }
  6483. else if (!isNaN(size)) {
  6484. height = size;
  6485. width = size;
  6486. }
  6487. else {
  6488. Tools.Error("Invalid 'size' parameter !");
  6489. return;
  6490. }
  6491. if (!screenshotCanvas) {
  6492. screenshotCanvas = document.createElement('canvas');
  6493. }
  6494. screenshotCanvas.width = width;
  6495. screenshotCanvas.height = height;
  6496. var renderContext = screenshotCanvas.getContext("2d");
  6497. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6498. var newWidth = width;
  6499. var newHeight = newWidth / ratio;
  6500. if (newHeight > height) {
  6501. newHeight = height;
  6502. newWidth = newHeight * ratio;
  6503. }
  6504. var offsetX = Math.max(0, width - newWidth) / 2;
  6505. var offsetY = Math.max(0, height - newHeight) / 2;
  6506. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6507. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6508. };
  6509. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  6510. if (mimeType === void 0) { mimeType = "image/png"; }
  6511. var width;
  6512. var height;
  6513. //If a precision value is specified
  6514. if (size.precision) {
  6515. width = Math.round(engine.getRenderWidth() * size.precision);
  6516. height = Math.round(width / engine.getAspectRatio(camera));
  6517. size = { width: width, height: height };
  6518. }
  6519. else if (size.width && size.height) {
  6520. width = size.width;
  6521. height = size.height;
  6522. }
  6523. else if (size.width && !size.height) {
  6524. width = size.width;
  6525. height = Math.round(width / engine.getAspectRatio(camera));
  6526. size = { width: width, height: height };
  6527. }
  6528. else if (size.height && !size.width) {
  6529. height = size.height;
  6530. width = Math.round(height * engine.getAspectRatio(camera));
  6531. size = { width: width, height: height };
  6532. }
  6533. else if (!isNaN(size)) {
  6534. height = size;
  6535. width = size;
  6536. }
  6537. else {
  6538. Tools.Error("Invalid 'size' parameter !");
  6539. return;
  6540. }
  6541. var scene = camera.getScene();
  6542. var previousCamera = null;
  6543. if (scene.activeCamera !== camera) {
  6544. previousCamera = scene.activeCamera;
  6545. scene.activeCamera = camera;
  6546. }
  6547. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6548. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6549. texture.renderList = scene.meshes;
  6550. texture.onAfterRenderObservable.add(function () {
  6551. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6552. });
  6553. scene.incrementRenderId();
  6554. scene.resetCachedMaterial();
  6555. texture.render(true);
  6556. texture.dispose();
  6557. if (previousCamera) {
  6558. scene.activeCamera = previousCamera;
  6559. }
  6560. camera.getProjectionMatrix(true); // Force cache refresh;
  6561. };
  6562. // XHR response validator for local file scenario
  6563. Tools.ValidateXHRData = function (xhr, dataType) {
  6564. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6565. if (dataType === void 0) { dataType = 7; }
  6566. try {
  6567. if (dataType & 1) {
  6568. if (xhr.responseText && xhr.responseText.length > 0) {
  6569. return true;
  6570. }
  6571. else if (dataType === 1) {
  6572. return false;
  6573. }
  6574. }
  6575. if (dataType & 2) {
  6576. // Check header width and height since there is no "TGA" magic number
  6577. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6578. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6579. return true;
  6580. }
  6581. else if (dataType === 2) {
  6582. return false;
  6583. }
  6584. }
  6585. if (dataType & 4) {
  6586. // Check for the "DDS" magic number
  6587. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6588. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6589. return true;
  6590. }
  6591. else {
  6592. return false;
  6593. }
  6594. }
  6595. }
  6596. catch (e) {
  6597. }
  6598. return false;
  6599. };
  6600. /**
  6601. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6602. * Be aware Math.random() could cause collisions, but:
  6603. * "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"
  6604. */
  6605. Tools.RandomId = function () {
  6606. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6607. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6608. return v.toString(16);
  6609. });
  6610. };
  6611. Object.defineProperty(Tools, "NoneLogLevel", {
  6612. get: function () {
  6613. return Tools._NoneLogLevel;
  6614. },
  6615. enumerable: true,
  6616. configurable: true
  6617. });
  6618. Object.defineProperty(Tools, "MessageLogLevel", {
  6619. get: function () {
  6620. return Tools._MessageLogLevel;
  6621. },
  6622. enumerable: true,
  6623. configurable: true
  6624. });
  6625. Object.defineProperty(Tools, "WarningLogLevel", {
  6626. get: function () {
  6627. return Tools._WarningLogLevel;
  6628. },
  6629. enumerable: true,
  6630. configurable: true
  6631. });
  6632. Object.defineProperty(Tools, "ErrorLogLevel", {
  6633. get: function () {
  6634. return Tools._ErrorLogLevel;
  6635. },
  6636. enumerable: true,
  6637. configurable: true
  6638. });
  6639. Object.defineProperty(Tools, "AllLogLevel", {
  6640. get: function () {
  6641. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6642. },
  6643. enumerable: true,
  6644. configurable: true
  6645. });
  6646. Tools._AddLogEntry = function (entry) {
  6647. Tools._LogCache = entry + Tools._LogCache;
  6648. if (Tools.OnNewCacheEntry) {
  6649. Tools.OnNewCacheEntry(entry);
  6650. }
  6651. };
  6652. Tools._FormatMessage = function (message) {
  6653. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6654. var date = new Date();
  6655. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6656. };
  6657. Tools._LogDisabled = function (message) {
  6658. // nothing to do
  6659. };
  6660. Tools._LogEnabled = function (message) {
  6661. var formattedMessage = Tools._FormatMessage(message);
  6662. console.log("BJS - " + formattedMessage);
  6663. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6664. Tools._AddLogEntry(entry);
  6665. };
  6666. Tools._WarnDisabled = function (message) {
  6667. // nothing to do
  6668. };
  6669. Tools._WarnEnabled = function (message) {
  6670. var formattedMessage = Tools._FormatMessage(message);
  6671. console.warn("BJS - " + formattedMessage);
  6672. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6673. Tools._AddLogEntry(entry);
  6674. };
  6675. Tools._ErrorDisabled = function (message) {
  6676. // nothing to do
  6677. };
  6678. Tools._ErrorEnabled = function (message) {
  6679. Tools.errorsCount++;
  6680. var formattedMessage = Tools._FormatMessage(message);
  6681. console.error("BJS - " + formattedMessage);
  6682. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6683. Tools._AddLogEntry(entry);
  6684. };
  6685. Object.defineProperty(Tools, "LogCache", {
  6686. get: function () {
  6687. return Tools._LogCache;
  6688. },
  6689. enumerable: true,
  6690. configurable: true
  6691. });
  6692. Tools.ClearLogCache = function () {
  6693. Tools._LogCache = "";
  6694. Tools.errorsCount = 0;
  6695. };
  6696. Object.defineProperty(Tools, "LogLevels", {
  6697. set: function (level) {
  6698. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6699. Tools.Log = Tools._LogEnabled;
  6700. }
  6701. else {
  6702. Tools.Log = Tools._LogDisabled;
  6703. }
  6704. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6705. Tools.Warn = Tools._WarnEnabled;
  6706. }
  6707. else {
  6708. Tools.Warn = Tools._WarnDisabled;
  6709. }
  6710. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6711. Tools.Error = Tools._ErrorEnabled;
  6712. }
  6713. else {
  6714. Tools.Error = Tools._ErrorDisabled;
  6715. }
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6721. get: function () {
  6722. return Tools._PerformanceNoneLogLevel;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6728. get: function () {
  6729. return Tools._PerformanceUserMarkLogLevel;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6735. get: function () {
  6736. return Tools._PerformanceConsoleLogLevel;
  6737. },
  6738. enumerable: true,
  6739. configurable: true
  6740. });
  6741. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6742. set: function (level) {
  6743. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6744. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6745. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6746. return;
  6747. }
  6748. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6749. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6750. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6751. return;
  6752. }
  6753. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6754. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6760. };
  6761. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6762. };
  6763. Tools._StartUserMark = function (counterName, condition) {
  6764. if (condition === void 0) { condition = true; }
  6765. if (!condition || !Tools._performance.mark) {
  6766. return;
  6767. }
  6768. Tools._performance.mark(counterName + "-Begin");
  6769. };
  6770. Tools._EndUserMark = function (counterName, condition) {
  6771. if (condition === void 0) { condition = true; }
  6772. if (!condition || !Tools._performance.mark) {
  6773. return;
  6774. }
  6775. Tools._performance.mark(counterName + "-End");
  6776. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6777. };
  6778. Tools._StartPerformanceConsole = function (counterName, condition) {
  6779. if (condition === void 0) { condition = true; }
  6780. if (!condition) {
  6781. return;
  6782. }
  6783. Tools._StartUserMark(counterName, condition);
  6784. if (console.time) {
  6785. console.time(counterName);
  6786. }
  6787. };
  6788. Tools._EndPerformanceConsole = function (counterName, condition) {
  6789. if (condition === void 0) { condition = true; }
  6790. if (!condition) {
  6791. return;
  6792. }
  6793. Tools._EndUserMark(counterName, condition);
  6794. if (console.time) {
  6795. console.timeEnd(counterName);
  6796. }
  6797. };
  6798. Object.defineProperty(Tools, "Now", {
  6799. get: function () {
  6800. if (window.performance && window.performance.now) {
  6801. return window.performance.now();
  6802. }
  6803. return new Date().getTime();
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. /**
  6809. * This method will return the name of the class used to create the instance of the given object.
  6810. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6811. * @param object the object to get the class name from
  6812. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6813. */
  6814. Tools.getClassName = function (object, isType) {
  6815. if (isType === void 0) { isType = false; }
  6816. var name = null;
  6817. if (!isType && object.getClassName) {
  6818. name = object.getClassName();
  6819. }
  6820. else {
  6821. if (object instanceof Object) {
  6822. var classObj = isType ? object : Object.getPrototypeOf(object);
  6823. name = classObj.constructor["__bjsclassName__"];
  6824. }
  6825. if (!name) {
  6826. name = typeof object;
  6827. }
  6828. }
  6829. return name;
  6830. };
  6831. Tools.first = function (array, predicate) {
  6832. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6833. var el = array_1[_i];
  6834. if (predicate(el)) {
  6835. return el;
  6836. }
  6837. }
  6838. };
  6839. /**
  6840. * This method will return the name of the full name of the class, including its owning module (if any).
  6841. * 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).
  6842. * @param object the object to get the class name from
  6843. * @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.
  6844. */
  6845. Tools.getFullClassName = function (object, isType) {
  6846. if (isType === void 0) { isType = false; }
  6847. var className = null;
  6848. var moduleName = null;
  6849. if (!isType && object.getClassName) {
  6850. className = object.getClassName();
  6851. }
  6852. else {
  6853. if (object instanceof Object) {
  6854. var classObj = isType ? object : Object.getPrototypeOf(object);
  6855. className = classObj.constructor["__bjsclassName__"];
  6856. moduleName = classObj.constructor["__bjsmoduleName__"];
  6857. }
  6858. if (!className) {
  6859. className = typeof object;
  6860. }
  6861. }
  6862. if (!className) {
  6863. return null;
  6864. }
  6865. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6866. };
  6867. /**
  6868. * 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.
  6869. * @param array
  6870. */
  6871. Tools.arrayOrStringFeeder = function (array) {
  6872. return function (index) {
  6873. if (index >= array.length) {
  6874. return null;
  6875. }
  6876. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6877. if (val && val.getHashCode) {
  6878. val = val.getHashCode();
  6879. }
  6880. if (typeof val === "string") {
  6881. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6882. }
  6883. return val;
  6884. };
  6885. };
  6886. /**
  6887. * Compute the hashCode of a stream of number
  6888. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6889. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6890. * @return the hash code computed
  6891. */
  6892. Tools.hashCodeFromStream = function (feeder) {
  6893. // Based from here: http://stackoverflow.com/a/7616484/802124
  6894. var hash = 0;
  6895. var index = 0;
  6896. var chr = feeder(index++);
  6897. while (chr != null) {
  6898. hash = ((hash << 5) - hash) + chr;
  6899. hash |= 0; // Convert to 32bit integer
  6900. chr = feeder(index++);
  6901. }
  6902. return hash;
  6903. };
  6904. return Tools;
  6905. }());
  6906. Tools.BaseUrl = "";
  6907. Tools.CorsBehavior = "anonymous";
  6908. Tools.UseFallbackTexture = true;
  6909. // Used in case of a texture loading problem
  6910. Tools.fallbackTexture = "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";
  6911. // Logs
  6912. Tools._NoneLogLevel = 0;
  6913. Tools._MessageLogLevel = 1;
  6914. Tools._WarningLogLevel = 2;
  6915. Tools._ErrorLogLevel = 4;
  6916. Tools._LogCache = "";
  6917. Tools.errorsCount = 0;
  6918. Tools.Log = Tools._LogEnabled;
  6919. Tools.Warn = Tools._WarnEnabled;
  6920. Tools.Error = Tools._ErrorEnabled;
  6921. // Performances
  6922. Tools._PerformanceNoneLogLevel = 0;
  6923. Tools._PerformanceUserMarkLogLevel = 1;
  6924. Tools._PerformanceConsoleLogLevel = 2;
  6925. Tools._performance = window.performance;
  6926. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6927. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6928. BABYLON.Tools = Tools;
  6929. /**
  6930. * This class is used to track a performance counter which is number based.
  6931. * The user has access to many properties which give statistics of different nature
  6932. *
  6933. * The implementer can track two kinds of Performance Counter: time and count
  6934. * 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.
  6935. * 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.
  6936. */
  6937. var PerfCounter = (function () {
  6938. function PerfCounter() {
  6939. this._startMonitoringTime = 0;
  6940. this._min = 0;
  6941. this._max = 0;
  6942. this._average = 0;
  6943. this._lastSecAverage = 0;
  6944. this._current = 0;
  6945. this._totalValueCount = 0;
  6946. this._totalAccumulated = 0;
  6947. this._lastSecAccumulated = 0;
  6948. this._lastSecTime = 0;
  6949. this._lastSecValueCount = 0;
  6950. }
  6951. Object.defineProperty(PerfCounter.prototype, "min", {
  6952. /**
  6953. * Returns the smallest value ever
  6954. */
  6955. get: function () {
  6956. return this._min;
  6957. },
  6958. enumerable: true,
  6959. configurable: true
  6960. });
  6961. Object.defineProperty(PerfCounter.prototype, "max", {
  6962. /**
  6963. * Returns the biggest value ever
  6964. */
  6965. get: function () {
  6966. return this._max;
  6967. },
  6968. enumerable: true,
  6969. configurable: true
  6970. });
  6971. Object.defineProperty(PerfCounter.prototype, "average", {
  6972. /**
  6973. * Returns the average value since the performance counter is running
  6974. */
  6975. get: function () {
  6976. return this._average;
  6977. },
  6978. enumerable: true,
  6979. configurable: true
  6980. });
  6981. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6982. /**
  6983. * Returns the average value of the last second the counter was monitored
  6984. */
  6985. get: function () {
  6986. return this._lastSecAverage;
  6987. },
  6988. enumerable: true,
  6989. configurable: true
  6990. });
  6991. Object.defineProperty(PerfCounter.prototype, "current", {
  6992. /**
  6993. * Returns the current value
  6994. */
  6995. get: function () {
  6996. return this._current;
  6997. },
  6998. enumerable: true,
  6999. configurable: true
  7000. });
  7001. Object.defineProperty(PerfCounter.prototype, "total", {
  7002. get: function () {
  7003. return this._totalAccumulated;
  7004. },
  7005. enumerable: true,
  7006. configurable: true
  7007. });
  7008. /**
  7009. * Call this method to start monitoring a new frame.
  7010. * 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.
  7011. */
  7012. PerfCounter.prototype.fetchNewFrame = function () {
  7013. this._totalValueCount++;
  7014. this._current = 0;
  7015. this._lastSecValueCount++;
  7016. };
  7017. /**
  7018. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7019. * @param newCount the count value to add to the monitored count
  7020. * @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.
  7021. */
  7022. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7023. this._current += newCount;
  7024. if (fetchResult) {
  7025. this._fetchResult();
  7026. }
  7027. };
  7028. /**
  7029. * Start monitoring this performance counter
  7030. */
  7031. PerfCounter.prototype.beginMonitoring = function () {
  7032. this._startMonitoringTime = Tools.Now;
  7033. };
  7034. /**
  7035. * Compute the time lapsed since the previous beginMonitoring() call.
  7036. * @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
  7037. */
  7038. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7039. if (newFrame === void 0) { newFrame = true; }
  7040. if (newFrame) {
  7041. this.fetchNewFrame();
  7042. }
  7043. var currentTime = Tools.Now;
  7044. this._current = currentTime - this._startMonitoringTime;
  7045. if (newFrame) {
  7046. this._fetchResult();
  7047. }
  7048. };
  7049. PerfCounter.prototype._fetchResult = function () {
  7050. this._totalAccumulated += this._current;
  7051. this._lastSecAccumulated += this._current;
  7052. // Min/Max update
  7053. this._min = Math.min(this._min, this._current);
  7054. this._max = Math.max(this._max, this._current);
  7055. this._average = this._totalAccumulated / this._totalValueCount;
  7056. // Reset last sec?
  7057. var now = Tools.Now;
  7058. if ((now - this._lastSecTime) > 1000) {
  7059. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7060. this._lastSecTime = now;
  7061. this._lastSecAccumulated = 0;
  7062. this._lastSecValueCount = 0;
  7063. }
  7064. };
  7065. return PerfCounter;
  7066. }());
  7067. BABYLON.PerfCounter = PerfCounter;
  7068. /**
  7069. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7070. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7071. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7072. * @param name The name of the class, case should be preserved
  7073. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7074. */
  7075. function className(name, module) {
  7076. return function (target) {
  7077. target["__bjsclassName__"] = name;
  7078. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7079. };
  7080. }
  7081. BABYLON.className = className;
  7082. /**
  7083. * An implementation of a loop for asynchronous functions.
  7084. */
  7085. var AsyncLoop = (function () {
  7086. /**
  7087. * Constroctor.
  7088. * @param iterations the number of iterations.
  7089. * @param _fn the function to run each iteration
  7090. * @param _successCallback the callback that will be called upon succesful execution
  7091. * @param offset starting offset.
  7092. */
  7093. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7094. if (offset === void 0) { offset = 0; }
  7095. this.iterations = iterations;
  7096. this._fn = _fn;
  7097. this._successCallback = _successCallback;
  7098. this.index = offset - 1;
  7099. this._done = false;
  7100. }
  7101. /**
  7102. * Execute the next iteration. Must be called after the last iteration was finished.
  7103. */
  7104. AsyncLoop.prototype.executeNext = function () {
  7105. if (!this._done) {
  7106. if (this.index + 1 < this.iterations) {
  7107. ++this.index;
  7108. this._fn(this);
  7109. }
  7110. else {
  7111. this.breakLoop();
  7112. }
  7113. }
  7114. };
  7115. /**
  7116. * Break the loop and run the success callback.
  7117. */
  7118. AsyncLoop.prototype.breakLoop = function () {
  7119. this._done = true;
  7120. this._successCallback();
  7121. };
  7122. /**
  7123. * Helper function
  7124. */
  7125. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7126. if (offset === void 0) { offset = 0; }
  7127. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7128. loop.executeNext();
  7129. return loop;
  7130. };
  7131. /**
  7132. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7133. * @param iterations total number of iterations
  7134. * @param syncedIterations number of synchronous iterations in each async iteration.
  7135. * @param fn the function to call each iteration.
  7136. * @param callback a success call back that will be called when iterating stops.
  7137. * @param breakFunction a break condition (optional)
  7138. * @param timeout timeout settings for the setTimeout function. default - 0.
  7139. * @constructor
  7140. */
  7141. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7142. if (timeout === void 0) { timeout = 0; }
  7143. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7144. if (breakFunction && breakFunction())
  7145. loop.breakLoop();
  7146. else {
  7147. setTimeout(function () {
  7148. for (var i = 0; i < syncedIterations; ++i) {
  7149. var iteration = (loop.index * syncedIterations) + i;
  7150. if (iteration >= iterations)
  7151. break;
  7152. fn(iteration);
  7153. if (breakFunction && breakFunction()) {
  7154. loop.breakLoop();
  7155. break;
  7156. }
  7157. }
  7158. loop.executeNext();
  7159. }, timeout);
  7160. }
  7161. }, callback);
  7162. };
  7163. return AsyncLoop;
  7164. }());
  7165. BABYLON.AsyncLoop = AsyncLoop;
  7166. })(BABYLON || (BABYLON = {}));
  7167. //# sourceMappingURL=babylon.tools.js.map
  7168. var BABYLON;
  7169. (function (BABYLON) {
  7170. var Internals;
  7171. (function (Internals) {
  7172. var _AlphaState = (function () {
  7173. /**
  7174. * Initializes the state.
  7175. */
  7176. function _AlphaState() {
  7177. this._isAlphaBlendDirty = false;
  7178. this._isBlendFunctionParametersDirty = false;
  7179. this._alphaBlend = false;
  7180. this._blendFunctionParameters = new Array(4);
  7181. this.reset();
  7182. }
  7183. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7184. get: function () {
  7185. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7186. },
  7187. enumerable: true,
  7188. configurable: true
  7189. });
  7190. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7191. get: function () {
  7192. return this._alphaBlend;
  7193. },
  7194. set: function (value) {
  7195. if (this._alphaBlend === value) {
  7196. return;
  7197. }
  7198. this._alphaBlend = value;
  7199. this._isAlphaBlendDirty = true;
  7200. },
  7201. enumerable: true,
  7202. configurable: true
  7203. });
  7204. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7205. if (this._blendFunctionParameters[0] === value0 &&
  7206. this._blendFunctionParameters[1] === value1 &&
  7207. this._blendFunctionParameters[2] === value2 &&
  7208. this._blendFunctionParameters[3] === value3) {
  7209. return;
  7210. }
  7211. this._blendFunctionParameters[0] = value0;
  7212. this._blendFunctionParameters[1] = value1;
  7213. this._blendFunctionParameters[2] = value2;
  7214. this._blendFunctionParameters[3] = value3;
  7215. this._isBlendFunctionParametersDirty = true;
  7216. };
  7217. _AlphaState.prototype.reset = function () {
  7218. this._alphaBlend = false;
  7219. this._blendFunctionParameters[0] = null;
  7220. this._blendFunctionParameters[1] = null;
  7221. this._blendFunctionParameters[2] = null;
  7222. this._blendFunctionParameters[3] = null;
  7223. this._isAlphaBlendDirty = true;
  7224. this._isBlendFunctionParametersDirty = false;
  7225. };
  7226. _AlphaState.prototype.apply = function (gl) {
  7227. if (!this.isDirty) {
  7228. return;
  7229. }
  7230. // Alpha blend
  7231. if (this._isAlphaBlendDirty) {
  7232. if (this._alphaBlend) {
  7233. gl.enable(gl.BLEND);
  7234. }
  7235. else {
  7236. gl.disable(gl.BLEND);
  7237. }
  7238. this._isAlphaBlendDirty = false;
  7239. }
  7240. // Alpha function
  7241. if (this._isBlendFunctionParametersDirty) {
  7242. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7243. this._isBlendFunctionParametersDirty = false;
  7244. }
  7245. };
  7246. return _AlphaState;
  7247. }());
  7248. Internals._AlphaState = _AlphaState;
  7249. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7250. })(BABYLON || (BABYLON = {}));
  7251. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7252. var BABYLON;
  7253. (function (BABYLON) {
  7254. var Internals;
  7255. (function (Internals) {
  7256. var _DepthCullingState = (function () {
  7257. /**
  7258. * Initializes the state.
  7259. */
  7260. function _DepthCullingState() {
  7261. this._isDepthTestDirty = false;
  7262. this._isDepthMaskDirty = false;
  7263. this._isDepthFuncDirty = false;
  7264. this._isCullFaceDirty = false;
  7265. this._isCullDirty = false;
  7266. this._isZOffsetDirty = false;
  7267. this.reset();
  7268. }
  7269. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7270. get: function () {
  7271. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7272. },
  7273. enumerable: true,
  7274. configurable: true
  7275. });
  7276. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7277. get: function () {
  7278. return this._zOffset;
  7279. },
  7280. set: function (value) {
  7281. if (this._zOffset === value) {
  7282. return;
  7283. }
  7284. this._zOffset = value;
  7285. this._isZOffsetDirty = true;
  7286. },
  7287. enumerable: true,
  7288. configurable: true
  7289. });
  7290. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7291. get: function () {
  7292. return this._cullFace;
  7293. },
  7294. set: function (value) {
  7295. if (this._cullFace === value) {
  7296. return;
  7297. }
  7298. this._cullFace = value;
  7299. this._isCullFaceDirty = true;
  7300. },
  7301. enumerable: true,
  7302. configurable: true
  7303. });
  7304. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7305. get: function () {
  7306. return this._cull;
  7307. },
  7308. set: function (value) {
  7309. if (this._cull === value) {
  7310. return;
  7311. }
  7312. this._cull = value;
  7313. this._isCullDirty = true;
  7314. },
  7315. enumerable: true,
  7316. configurable: true
  7317. });
  7318. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7319. get: function () {
  7320. return this._depthFunc;
  7321. },
  7322. set: function (value) {
  7323. if (this._depthFunc === value) {
  7324. return;
  7325. }
  7326. this._depthFunc = value;
  7327. this._isDepthFuncDirty = true;
  7328. },
  7329. enumerable: true,
  7330. configurable: true
  7331. });
  7332. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7333. get: function () {
  7334. return this._depthMask;
  7335. },
  7336. set: function (value) {
  7337. if (this._depthMask === value) {
  7338. return;
  7339. }
  7340. this._depthMask = value;
  7341. this._isDepthMaskDirty = true;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7347. get: function () {
  7348. return this._depthTest;
  7349. },
  7350. set: function (value) {
  7351. if (this._depthTest === value) {
  7352. return;
  7353. }
  7354. this._depthTest = value;
  7355. this._isDepthTestDirty = true;
  7356. },
  7357. enumerable: true,
  7358. configurable: true
  7359. });
  7360. _DepthCullingState.prototype.reset = function () {
  7361. this._depthMask = true;
  7362. this._depthTest = true;
  7363. this._depthFunc = null;
  7364. this._cullFace = null;
  7365. this._cull = null;
  7366. this._zOffset = 0;
  7367. this._isDepthTestDirty = true;
  7368. this._isDepthMaskDirty = true;
  7369. this._isDepthFuncDirty = false;
  7370. this._isCullFaceDirty = false;
  7371. this._isCullDirty = false;
  7372. this._isZOffsetDirty = false;
  7373. };
  7374. _DepthCullingState.prototype.apply = function (gl) {
  7375. if (!this.isDirty) {
  7376. return;
  7377. }
  7378. // Cull
  7379. if (this._isCullDirty) {
  7380. if (this.cull) {
  7381. gl.enable(gl.CULL_FACE);
  7382. }
  7383. else {
  7384. gl.disable(gl.CULL_FACE);
  7385. }
  7386. this._isCullDirty = false;
  7387. }
  7388. // Cull face
  7389. if (this._isCullFaceDirty) {
  7390. gl.cullFace(this.cullFace);
  7391. this._isCullFaceDirty = false;
  7392. }
  7393. // Depth mask
  7394. if (this._isDepthMaskDirty) {
  7395. gl.depthMask(this.depthMask);
  7396. this._isDepthMaskDirty = false;
  7397. }
  7398. // Depth test
  7399. if (this._isDepthTestDirty) {
  7400. if (this.depthTest) {
  7401. gl.enable(gl.DEPTH_TEST);
  7402. }
  7403. else {
  7404. gl.disable(gl.DEPTH_TEST);
  7405. }
  7406. this._isDepthTestDirty = false;
  7407. }
  7408. // Depth func
  7409. if (this._isDepthFuncDirty) {
  7410. gl.depthFunc(this.depthFunc);
  7411. this._isDepthFuncDirty = false;
  7412. }
  7413. // zOffset
  7414. if (this._isZOffsetDirty) {
  7415. if (this.zOffset) {
  7416. gl.enable(gl.POLYGON_OFFSET_FILL);
  7417. gl.polygonOffset(this.zOffset, 0);
  7418. }
  7419. else {
  7420. gl.disable(gl.POLYGON_OFFSET_FILL);
  7421. }
  7422. this._isZOffsetDirty = false;
  7423. }
  7424. };
  7425. return _DepthCullingState;
  7426. }());
  7427. Internals._DepthCullingState = _DepthCullingState;
  7428. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7429. })(BABYLON || (BABYLON = {}));
  7430. //# sourceMappingURL=babylon.depthCullingState.js.map
  7431. var BABYLON;
  7432. (function (BABYLON) {
  7433. var Internals;
  7434. (function (Internals) {
  7435. var _StencilState = (function () {
  7436. function _StencilState() {
  7437. this._isStencilTestDirty = false;
  7438. this._isStencilMaskDirty = false;
  7439. this._isStencilFuncDirty = false;
  7440. this._isStencilOpDirty = false;
  7441. this.reset();
  7442. }
  7443. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7444. get: function () {
  7445. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7446. },
  7447. enumerable: true,
  7448. configurable: true
  7449. });
  7450. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7451. get: function () {
  7452. return this._stencilFunc;
  7453. },
  7454. set: function (value) {
  7455. if (this._stencilFunc === value) {
  7456. return;
  7457. }
  7458. this._stencilFunc = value;
  7459. this._isStencilFuncDirty = true;
  7460. },
  7461. enumerable: true,
  7462. configurable: true
  7463. });
  7464. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7465. get: function () {
  7466. return this._stencilFuncRef;
  7467. },
  7468. set: function (value) {
  7469. if (this._stencilFuncRef === value) {
  7470. return;
  7471. }
  7472. this._stencilFuncRef = value;
  7473. this._isStencilFuncDirty = true;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7479. get: function () {
  7480. return this._stencilFuncMask;
  7481. },
  7482. set: function (value) {
  7483. if (this._stencilFuncMask === value) {
  7484. return;
  7485. }
  7486. this._stencilFuncMask = value;
  7487. this._isStencilFuncDirty = true;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7493. get: function () {
  7494. return this._stencilOpStencilFail;
  7495. },
  7496. set: function (value) {
  7497. if (this._stencilOpStencilFail === value) {
  7498. return;
  7499. }
  7500. this._stencilOpStencilFail = value;
  7501. this._isStencilOpDirty = true;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7507. get: function () {
  7508. return this._stencilOpDepthFail;
  7509. },
  7510. set: function (value) {
  7511. if (this._stencilOpDepthFail === value) {
  7512. return;
  7513. }
  7514. this._stencilOpDepthFail = value;
  7515. this._isStencilOpDirty = true;
  7516. },
  7517. enumerable: true,
  7518. configurable: true
  7519. });
  7520. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7521. get: function () {
  7522. return this._stencilOpStencilDepthPass;
  7523. },
  7524. set: function (value) {
  7525. if (this._stencilOpStencilDepthPass === value) {
  7526. return;
  7527. }
  7528. this._stencilOpStencilDepthPass = value;
  7529. this._isStencilOpDirty = true;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7535. get: function () {
  7536. return this._stencilMask;
  7537. },
  7538. set: function (value) {
  7539. if (this._stencilMask === value) {
  7540. return;
  7541. }
  7542. this._stencilMask = value;
  7543. this._isStencilMaskDirty = true;
  7544. },
  7545. enumerable: true,
  7546. configurable: true
  7547. });
  7548. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7549. get: function () {
  7550. return this._stencilTest;
  7551. },
  7552. set: function (value) {
  7553. if (this._stencilTest === value) {
  7554. return;
  7555. }
  7556. this._stencilTest = value;
  7557. this._isStencilTestDirty = true;
  7558. },
  7559. enumerable: true,
  7560. configurable: true
  7561. });
  7562. _StencilState.prototype.reset = function () {
  7563. this._stencilTest = false;
  7564. this._stencilMask = 0xFF;
  7565. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7566. this._stencilFuncRef = 1;
  7567. this._stencilFuncMask = 0xFF;
  7568. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7569. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7570. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7571. this._isStencilTestDirty = true;
  7572. this._isStencilMaskDirty = true;
  7573. this._isStencilFuncDirty = true;
  7574. this._isStencilOpDirty = true;
  7575. };
  7576. _StencilState.prototype.apply = function (gl) {
  7577. if (!this.isDirty) {
  7578. return;
  7579. }
  7580. // Stencil test
  7581. if (this._isStencilTestDirty) {
  7582. if (this.stencilTest) {
  7583. gl.enable(gl.STENCIL_TEST);
  7584. }
  7585. else {
  7586. gl.disable(gl.STENCIL_TEST);
  7587. }
  7588. this._isStencilTestDirty = false;
  7589. }
  7590. // Stencil mask
  7591. if (this._isStencilMaskDirty) {
  7592. gl.stencilMask(this.stencilMask);
  7593. this._isStencilMaskDirty = false;
  7594. }
  7595. // Stencil func
  7596. if (this._isStencilFuncDirty) {
  7597. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7598. this._isStencilFuncDirty = false;
  7599. }
  7600. // Stencil op
  7601. if (this._isStencilOpDirty) {
  7602. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7603. this._isStencilOpDirty = false;
  7604. }
  7605. };
  7606. return _StencilState;
  7607. }());
  7608. Internals._StencilState = _StencilState;
  7609. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7610. })(BABYLON || (BABYLON = {}));
  7611. //# sourceMappingURL=babylon.stencilState.js.map
  7612. var BABYLON;
  7613. (function (BABYLON) {
  7614. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7615. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7616. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7617. gl.compileShader(shader);
  7618. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7619. throw new Error(gl.getShaderInfoLog(shader));
  7620. }
  7621. return shader;
  7622. };
  7623. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7624. var magFilter = gl.NEAREST;
  7625. var minFilter = gl.NEAREST;
  7626. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7627. magFilter = gl.LINEAR;
  7628. if (generateMipMaps) {
  7629. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7630. }
  7631. else {
  7632. minFilter = gl.LINEAR;
  7633. }
  7634. }
  7635. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7636. magFilter = gl.LINEAR;
  7637. if (generateMipMaps) {
  7638. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7639. }
  7640. else {
  7641. minFilter = gl.LINEAR;
  7642. }
  7643. }
  7644. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7645. magFilter = gl.NEAREST;
  7646. if (generateMipMaps) {
  7647. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7648. }
  7649. else {
  7650. minFilter = gl.NEAREST;
  7651. }
  7652. }
  7653. return {
  7654. min: minFilter,
  7655. mag: magFilter
  7656. };
  7657. };
  7658. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7660. var engine = scene.getEngine();
  7661. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7662. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7663. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7665. texture._baseWidth = width;
  7666. texture._baseHeight = height;
  7667. texture._width = potWidth;
  7668. texture._height = potHeight;
  7669. texture.isReady = true;
  7670. processFunction(potWidth, potHeight);
  7671. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7672. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7673. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7674. if (!noMipmap && !isCompressed) {
  7675. gl.generateMipmap(gl.TEXTURE_2D);
  7676. }
  7677. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7678. engine.resetTextureCache();
  7679. scene._removePendingData(texture);
  7680. texture.onLoadedCallbacks.forEach(function (callback) {
  7681. callback();
  7682. });
  7683. texture.onLoadedCallbacks = [];
  7684. };
  7685. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7686. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7687. var img;
  7688. var onload = function () {
  7689. loadedImages[index] = img;
  7690. loadedImages._internalCount++;
  7691. scene._removePendingData(img);
  7692. if (loadedImages._internalCount === 6) {
  7693. onfinish(loadedImages);
  7694. }
  7695. };
  7696. var onerror = function () {
  7697. scene._removePendingData(img);
  7698. if (onErrorCallBack) {
  7699. onErrorCallBack();
  7700. }
  7701. };
  7702. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7703. scene._addPendingData(img);
  7704. };
  7705. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7706. if (onError === void 0) { onError = null; }
  7707. var loadedImages = [];
  7708. loadedImages._internalCount = 0;
  7709. for (var index = 0; index < 6; index++) {
  7710. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7711. }
  7712. };
  7713. var InstancingAttributeInfo = (function () {
  7714. function InstancingAttributeInfo() {
  7715. }
  7716. return InstancingAttributeInfo;
  7717. }());
  7718. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7719. var EngineCapabilities = (function () {
  7720. function EngineCapabilities() {
  7721. }
  7722. return EngineCapabilities;
  7723. }());
  7724. BABYLON.EngineCapabilities = EngineCapabilities;
  7725. /**
  7726. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7727. */
  7728. var Engine = (function () {
  7729. /**
  7730. * @constructor
  7731. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7732. * @param {boolean} [antialias] - enable antialias
  7733. * @param options - further options to be sent to the getContext function
  7734. */
  7735. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7736. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7737. var _this = this;
  7738. // Public members
  7739. this.isFullscreen = false;
  7740. this.isPointerLock = false;
  7741. this.cullBackFaces = true;
  7742. this.renderEvenInBackground = true;
  7743. // To enable/disable IDB support and avoid XHR on .manifest
  7744. this.enableOfflineSupport = true;
  7745. this.scenes = new Array();
  7746. this._windowIsBackground = false;
  7747. this._webGLVersion = 1.0;
  7748. this._badOS = false;
  7749. this._drawCalls = new BABYLON.PerfCounter();
  7750. this._renderingQueueLaunched = false;
  7751. this._activeRenderLoops = [];
  7752. // FPS
  7753. this.fpsRange = 60;
  7754. this.previousFramesDuration = [];
  7755. this.fps = 60;
  7756. this.deltaTime = 0;
  7757. // States
  7758. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7759. this._stencilState = new BABYLON.Internals._StencilState();
  7760. this._alphaState = new BABYLON.Internals._AlphaState();
  7761. this._alphaMode = Engine.ALPHA_DISABLE;
  7762. // Cache
  7763. this._loadedTexturesCache = new Array();
  7764. this._maxTextureChannels = 16;
  7765. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7766. this._compiledEffects = {};
  7767. this._vertexAttribArraysEnabled = [];
  7768. this._uintIndicesCurrentlySet = false;
  7769. this._currentBoundBuffer = new Array();
  7770. this._currentBufferPointers = [];
  7771. this._currentInstanceLocations = new Array();
  7772. this._currentInstanceBuffers = new Array();
  7773. this._vaoRecordInProgress = false;
  7774. this._mustWipeVertexAttributes = false;
  7775. // Hardware supported Compressed Textures
  7776. this._texturesSupported = new Array();
  7777. this._onVRFullScreenTriggered = function () {
  7778. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7779. //get the old size before we change
  7780. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7781. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7782. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  7783. //But actually, no browser follow the specs...
  7784. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  7785. //get the width and height, change the render size
  7786. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7787. var width, height;
  7788. _this.setHardwareScalingLevel(1);
  7789. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7790. }
  7791. else {
  7792. //When the specs are implemented, need to uncomment this.
  7793. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7794. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7795. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7796. _this._vrDisplayEnabled = undefined;
  7797. }
  7798. };
  7799. this._renderingCanvas = canvas;
  7800. this._externalData = new BABYLON.StringDictionary();
  7801. options = options || {};
  7802. if (antialias != null) {
  7803. options.antialias = antialias;
  7804. }
  7805. if (options.preserveDrawingBuffer === undefined) {
  7806. options.preserveDrawingBuffer = false;
  7807. }
  7808. // GL
  7809. if (!options.disableWebGL2Support) {
  7810. try {
  7811. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7812. if (this._gl) {
  7813. this._webGLVersion = 2.0;
  7814. }
  7815. }
  7816. catch (e) {
  7817. }
  7818. }
  7819. if (!this._gl) {
  7820. if (!canvas) {
  7821. throw new Error("The provided canvas is null or undefined.");
  7822. }
  7823. try {
  7824. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7825. }
  7826. catch (e) {
  7827. throw new Error("WebGL not supported");
  7828. }
  7829. }
  7830. if (!this._gl) {
  7831. throw new Error("WebGL not supported");
  7832. }
  7833. this._onBlur = function () {
  7834. _this._windowIsBackground = true;
  7835. };
  7836. this._onFocus = function () {
  7837. _this._windowIsBackground = false;
  7838. };
  7839. window.addEventListener("blur", this._onBlur);
  7840. window.addEventListener("focus", this._onFocus);
  7841. // Viewport
  7842. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7843. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7844. this.resize();
  7845. // Caps
  7846. this._isStencilEnable = options.stencil;
  7847. this._caps = new EngineCapabilities();
  7848. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7849. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7850. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7851. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7852. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7853. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7854. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7855. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7856. // Infos
  7857. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7858. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7859. if (rendererInfo != null) {
  7860. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7861. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7862. }
  7863. if (!this._glVendor) {
  7864. this._glVendor = "Unknown vendor";
  7865. }
  7866. if (!this._glRenderer) {
  7867. this._glRenderer = "Unknown renderer";
  7868. }
  7869. // Extensions
  7870. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7871. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7872. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7873. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7874. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7875. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7876. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7877. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  7878. 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');
  7879. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7880. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7881. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7882. this._caps.highPrecisionShaderSupported = true;
  7883. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7884. // Checks if some of the format renders first to allow the use of webgl inspector.
  7885. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7886. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7887. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7888. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7889. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7890. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7891. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7892. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7893. // Vertex array object
  7894. if (this._webGLVersion > 1) {
  7895. this._caps.vertexArrayObject = true;
  7896. }
  7897. else {
  7898. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7899. if (vertexArrayObjectExtension != null) {
  7900. this._caps.vertexArrayObject = true;
  7901. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7902. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7903. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7904. }
  7905. else {
  7906. this._caps.vertexArrayObject = false;
  7907. }
  7908. }
  7909. // Instances count
  7910. if (this._webGLVersion > 1) {
  7911. this._caps.instancedArrays = true;
  7912. }
  7913. else {
  7914. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7915. if (instanceExtension != null) {
  7916. this._caps.instancedArrays = true;
  7917. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7918. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7919. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7920. }
  7921. else {
  7922. this._caps.instancedArrays = false;
  7923. }
  7924. }
  7925. // Intelligently add supported compressed formats in order to check for.
  7926. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7927. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7928. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7929. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7930. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  7931. if (this._caps.astc)
  7932. this.texturesSupported.push('-astc.ktx');
  7933. if (this._caps.s3tc)
  7934. this.texturesSupported.push('-dxt.ktx');
  7935. if (this._caps.pvrtc)
  7936. this.texturesSupported.push('-pvrtc.ktx');
  7937. if (this._caps.etc2)
  7938. this.texturesSupported.push('-etc2.ktx');
  7939. if (this._caps.atc)
  7940. this.texturesSupported.push('-atc.ktx');
  7941. if (this._caps.etc1)
  7942. this.texturesSupported.push('-etc1.ktx');
  7943. if (this._gl.getShaderPrecisionFormat) {
  7944. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7945. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7946. }
  7947. // Depth buffer
  7948. this.setDepthBuffer(true);
  7949. this.setDepthFunctionToLessOrEqual();
  7950. this.setDepthWrite(true);
  7951. // Fullscreen
  7952. this._onFullscreenChange = function () {
  7953. if (document.fullscreen !== undefined) {
  7954. _this.isFullscreen = document.fullscreen;
  7955. }
  7956. else if (document.mozFullScreen !== undefined) {
  7957. _this.isFullscreen = document.mozFullScreen;
  7958. }
  7959. else if (document.webkitIsFullScreen !== undefined) {
  7960. _this.isFullscreen = document.webkitIsFullScreen;
  7961. }
  7962. else if (document.msIsFullScreen !== undefined) {
  7963. _this.isFullscreen = document.msIsFullScreen;
  7964. }
  7965. // Pointer lock
  7966. if (_this.isFullscreen && _this._pointerLockRequested) {
  7967. canvas.requestPointerLock = canvas.requestPointerLock ||
  7968. canvas.msRequestPointerLock ||
  7969. canvas.mozRequestPointerLock ||
  7970. canvas.webkitRequestPointerLock;
  7971. if (canvas.requestPointerLock) {
  7972. canvas.requestPointerLock();
  7973. }
  7974. }
  7975. };
  7976. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7977. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7978. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7979. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7980. // Pointer lock
  7981. this._onPointerLockChange = function () {
  7982. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7983. document.webkitPointerLockElement === canvas ||
  7984. document.msPointerLockElement === canvas ||
  7985. document.pointerLockElement === canvas);
  7986. };
  7987. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7988. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7989. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7990. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7991. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  7992. Engine.audioEngine = new BABYLON.AudioEngine();
  7993. }
  7994. //default loading screen
  7995. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  7996. //Load WebVR Devices
  7997. if (options.autoEnableWebVR) {
  7998. this.initWebVR();
  7999. }
  8000. //Detect if we are running on a faulty buggy OS.
  8001. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8002. //ua sniffing is the tool of the devil.
  8003. this._badOS = regexp.test(navigator.userAgent);
  8004. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8005. }
  8006. Object.defineProperty(Engine, "NEVER", {
  8007. get: function () {
  8008. return Engine._NEVER;
  8009. },
  8010. enumerable: true,
  8011. configurable: true
  8012. });
  8013. Object.defineProperty(Engine, "ALWAYS", {
  8014. get: function () {
  8015. return Engine._ALWAYS;
  8016. },
  8017. enumerable: true,
  8018. configurable: true
  8019. });
  8020. Object.defineProperty(Engine, "LESS", {
  8021. get: function () {
  8022. return Engine._LESS;
  8023. },
  8024. enumerable: true,
  8025. configurable: true
  8026. });
  8027. Object.defineProperty(Engine, "EQUAL", {
  8028. get: function () {
  8029. return Engine._EQUAL;
  8030. },
  8031. enumerable: true,
  8032. configurable: true
  8033. });
  8034. Object.defineProperty(Engine, "LEQUAL", {
  8035. get: function () {
  8036. return Engine._LEQUAL;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(Engine, "GREATER", {
  8042. get: function () {
  8043. return Engine._GREATER;
  8044. },
  8045. enumerable: true,
  8046. configurable: true
  8047. });
  8048. Object.defineProperty(Engine, "GEQUAL", {
  8049. get: function () {
  8050. return Engine._GEQUAL;
  8051. },
  8052. enumerable: true,
  8053. configurable: true
  8054. });
  8055. Object.defineProperty(Engine, "NOTEQUAL", {
  8056. get: function () {
  8057. return Engine._NOTEQUAL;
  8058. },
  8059. enumerable: true,
  8060. configurable: true
  8061. });
  8062. Object.defineProperty(Engine, "KEEP", {
  8063. get: function () {
  8064. return Engine._KEEP;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Object.defineProperty(Engine, "REPLACE", {
  8070. get: function () {
  8071. return Engine._REPLACE;
  8072. },
  8073. enumerable: true,
  8074. configurable: true
  8075. });
  8076. Object.defineProperty(Engine, "INCR", {
  8077. get: function () {
  8078. return Engine._INCR;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Engine, "DECR", {
  8084. get: function () {
  8085. return Engine._DECR;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Object.defineProperty(Engine, "INVERT", {
  8091. get: function () {
  8092. return Engine._INVERT;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. Object.defineProperty(Engine, "INCR_WRAP", {
  8098. get: function () {
  8099. return Engine._INCR_WRAP;
  8100. },
  8101. enumerable: true,
  8102. configurable: true
  8103. });
  8104. Object.defineProperty(Engine, "DECR_WRAP", {
  8105. get: function () {
  8106. return Engine._DECR_WRAP;
  8107. },
  8108. enumerable: true,
  8109. configurable: true
  8110. });
  8111. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8112. get: function () {
  8113. return Engine._ALPHA_DISABLE;
  8114. },
  8115. enumerable: true,
  8116. configurable: true
  8117. });
  8118. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8119. get: function () {
  8120. return Engine._ALPHA_ONEONE;
  8121. },
  8122. enumerable: true,
  8123. configurable: true
  8124. });
  8125. Object.defineProperty(Engine, "ALPHA_ADD", {
  8126. get: function () {
  8127. return Engine._ALPHA_ADD;
  8128. },
  8129. enumerable: true,
  8130. configurable: true
  8131. });
  8132. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8133. get: function () {
  8134. return Engine._ALPHA_COMBINE;
  8135. },
  8136. enumerable: true,
  8137. configurable: true
  8138. });
  8139. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8140. get: function () {
  8141. return Engine._ALPHA_SUBTRACT;
  8142. },
  8143. enumerable: true,
  8144. configurable: true
  8145. });
  8146. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8147. get: function () {
  8148. return Engine._ALPHA_MULTIPLY;
  8149. },
  8150. enumerable: true,
  8151. configurable: true
  8152. });
  8153. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8154. get: function () {
  8155. return Engine._ALPHA_MAXIMIZED;
  8156. },
  8157. enumerable: true,
  8158. configurable: true
  8159. });
  8160. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8161. get: function () {
  8162. return Engine._ALPHA_PREMULTIPLIED;
  8163. },
  8164. enumerable: true,
  8165. configurable: true
  8166. });
  8167. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8168. get: function () {
  8169. return Engine._DELAYLOADSTATE_NONE;
  8170. },
  8171. enumerable: true,
  8172. configurable: true
  8173. });
  8174. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8175. get: function () {
  8176. return Engine._DELAYLOADSTATE_LOADED;
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8182. get: function () {
  8183. return Engine._DELAYLOADSTATE_LOADING;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8189. get: function () {
  8190. return Engine._DELAYLOADSTATE_NOTLOADED;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8196. get: function () {
  8197. return Engine._TEXTUREFORMAT_ALPHA;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8203. get: function () {
  8204. return Engine._TEXTUREFORMAT_LUMINANCE;
  8205. },
  8206. enumerable: true,
  8207. configurable: true
  8208. });
  8209. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8210. get: function () {
  8211. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8217. get: function () {
  8218. return Engine._TEXTUREFORMAT_RGB;
  8219. },
  8220. enumerable: true,
  8221. configurable: true
  8222. });
  8223. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8224. get: function () {
  8225. return Engine._TEXTUREFORMAT_RGBA;
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8231. get: function () {
  8232. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8233. },
  8234. enumerable: true,
  8235. configurable: true
  8236. });
  8237. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8238. get: function () {
  8239. return Engine._TEXTURETYPE_FLOAT;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8245. get: function () {
  8246. return Engine._TEXTURETYPE_HALF_FLOAT;
  8247. },
  8248. enumerable: true,
  8249. configurable: true
  8250. });
  8251. Object.defineProperty(Engine, "Version", {
  8252. get: function () {
  8253. return "2.6-alpha";
  8254. },
  8255. enumerable: true,
  8256. configurable: true
  8257. });
  8258. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8259. get: function () {
  8260. return this._texturesSupported;
  8261. },
  8262. enumerable: true,
  8263. configurable: true
  8264. });
  8265. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8266. get: function () {
  8267. return this._textureFormatInUse;
  8268. },
  8269. enumerable: true,
  8270. configurable: true
  8271. });
  8272. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8273. get: function () {
  8274. return this._webGLVersion;
  8275. },
  8276. enumerable: true,
  8277. configurable: true
  8278. });
  8279. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8280. /**
  8281. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8282. */
  8283. get: function () {
  8284. return this._isStencilEnable;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Engine.prototype._prepareWorkingCanvas = function () {
  8290. if (this._workingCanvas) {
  8291. return;
  8292. }
  8293. this._workingCanvas = document.createElement("canvas");
  8294. this._workingContext = this._workingCanvas.getContext("2d");
  8295. };
  8296. Engine.prototype.resetTextureCache = function () {
  8297. for (var index = 0; index < this._maxTextureChannels; index++) {
  8298. this._activeTexturesCache[index] = null;
  8299. }
  8300. };
  8301. Engine.prototype.getGlInfo = function () {
  8302. return {
  8303. vendor: this._glVendor,
  8304. renderer: this._glRenderer,
  8305. version: this._glVersion
  8306. };
  8307. };
  8308. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8309. if (useScreen === void 0) { useScreen = false; }
  8310. var viewport = camera.viewport;
  8311. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8312. };
  8313. Engine.prototype.getRenderWidth = function (useScreen) {
  8314. if (useScreen === void 0) { useScreen = false; }
  8315. if (!useScreen && this._currentRenderTarget) {
  8316. return this._currentRenderTarget._width;
  8317. }
  8318. return this._renderingCanvas.width;
  8319. };
  8320. Engine.prototype.getRenderHeight = function (useScreen) {
  8321. if (useScreen === void 0) { useScreen = false; }
  8322. if (!useScreen && this._currentRenderTarget) {
  8323. return this._currentRenderTarget._height;
  8324. }
  8325. return this._renderingCanvas.height;
  8326. };
  8327. Engine.prototype.getRenderingCanvas = function () {
  8328. return this._renderingCanvas;
  8329. };
  8330. Engine.prototype.getRenderingCanvasClientRect = function () {
  8331. return this._renderingCanvas.getBoundingClientRect();
  8332. };
  8333. Engine.prototype.setHardwareScalingLevel = function (level) {
  8334. this._hardwareScalingLevel = level;
  8335. this.resize();
  8336. };
  8337. Engine.prototype.getHardwareScalingLevel = function () {
  8338. return this._hardwareScalingLevel;
  8339. };
  8340. Engine.prototype.getLoadedTexturesCache = function () {
  8341. return this._loadedTexturesCache;
  8342. };
  8343. Engine.prototype.getCaps = function () {
  8344. return this._caps;
  8345. };
  8346. Object.defineProperty(Engine.prototype, "drawCalls", {
  8347. get: function () {
  8348. return this._drawCalls.current;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8354. get: function () {
  8355. return this._drawCalls;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Engine.prototype.getDepthFunction = function () {
  8361. return this._depthCullingState.depthFunc;
  8362. };
  8363. Engine.prototype.setDepthFunction = function (depthFunc) {
  8364. this._depthCullingState.depthFunc = depthFunc;
  8365. };
  8366. Engine.prototype.setDepthFunctionToGreater = function () {
  8367. this._depthCullingState.depthFunc = this._gl.GREATER;
  8368. };
  8369. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8370. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8371. };
  8372. Engine.prototype.setDepthFunctionToLess = function () {
  8373. this._depthCullingState.depthFunc = this._gl.LESS;
  8374. };
  8375. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8376. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8377. };
  8378. Engine.prototype.getStencilBuffer = function () {
  8379. return this._stencilState.stencilTest;
  8380. };
  8381. Engine.prototype.setStencilBuffer = function (enable) {
  8382. this._stencilState.stencilTest = enable;
  8383. };
  8384. Engine.prototype.getStencilMask = function () {
  8385. return this._stencilState.stencilMask;
  8386. };
  8387. Engine.prototype.setStencilMask = function (mask) {
  8388. this._stencilState.stencilMask = mask;
  8389. };
  8390. Engine.prototype.getStencilFunction = function () {
  8391. return this._stencilState.stencilFunc;
  8392. };
  8393. Engine.prototype.getStencilFunctionReference = function () {
  8394. return this._stencilState.stencilFuncRef;
  8395. };
  8396. Engine.prototype.getStencilFunctionMask = function () {
  8397. return this._stencilState.stencilFuncMask;
  8398. };
  8399. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8400. this._stencilState.stencilFunc = stencilFunc;
  8401. };
  8402. Engine.prototype.setStencilFunctionReference = function (reference) {
  8403. this._stencilState.stencilFuncRef = reference;
  8404. };
  8405. Engine.prototype.setStencilFunctionMask = function (mask) {
  8406. this._stencilState.stencilFuncMask = mask;
  8407. };
  8408. Engine.prototype.getStencilOperationFail = function () {
  8409. return this._stencilState.stencilOpStencilFail;
  8410. };
  8411. Engine.prototype.getStencilOperationDepthFail = function () {
  8412. return this._stencilState.stencilOpDepthFail;
  8413. };
  8414. Engine.prototype.getStencilOperationPass = function () {
  8415. return this._stencilState.stencilOpStencilDepthPass;
  8416. };
  8417. Engine.prototype.setStencilOperationFail = function (operation) {
  8418. this._stencilState.stencilOpStencilFail = operation;
  8419. };
  8420. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8421. this._stencilState.stencilOpDepthFail = operation;
  8422. };
  8423. Engine.prototype.setStencilOperationPass = function (operation) {
  8424. this._stencilState.stencilOpStencilDepthPass = operation;
  8425. };
  8426. /**
  8427. * stop executing a render loop function and remove it from the execution array
  8428. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8429. */
  8430. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8431. if (!renderFunction) {
  8432. this._activeRenderLoops = [];
  8433. return;
  8434. }
  8435. var index = this._activeRenderLoops.indexOf(renderFunction);
  8436. if (index >= 0) {
  8437. this._activeRenderLoops.splice(index, 1);
  8438. }
  8439. };
  8440. Engine.prototype._renderLoop = function () {
  8441. var shouldRender = true;
  8442. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8443. shouldRender = false;
  8444. }
  8445. if (shouldRender) {
  8446. // Start new frame
  8447. this.beginFrame();
  8448. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8449. var renderFunction = this._activeRenderLoops[index];
  8450. renderFunction();
  8451. }
  8452. // Present
  8453. this.endFrame();
  8454. }
  8455. if (this._activeRenderLoops.length > 0) {
  8456. // Register new frame
  8457. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8458. }
  8459. else {
  8460. this._renderingQueueLaunched = false;
  8461. }
  8462. };
  8463. /**
  8464. * Register and execute a render loop. The engine can have more than one render function.
  8465. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8466. * @example
  8467. * engine.runRenderLoop(function () {
  8468. * scene.render()
  8469. * })
  8470. */
  8471. Engine.prototype.runRenderLoop = function (renderFunction) {
  8472. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8473. return;
  8474. }
  8475. this._activeRenderLoops.push(renderFunction);
  8476. if (!this._renderingQueueLaunched) {
  8477. this._renderingQueueLaunched = true;
  8478. this._bindedRenderFunction = this._renderLoop.bind(this);
  8479. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8480. }
  8481. };
  8482. /**
  8483. * Toggle full screen mode.
  8484. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8485. * @param {any} options - an options object to be sent to the requestFullscreen function
  8486. */
  8487. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8488. if (this.isFullscreen) {
  8489. BABYLON.Tools.ExitFullscreen();
  8490. }
  8491. else {
  8492. this._pointerLockRequested = requestPointerLock;
  8493. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8494. }
  8495. };
  8496. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8497. if (stencil === void 0) { stencil = false; }
  8498. this.applyStates();
  8499. var mode = 0;
  8500. if (backBuffer && color) {
  8501. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8502. mode |= this._gl.COLOR_BUFFER_BIT;
  8503. }
  8504. if (depth) {
  8505. this._gl.clearDepth(1.0);
  8506. mode |= this._gl.DEPTH_BUFFER_BIT;
  8507. }
  8508. if (stencil) {
  8509. this._gl.clearStencil(0);
  8510. mode |= this._gl.STENCIL_BUFFER_BIT;
  8511. }
  8512. this._gl.clear(mode);
  8513. };
  8514. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8515. var gl = this._gl;
  8516. // Save state
  8517. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8518. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8519. // Change state
  8520. gl.enable(gl.SCISSOR_TEST);
  8521. gl.scissor(x, y, width, height);
  8522. // Clear
  8523. this.clear(clearColor, true, true, true);
  8524. // Restore state
  8525. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8526. if (curScissor === true) {
  8527. gl.enable(gl.SCISSOR_TEST);
  8528. }
  8529. else {
  8530. gl.disable(gl.SCISSOR_TEST);
  8531. }
  8532. };
  8533. /**
  8534. * Set the WebGL's viewport
  8535. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8536. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8537. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8538. */
  8539. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8540. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8541. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8542. var x = viewport.x || 0;
  8543. var y = viewport.y || 0;
  8544. this._cachedViewport = viewport;
  8545. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8546. };
  8547. /**
  8548. * Directly set the WebGL Viewport
  8549. * The x, y, width & height are directly passed to the WebGL call
  8550. * @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.
  8551. */
  8552. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8553. var currentViewport = this._cachedViewport;
  8554. this._cachedViewport = null;
  8555. this._gl.viewport(x, y, width, height);
  8556. return currentViewport;
  8557. };
  8558. Engine.prototype.beginFrame = function () {
  8559. this._measureFps();
  8560. };
  8561. Engine.prototype.endFrame = function () {
  8562. //force a flush in case we are using a bad OS.
  8563. if (this._badOS) {
  8564. this.flushFramebuffer();
  8565. }
  8566. //submit frame to the vr device, if enabled
  8567. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8568. this._vrDisplayEnabled.submitFrame();
  8569. }
  8570. };
  8571. /**
  8572. * resize the view according to the canvas' size.
  8573. * @example
  8574. * window.addEventListener("resize", function () {
  8575. * engine.resize();
  8576. * });
  8577. */
  8578. Engine.prototype.resize = function () {
  8579. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8580. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8581. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8582. };
  8583. /**
  8584. * force a specific size of the canvas
  8585. * @param {number} width - the new canvas' width
  8586. * @param {number} height - the new canvas' height
  8587. */
  8588. Engine.prototype.setSize = function (width, height) {
  8589. this._renderingCanvas.width = width;
  8590. this._renderingCanvas.height = height;
  8591. for (var index = 0; index < this.scenes.length; index++) {
  8592. var scene = this.scenes[index];
  8593. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8594. var cam = scene.cameras[camIndex];
  8595. cam._currentRenderId = 0;
  8596. }
  8597. }
  8598. };
  8599. //WebVR functions
  8600. Engine.prototype.initWebVR = function () {
  8601. if (!this.vrDisplaysPromise) {
  8602. this._getVRDisplays();
  8603. }
  8604. };
  8605. Engine.prototype.enableVR = function (vrDevice) {
  8606. this._vrDisplayEnabled = vrDevice;
  8607. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8608. };
  8609. Engine.prototype.disableVR = function () {
  8610. if (this._vrDisplayEnabled) {
  8611. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8612. }
  8613. };
  8614. Engine.prototype._getVRDisplays = function () {
  8615. var _this = this;
  8616. var getWebVRDevices = function (devices) {
  8617. var size = devices.length;
  8618. var i = 0;
  8619. _this._vrDisplays = devices.filter(function (device) {
  8620. return devices[i] instanceof VRDisplay;
  8621. });
  8622. return _this._vrDisplays;
  8623. };
  8624. //using a key due to typescript
  8625. if (navigator.getVRDisplays) {
  8626. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8627. }
  8628. };
  8629. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8630. this._currentRenderTarget = texture;
  8631. this.bindUnboundFramebuffer(texture._framebuffer);
  8632. var gl = this._gl;
  8633. if (texture.isCube) {
  8634. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8635. }
  8636. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8637. this.wipeCaches();
  8638. };
  8639. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8640. if (this._currentFramebuffer !== framebuffer) {
  8641. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8642. this._currentFramebuffer = framebuffer;
  8643. }
  8644. };
  8645. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  8646. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8647. this._currentRenderTarget = null;
  8648. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8649. var gl = this._gl;
  8650. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8651. gl.generateMipmap(gl.TEXTURE_2D);
  8652. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8653. }
  8654. this.bindUnboundFramebuffer(null);
  8655. };
  8656. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8657. if (texture.generateMipMaps) {
  8658. var gl = this._gl;
  8659. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8660. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8661. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8662. }
  8663. };
  8664. Engine.prototype.flushFramebuffer = function () {
  8665. this._gl.flush();
  8666. };
  8667. Engine.prototype.restoreDefaultFramebuffer = function () {
  8668. this._currentRenderTarget = null;
  8669. this.bindUnboundFramebuffer(null);
  8670. this.setViewport(this._cachedViewport);
  8671. this.wipeCaches();
  8672. };
  8673. // VBOs
  8674. Engine.prototype._resetVertexBufferBinding = function () {
  8675. this.bindArrayBuffer(null);
  8676. this._cachedVertexBuffers = null;
  8677. };
  8678. Engine.prototype.createVertexBuffer = function (vertices) {
  8679. var vbo = this._gl.createBuffer();
  8680. this.bindArrayBuffer(vbo);
  8681. if (vertices instanceof Float32Array) {
  8682. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8683. }
  8684. else {
  8685. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8686. }
  8687. this._resetVertexBufferBinding();
  8688. vbo.references = 1;
  8689. return vbo;
  8690. };
  8691. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8692. var vbo = this._gl.createBuffer();
  8693. this.bindArrayBuffer(vbo);
  8694. if (vertices instanceof Float32Array) {
  8695. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8696. }
  8697. else {
  8698. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8699. }
  8700. this._resetVertexBufferBinding();
  8701. vbo.references = 1;
  8702. return vbo;
  8703. };
  8704. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8705. this.bindArrayBuffer(vertexBuffer);
  8706. if (offset === undefined) {
  8707. offset = 0;
  8708. }
  8709. if (count === undefined) {
  8710. if (vertices instanceof Float32Array) {
  8711. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8712. }
  8713. else {
  8714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8715. }
  8716. }
  8717. else {
  8718. if (vertices instanceof Float32Array) {
  8719. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8720. }
  8721. else {
  8722. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8723. }
  8724. }
  8725. this._resetVertexBufferBinding();
  8726. };
  8727. Engine.prototype._resetIndexBufferBinding = function () {
  8728. this.bindIndexBuffer(null);
  8729. this._cachedIndexBuffer = null;
  8730. };
  8731. Engine.prototype.createIndexBuffer = function (indices) {
  8732. var vbo = this._gl.createBuffer();
  8733. this.bindIndexBuffer(vbo);
  8734. // Check for 32 bits indices
  8735. var arrayBuffer;
  8736. var need32Bits = false;
  8737. if (indices instanceof Uint16Array) {
  8738. arrayBuffer = indices;
  8739. }
  8740. else {
  8741. //check 32 bit support
  8742. if (this._caps.uintIndices) {
  8743. if (indices instanceof Uint32Array) {
  8744. arrayBuffer = indices;
  8745. need32Bits = true;
  8746. }
  8747. else {
  8748. //number[] or Int32Array, check if 32 bit is necessary
  8749. for (var index = 0; index < indices.length; index++) {
  8750. if (indices[index] > 65535) {
  8751. need32Bits = true;
  8752. break;
  8753. }
  8754. }
  8755. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8756. }
  8757. }
  8758. else {
  8759. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8760. arrayBuffer = new Uint16Array(indices);
  8761. }
  8762. }
  8763. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8764. this._resetIndexBufferBinding();
  8765. vbo.references = 1;
  8766. vbo.is32Bits = need32Bits;
  8767. return vbo;
  8768. };
  8769. Engine.prototype.bindArrayBuffer = function (buffer) {
  8770. if (!this._vaoRecordInProgress) {
  8771. this._unBindVertexArrayObject();
  8772. }
  8773. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8774. };
  8775. Engine.prototype.bindIndexBuffer = function (buffer) {
  8776. if (!this._vaoRecordInProgress) {
  8777. this._unBindVertexArrayObject();
  8778. }
  8779. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8780. };
  8781. Engine.prototype.bindBuffer = function (buffer, target) {
  8782. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8783. this._gl.bindBuffer(target, buffer);
  8784. this._currentBoundBuffer[target] = buffer;
  8785. }
  8786. };
  8787. Engine.prototype.updateArrayBuffer = function (data) {
  8788. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8789. };
  8790. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8791. var pointer = this._currentBufferPointers[indx];
  8792. var changed = false;
  8793. if (!pointer) {
  8794. changed = true;
  8795. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8796. }
  8797. else {
  8798. if (pointer.buffer !== buffer) {
  8799. pointer.buffer = buffer;
  8800. changed = true;
  8801. }
  8802. if (pointer.size !== size) {
  8803. pointer.size = size;
  8804. changed = true;
  8805. }
  8806. if (pointer.type !== type) {
  8807. pointer.type = type;
  8808. changed = true;
  8809. }
  8810. if (pointer.normalized !== normalized) {
  8811. pointer.normalized = normalized;
  8812. changed = true;
  8813. }
  8814. if (pointer.stride !== stride) {
  8815. pointer.stride = stride;
  8816. changed = true;
  8817. }
  8818. if (pointer.offset !== offset) {
  8819. pointer.offset = offset;
  8820. changed = true;
  8821. }
  8822. }
  8823. if (changed || this._vaoRecordInProgress) {
  8824. this.bindArrayBuffer(buffer);
  8825. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8826. }
  8827. };
  8828. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8829. if (indexBuffer == null) {
  8830. return;
  8831. }
  8832. if (this._cachedIndexBuffer !== indexBuffer) {
  8833. this._cachedIndexBuffer = indexBuffer;
  8834. this.bindIndexBuffer(indexBuffer);
  8835. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8836. }
  8837. };
  8838. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8839. var attributes = effect.getAttributesNames();
  8840. if (!this._vaoRecordInProgress) {
  8841. this._unBindVertexArrayObject();
  8842. }
  8843. this.unbindAllAttributes();
  8844. for (var index = 0; index < attributes.length; index++) {
  8845. var order = effect.getAttributeLocation(index);
  8846. if (order >= 0) {
  8847. var vertexBuffer = vertexBuffers[attributes[index]];
  8848. if (!vertexBuffer) {
  8849. continue;
  8850. }
  8851. this._gl.enableVertexAttribArray(order);
  8852. if (!this._vaoRecordInProgress) {
  8853. this._vertexAttribArraysEnabled[order] = true;
  8854. }
  8855. var buffer = vertexBuffer.getBuffer();
  8856. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8857. if (vertexBuffer.getIsInstanced()) {
  8858. this._gl.vertexAttribDivisor(order, 1);
  8859. if (!this._vaoRecordInProgress) {
  8860. this._currentInstanceLocations.push(order);
  8861. this._currentInstanceBuffers.push(buffer);
  8862. }
  8863. }
  8864. }
  8865. }
  8866. };
  8867. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8868. var vao = this._gl.createVertexArray();
  8869. this._vaoRecordInProgress = true;
  8870. this._gl.bindVertexArray(vao);
  8871. this._mustWipeVertexAttributes = true;
  8872. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8873. this.bindIndexBuffer(indexBuffer);
  8874. this._vaoRecordInProgress = false;
  8875. this._gl.bindVertexArray(null);
  8876. return vao;
  8877. };
  8878. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8879. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8880. this._cachedVertexArrayObject = vertexArrayObject;
  8881. this._gl.bindVertexArray(vertexArrayObject);
  8882. this._cachedVertexBuffers = null;
  8883. this._cachedIndexBuffer = null;
  8884. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8885. this._mustWipeVertexAttributes = true;
  8886. }
  8887. };
  8888. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8889. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8890. this._cachedVertexBuffers = vertexBuffer;
  8891. this._cachedEffectForVertexBuffers = effect;
  8892. var attributesCount = effect.getAttributesCount();
  8893. this._unBindVertexArrayObject();
  8894. this.unbindAllAttributes();
  8895. var offset = 0;
  8896. for (var index = 0; index < attributesCount; index++) {
  8897. if (index < vertexDeclaration.length) {
  8898. var order = effect.getAttributeLocation(index);
  8899. if (order >= 0) {
  8900. this._gl.enableVertexAttribArray(order);
  8901. this._vertexAttribArraysEnabled[order] = true;
  8902. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8903. }
  8904. offset += vertexDeclaration[index] * 4;
  8905. }
  8906. }
  8907. }
  8908. this._bindIndexBufferWithCache(indexBuffer);
  8909. };
  8910. Engine.prototype._unBindVertexArrayObject = function () {
  8911. if (!this._cachedVertexArrayObject) {
  8912. return;
  8913. }
  8914. this._cachedVertexArrayObject = null;
  8915. this._gl.bindVertexArray(null);
  8916. };
  8917. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8918. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8919. this._cachedVertexBuffers = vertexBuffers;
  8920. this._cachedEffectForVertexBuffers = effect;
  8921. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8922. }
  8923. this._bindIndexBufferWithCache(indexBuffer);
  8924. };
  8925. Engine.prototype.unbindInstanceAttributes = function () {
  8926. var boundBuffer;
  8927. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8928. var instancesBuffer = this._currentInstanceBuffers[i];
  8929. if (boundBuffer != instancesBuffer) {
  8930. boundBuffer = instancesBuffer;
  8931. this.bindArrayBuffer(instancesBuffer);
  8932. }
  8933. var offsetLocation = this._currentInstanceLocations[i];
  8934. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8935. }
  8936. this._currentInstanceBuffers.length = 0;
  8937. this._currentInstanceLocations.length = 0;
  8938. };
  8939. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8940. this._gl.deleteVertexArray(vao);
  8941. };
  8942. Engine.prototype._releaseBuffer = function (buffer) {
  8943. buffer.references--;
  8944. if (buffer.references === 0) {
  8945. this._gl.deleteBuffer(buffer);
  8946. return true;
  8947. }
  8948. return false;
  8949. };
  8950. Engine.prototype.createInstancesBuffer = function (capacity) {
  8951. var buffer = this._gl.createBuffer();
  8952. buffer.capacity = capacity;
  8953. this.bindArrayBuffer(buffer);
  8954. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8955. return buffer;
  8956. };
  8957. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8958. this._gl.deleteBuffer(buffer);
  8959. };
  8960. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8961. this.bindArrayBuffer(instancesBuffer);
  8962. if (data) {
  8963. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8964. }
  8965. if (offsetLocations[0].index !== undefined) {
  8966. var stride = 0;
  8967. for (var i = 0; i < offsetLocations.length; i++) {
  8968. var ai = offsetLocations[i];
  8969. stride += ai.attributeSize * 4;
  8970. }
  8971. for (var i = 0; i < offsetLocations.length; i++) {
  8972. var ai = offsetLocations[i];
  8973. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8974. this._gl.enableVertexAttribArray(ai.index);
  8975. this._vertexAttribArraysEnabled[ai.index] = true;
  8976. }
  8977. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8978. this._gl.vertexAttribDivisor(ai.index, 1);
  8979. this._currentInstanceLocations.push(ai.index);
  8980. this._currentInstanceBuffers.push(instancesBuffer);
  8981. }
  8982. }
  8983. else {
  8984. for (var index = 0; index < 4; index++) {
  8985. var offsetLocation = offsetLocations[index];
  8986. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8987. this._gl.enableVertexAttribArray(offsetLocation);
  8988. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8989. }
  8990. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8991. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8992. this._currentInstanceLocations.push(offsetLocation);
  8993. this._currentInstanceBuffers.push(instancesBuffer);
  8994. }
  8995. }
  8996. };
  8997. Engine.prototype.applyStates = function () {
  8998. this._depthCullingState.apply(this._gl);
  8999. this._stencilState.apply(this._gl);
  9000. this._alphaState.apply(this._gl);
  9001. };
  9002. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9003. // Apply states
  9004. this.applyStates();
  9005. this._drawCalls.addCount(1, false);
  9006. // Render
  9007. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9008. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9009. if (instancesCount) {
  9010. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9011. return;
  9012. }
  9013. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9014. };
  9015. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9016. // Apply states
  9017. this.applyStates();
  9018. this._drawCalls.addCount(1, false);
  9019. if (instancesCount) {
  9020. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9021. return;
  9022. }
  9023. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9024. };
  9025. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9026. // Apply states
  9027. this.applyStates();
  9028. this._drawCalls.addCount(1, false);
  9029. if (instancesCount) {
  9030. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9031. return;
  9032. }
  9033. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9034. };
  9035. // Shaders
  9036. Engine.prototype._releaseEffect = function (effect) {
  9037. if (this._compiledEffects[effect._key]) {
  9038. delete this._compiledEffects[effect._key];
  9039. if (effect.getProgram()) {
  9040. this._gl.deleteProgram(effect.getProgram());
  9041. }
  9042. }
  9043. };
  9044. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9045. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9046. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9047. var name = vertex + "+" + fragment + "@" + defines;
  9048. if (this._compiledEffects[name]) {
  9049. return this._compiledEffects[name];
  9050. }
  9051. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9052. effect._key = name;
  9053. this._compiledEffects[name] = effect;
  9054. return effect;
  9055. };
  9056. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9057. if (uniformsNames === void 0) { uniformsNames = []; }
  9058. if (samplers === void 0) { samplers = []; }
  9059. if (defines === void 0) { defines = ""; }
  9060. return this.createEffect({
  9061. vertex: "particles",
  9062. fragmentElement: fragmentName
  9063. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9064. };
  9065. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9066. context = context || this._gl;
  9067. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9068. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9069. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9070. var shaderProgram = context.createProgram();
  9071. context.attachShader(shaderProgram, vertexShader);
  9072. context.attachShader(shaderProgram, fragmentShader);
  9073. context.linkProgram(shaderProgram);
  9074. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9075. if (!linked) {
  9076. var error = context.getProgramInfoLog(shaderProgram);
  9077. if (error) {
  9078. throw new Error(error);
  9079. }
  9080. }
  9081. context.deleteShader(vertexShader);
  9082. context.deleteShader(fragmentShader);
  9083. return shaderProgram;
  9084. };
  9085. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9086. var results = [];
  9087. for (var index = 0; index < uniformsNames.length; index++) {
  9088. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9089. }
  9090. return results;
  9091. };
  9092. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9093. var results = [];
  9094. for (var index = 0; index < attributesNames.length; index++) {
  9095. try {
  9096. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9097. }
  9098. catch (e) {
  9099. results.push(-1);
  9100. }
  9101. }
  9102. return results;
  9103. };
  9104. Engine.prototype.enableEffect = function (effect) {
  9105. // Use program
  9106. this.setProgram(effect.getProgram());
  9107. this._currentEffect = effect;
  9108. if (effect.onBind) {
  9109. effect.onBind(effect);
  9110. }
  9111. };
  9112. Engine.prototype.setIntArray = function (uniform, array) {
  9113. if (!uniform)
  9114. return;
  9115. this._gl.uniform1iv(uniform, array);
  9116. };
  9117. Engine.prototype.setIntArray2 = function (uniform, array) {
  9118. if (!uniform || array.length % 2 !== 0)
  9119. return;
  9120. this._gl.uniform2iv(uniform, array);
  9121. };
  9122. Engine.prototype.setIntArray3 = function (uniform, array) {
  9123. if (!uniform || array.length % 3 !== 0)
  9124. return;
  9125. this._gl.uniform3iv(uniform, array);
  9126. };
  9127. Engine.prototype.setIntArray4 = function (uniform, array) {
  9128. if (!uniform || array.length % 4 !== 0)
  9129. return;
  9130. this._gl.uniform4iv(uniform, array);
  9131. };
  9132. Engine.prototype.setFloatArray = function (uniform, array) {
  9133. if (!uniform)
  9134. return;
  9135. this._gl.uniform1fv(uniform, array);
  9136. };
  9137. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9138. if (!uniform || array.length % 2 !== 0)
  9139. return;
  9140. this._gl.uniform2fv(uniform, array);
  9141. };
  9142. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9143. if (!uniform || array.length % 3 !== 0)
  9144. return;
  9145. this._gl.uniform3fv(uniform, array);
  9146. };
  9147. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9148. if (!uniform || array.length % 4 !== 0)
  9149. return;
  9150. this._gl.uniform4fv(uniform, array);
  9151. };
  9152. Engine.prototype.setArray = function (uniform, array) {
  9153. if (!uniform)
  9154. return;
  9155. this._gl.uniform1fv(uniform, array);
  9156. };
  9157. Engine.prototype.setArray2 = function (uniform, array) {
  9158. if (!uniform || array.length % 2 !== 0)
  9159. return;
  9160. this._gl.uniform2fv(uniform, array);
  9161. };
  9162. Engine.prototype.setArray3 = function (uniform, array) {
  9163. if (!uniform || array.length % 3 !== 0)
  9164. return;
  9165. this._gl.uniform3fv(uniform, array);
  9166. };
  9167. Engine.prototype.setArray4 = function (uniform, array) {
  9168. if (!uniform || array.length % 4 !== 0)
  9169. return;
  9170. this._gl.uniform4fv(uniform, array);
  9171. };
  9172. Engine.prototype.setMatrices = function (uniform, matrices) {
  9173. if (!uniform)
  9174. return;
  9175. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9176. };
  9177. Engine.prototype.setMatrix = function (uniform, matrix) {
  9178. if (!uniform)
  9179. return;
  9180. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9181. };
  9182. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9183. if (!uniform)
  9184. return;
  9185. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9186. };
  9187. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9188. if (!uniform)
  9189. return;
  9190. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9191. };
  9192. Engine.prototype.setFloat = function (uniform, value) {
  9193. if (!uniform)
  9194. return;
  9195. this._gl.uniform1f(uniform, value);
  9196. };
  9197. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9198. if (!uniform)
  9199. return;
  9200. this._gl.uniform2f(uniform, x, y);
  9201. };
  9202. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9203. if (!uniform)
  9204. return;
  9205. this._gl.uniform3f(uniform, x, y, z);
  9206. };
  9207. Engine.prototype.setBool = function (uniform, bool) {
  9208. if (!uniform)
  9209. return;
  9210. this._gl.uniform1i(uniform, bool);
  9211. };
  9212. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9213. if (!uniform)
  9214. return;
  9215. this._gl.uniform4f(uniform, x, y, z, w);
  9216. };
  9217. Engine.prototype.setColor3 = function (uniform, color3) {
  9218. if (!uniform)
  9219. return;
  9220. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9221. };
  9222. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9223. if (!uniform)
  9224. return;
  9225. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9226. };
  9227. // States
  9228. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9229. if (zOffset === void 0) { zOffset = 0; }
  9230. if (reverseSide === void 0) { reverseSide = false; }
  9231. // Culling
  9232. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9233. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9234. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9235. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9236. if (culling) {
  9237. this._depthCullingState.cullFace = cullFace;
  9238. this._depthCullingState.cull = true;
  9239. }
  9240. else {
  9241. this._depthCullingState.cull = false;
  9242. }
  9243. }
  9244. // Z offset
  9245. this._depthCullingState.zOffset = zOffset;
  9246. };
  9247. Engine.prototype.setDepthBuffer = function (enable) {
  9248. this._depthCullingState.depthTest = enable;
  9249. };
  9250. Engine.prototype.getDepthWrite = function () {
  9251. return this._depthCullingState.depthMask;
  9252. };
  9253. Engine.prototype.setDepthWrite = function (enable) {
  9254. this._depthCullingState.depthMask = enable;
  9255. };
  9256. Engine.prototype.setColorWrite = function (enable) {
  9257. this._gl.colorMask(enable, enable, enable, enable);
  9258. };
  9259. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9260. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9261. if (this._alphaMode === mode) {
  9262. return;
  9263. }
  9264. switch (mode) {
  9265. case Engine.ALPHA_DISABLE:
  9266. this._alphaState.alphaBlend = false;
  9267. break;
  9268. case Engine.ALPHA_PREMULTIPLIED:
  9269. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9270. this._alphaState.alphaBlend = true;
  9271. break;
  9272. case Engine.ALPHA_COMBINE:
  9273. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9274. this._alphaState.alphaBlend = true;
  9275. break;
  9276. case Engine.ALPHA_ONEONE:
  9277. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9278. this._alphaState.alphaBlend = true;
  9279. break;
  9280. case Engine.ALPHA_ADD:
  9281. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9282. this._alphaState.alphaBlend = true;
  9283. break;
  9284. case Engine.ALPHA_SUBTRACT:
  9285. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9286. this._alphaState.alphaBlend = true;
  9287. break;
  9288. case Engine.ALPHA_MULTIPLY:
  9289. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9290. this._alphaState.alphaBlend = true;
  9291. break;
  9292. case Engine.ALPHA_MAXIMIZED:
  9293. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9294. this._alphaState.alphaBlend = true;
  9295. break;
  9296. }
  9297. if (!noDepthWriteChange) {
  9298. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9299. }
  9300. this._alphaMode = mode;
  9301. };
  9302. Engine.prototype.getAlphaMode = function () {
  9303. return this._alphaMode;
  9304. };
  9305. Engine.prototype.setAlphaTesting = function (enable) {
  9306. this._alphaTest = enable;
  9307. };
  9308. Engine.prototype.getAlphaTesting = function () {
  9309. return this._alphaTest;
  9310. };
  9311. // Textures
  9312. Engine.prototype.wipeCaches = function () {
  9313. this.resetTextureCache();
  9314. this._currentEffect = null;
  9315. this._stencilState.reset();
  9316. this._depthCullingState.reset();
  9317. this.setDepthFunctionToLessOrEqual();
  9318. this._alphaState.reset();
  9319. this._cachedVertexBuffers = null;
  9320. this._cachedIndexBuffer = null;
  9321. this._cachedEffectForVertexBuffers = null;
  9322. this._unBindVertexArrayObject();
  9323. this.bindIndexBuffer(null);
  9324. this.bindArrayBuffer(null);
  9325. };
  9326. /**
  9327. * Set the compressed texture format to use, based on the formats you have, and the formats
  9328. * supported by the hardware / browser.
  9329. *
  9330. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9331. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9332. * to API arguments needed to compressed textures. This puts the burden on the container
  9333. * generator to house the arcane code for determining these for current & future formats.
  9334. *
  9335. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9336. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9337. *
  9338. * Note: The result of this call is not taken into account when a texture is base64.
  9339. *
  9340. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9341. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9342. *
  9343. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9344. * @returns The extension selected.
  9345. */
  9346. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9347. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9348. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9349. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9350. return this._textureFormatInUse = this._texturesSupported[i];
  9351. }
  9352. }
  9353. }
  9354. // actively set format to nothing, to allow this to be called more than once
  9355. // and possibly fail the 2nd time
  9356. return this._textureFormatInUse = null;
  9357. };
  9358. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9359. var _this = this;
  9360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9361. if (onLoad === void 0) { onLoad = null; }
  9362. if (onError === void 0) { onError = null; }
  9363. if (buffer === void 0) { buffer = null; }
  9364. var texture = fallBack ? fallBack : this._gl.createTexture();
  9365. var extension;
  9366. var isKTX = false;
  9367. var fromData = false;
  9368. var url = String(urlArg);
  9369. if (url.substr(0, 5) === "data:") {
  9370. fromData = true;
  9371. }
  9372. if (!fromData) {
  9373. var lastDot = url.lastIndexOf('.');
  9374. extension = url.substring(lastDot).toLowerCase();
  9375. if (this._textureFormatInUse && !fromData && !fallBack) {
  9376. extension = this._textureFormatInUse;
  9377. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9378. isKTX = true;
  9379. }
  9380. }
  9381. else {
  9382. var oldUrl = url;
  9383. fromData = oldUrl.split(':');
  9384. url = oldUrl;
  9385. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9386. }
  9387. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9388. var isTGA = (extension === ".tga");
  9389. scene._addPendingData(texture);
  9390. texture.url = url;
  9391. texture.noMipmap = noMipmap;
  9392. texture.references = 1;
  9393. texture.samplingMode = samplingMode;
  9394. texture.onLoadedCallbacks = [];
  9395. if (onLoad) {
  9396. texture.onLoadedCallbacks.push(onLoad);
  9397. }
  9398. if (!fallBack)
  9399. this._loadedTexturesCache.push(texture);
  9400. var onerror = function () {
  9401. scene._removePendingData(texture);
  9402. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9403. if (isKTX) {
  9404. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9405. }
  9406. else if (onError) {
  9407. onError();
  9408. }
  9409. };
  9410. var callback;
  9411. if (isKTX || isTGA || isDDS) {
  9412. if (isKTX) {
  9413. callback = function (data) {
  9414. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9415. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9416. ktx.uploadLevels(_this._gl, !noMipmap);
  9417. }, samplingMode);
  9418. };
  9419. }
  9420. else if (isTGA) {
  9421. callback = function (arrayBuffer) {
  9422. var data = new Uint8Array(arrayBuffer);
  9423. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9424. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9425. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9426. }, samplingMode);
  9427. };
  9428. }
  9429. else if (isDDS) {
  9430. callback = function (data) {
  9431. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9432. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9433. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9434. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9435. }, samplingMode);
  9436. };
  9437. }
  9438. if (!(fromData instanceof Array))
  9439. BABYLON.Tools.LoadFile(url, function (data) {
  9440. callback(data);
  9441. }, null, scene.database, true, onerror);
  9442. else
  9443. callback(buffer);
  9444. }
  9445. else {
  9446. var onload = function (img) {
  9447. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9448. var isPot = (img.width === potWidth && img.height === potHeight);
  9449. if (!isPot) {
  9450. _this._prepareWorkingCanvas();
  9451. _this._workingCanvas.width = potWidth;
  9452. _this._workingCanvas.height = potHeight;
  9453. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9454. _this._workingContext.imageSmoothingEnabled = false;
  9455. _this._workingContext.mozImageSmoothingEnabled = false;
  9456. _this._workingContext.oImageSmoothingEnabled = false;
  9457. _this._workingContext.webkitImageSmoothingEnabled = false;
  9458. _this._workingContext.msImageSmoothingEnabled = false;
  9459. }
  9460. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9461. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9462. _this._workingContext.imageSmoothingEnabled = true;
  9463. _this._workingContext.mozImageSmoothingEnabled = true;
  9464. _this._workingContext.oImageSmoothingEnabled = true;
  9465. _this._workingContext.webkitImageSmoothingEnabled = true;
  9466. _this._workingContext.msImageSmoothingEnabled = true;
  9467. }
  9468. }
  9469. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9470. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9471. }, samplingMode);
  9472. };
  9473. if (!(fromData instanceof Array))
  9474. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9475. else
  9476. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9477. }
  9478. return texture;
  9479. };
  9480. Engine.prototype._getInternalFormat = function (format) {
  9481. var internalFormat = this._gl.RGBA;
  9482. switch (format) {
  9483. case Engine.TEXTUREFORMAT_ALPHA:
  9484. internalFormat = this._gl.ALPHA;
  9485. break;
  9486. case Engine.TEXTUREFORMAT_LUMINANCE:
  9487. internalFormat = this._gl.LUMINANCE;
  9488. break;
  9489. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9490. internalFormat = this._gl.LUMINANCE_ALPHA;
  9491. break;
  9492. case Engine.TEXTUREFORMAT_RGB:
  9493. internalFormat = this._gl.RGB;
  9494. break;
  9495. case Engine.TEXTUREFORMAT_RGBA:
  9496. internalFormat = this._gl.RGBA;
  9497. break;
  9498. }
  9499. return internalFormat;
  9500. };
  9501. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9502. if (compression === void 0) { compression = null; }
  9503. var internalFormat = this._getInternalFormat(format);
  9504. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9505. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9506. if (texture._width % 4 !== 0) {
  9507. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9508. }
  9509. if (compression) {
  9510. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9511. }
  9512. else {
  9513. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9514. }
  9515. if (texture.generateMipMaps) {
  9516. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9517. }
  9518. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9519. this.resetTextureCache();
  9520. texture.isReady = true;
  9521. };
  9522. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9523. if (compression === void 0) { compression = null; }
  9524. var texture = this._gl.createTexture();
  9525. texture._baseWidth = width;
  9526. texture._baseHeight = height;
  9527. texture._width = width;
  9528. texture._height = height;
  9529. texture.references = 1;
  9530. this.updateRawTexture(texture, data, format, invertY, compression);
  9531. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9532. // Filters
  9533. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9534. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9536. if (generateMipMaps) {
  9537. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9538. }
  9539. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9540. texture.samplingMode = samplingMode;
  9541. this._loadedTexturesCache.push(texture);
  9542. return texture;
  9543. };
  9544. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9545. var texture = this._gl.createTexture();
  9546. texture._baseWidth = width;
  9547. texture._baseHeight = height;
  9548. if (generateMipMaps) {
  9549. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9550. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9551. }
  9552. this.resetTextureCache();
  9553. texture._width = width;
  9554. texture._height = height;
  9555. texture.isReady = false;
  9556. texture.generateMipMaps = generateMipMaps;
  9557. texture.references = 1;
  9558. texture.samplingMode = samplingMode;
  9559. this.updateTextureSamplingMode(samplingMode, texture);
  9560. this._loadedTexturesCache.push(texture);
  9561. return texture;
  9562. };
  9563. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9564. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9565. if (texture.isCube) {
  9566. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9567. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9568. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9569. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9570. }
  9571. else {
  9572. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9573. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9574. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9575. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9576. }
  9577. texture.samplingMode = samplingMode;
  9578. };
  9579. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9580. if (premulAlpha === void 0) { premulAlpha = false; }
  9581. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9582. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9583. if (premulAlpha) {
  9584. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9585. }
  9586. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9587. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9588. if (texture.generateMipMaps) {
  9589. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9590. }
  9591. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9592. if (premulAlpha) {
  9593. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9594. }
  9595. this.resetTextureCache();
  9596. texture.isReady = true;
  9597. };
  9598. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9599. if (texture._isDisabled) {
  9600. return;
  9601. }
  9602. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9603. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9604. try {
  9605. // Testing video texture support
  9606. if (this._videoTextureSupported === undefined) {
  9607. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9608. if (this._gl.getError() !== 0) {
  9609. this._videoTextureSupported = false;
  9610. }
  9611. else {
  9612. this._videoTextureSupported = true;
  9613. }
  9614. }
  9615. // Copy video through the current working canvas if video texture is not supported
  9616. if (!this._videoTextureSupported) {
  9617. if (!texture._workingCanvas) {
  9618. texture._workingCanvas = document.createElement("canvas");
  9619. texture._workingContext = texture._workingCanvas.getContext("2d");
  9620. texture._workingCanvas.width = texture._width;
  9621. texture._workingCanvas.height = texture._height;
  9622. }
  9623. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9624. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9625. }
  9626. else {
  9627. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9628. }
  9629. if (texture.generateMipMaps) {
  9630. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9631. }
  9632. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9633. this.resetTextureCache();
  9634. texture.isReady = true;
  9635. }
  9636. catch (ex) {
  9637. // Something unexpected
  9638. // Let's disable the texture
  9639. texture._isDisabled = true;
  9640. }
  9641. };
  9642. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9643. // old version had a "generateMipMaps" arg instead of options.
  9644. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9645. // in the same way, generateDepthBuffer is defaulted to true
  9646. var generateMipMaps = false;
  9647. var generateDepthBuffer = true;
  9648. var generateStencilBuffer = false;
  9649. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9650. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9651. if (options !== undefined) {
  9652. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9653. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9654. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9655. type = options.type === undefined ? type : options.type;
  9656. if (options.samplingMode !== undefined) {
  9657. samplingMode = options.samplingMode;
  9658. }
  9659. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9660. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9661. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9662. }
  9663. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9664. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9665. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9666. }
  9667. }
  9668. var gl = this._gl;
  9669. var texture = gl.createTexture();
  9670. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9671. var width = size.width || size;
  9672. var height = size.height || size;
  9673. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9674. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9675. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9676. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9677. }
  9678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9682. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9683. var depthStencilBuffer;
  9684. // Create the depth/stencil buffer
  9685. if (generateStencilBuffer) {
  9686. depthStencilBuffer = gl.createRenderbuffer();
  9687. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9688. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9689. }
  9690. else if (generateDepthBuffer) {
  9691. depthStencilBuffer = gl.createRenderbuffer();
  9692. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9693. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9694. }
  9695. // Create the framebuffer
  9696. var framebuffer = gl.createFramebuffer();
  9697. this.bindUnboundFramebuffer(framebuffer);
  9698. // Manage attachments
  9699. if (generateStencilBuffer) {
  9700. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9701. }
  9702. else if (generateDepthBuffer) {
  9703. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9704. }
  9705. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9706. if (generateMipMaps) {
  9707. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9708. }
  9709. // Unbind
  9710. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9712. this.bindUnboundFramebuffer(null);
  9713. texture._framebuffer = framebuffer;
  9714. if (generateDepthBuffer) {
  9715. texture._depthBuffer = depthStencilBuffer;
  9716. }
  9717. texture._baseWidth = width;
  9718. texture._baseHeight = height;
  9719. texture._width = width;
  9720. texture._height = height;
  9721. texture.isReady = true;
  9722. texture.generateMipMaps = generateMipMaps;
  9723. texture.references = 1;
  9724. texture.samplingMode = samplingMode;
  9725. texture.type = type;
  9726. this.resetTextureCache();
  9727. this._loadedTexturesCache.push(texture);
  9728. return texture;
  9729. };
  9730. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9731. var gl = this._gl;
  9732. var texture = gl.createTexture();
  9733. var generateMipMaps = true;
  9734. var generateDepthBuffer = true;
  9735. var generateStencilBuffer = false;
  9736. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9737. if (options !== undefined) {
  9738. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9739. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9740. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9741. if (options.samplingMode !== undefined) {
  9742. samplingMode = options.samplingMode;
  9743. }
  9744. }
  9745. texture.isCube = true;
  9746. texture.references = 1;
  9747. texture.generateMipMaps = generateMipMaps;
  9748. texture.references = 1;
  9749. texture.samplingMode = samplingMode;
  9750. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9752. for (var face = 0; face < 6; face++) {
  9753. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9754. }
  9755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9759. // Create the depth buffer
  9760. var depthStencilBuffer;
  9761. // Create the depth/stencil buffer
  9762. if (generateStencilBuffer) {
  9763. depthStencilBuffer = gl.createRenderbuffer();
  9764. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9765. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  9766. }
  9767. else if (generateDepthBuffer) {
  9768. depthStencilBuffer = gl.createRenderbuffer();
  9769. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9770. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  9771. }
  9772. // Create the framebuffer
  9773. var framebuffer = gl.createFramebuffer();
  9774. this.bindUnboundFramebuffer(framebuffer);
  9775. // Manage attachments
  9776. if (generateStencilBuffer) {
  9777. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9778. }
  9779. else if (generateDepthBuffer) {
  9780. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9781. }
  9782. // Mipmaps
  9783. if (texture.generateMipMaps) {
  9784. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9786. }
  9787. // Unbind
  9788. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9790. this.bindUnboundFramebuffer(null);
  9791. texture._framebuffer = framebuffer;
  9792. if (generateDepthBuffer) {
  9793. texture._depthBuffer = depthStencilBuffer;
  9794. }
  9795. texture._width = size;
  9796. texture._height = size;
  9797. texture.isReady = true;
  9798. this.resetTextureCache();
  9799. this._loadedTexturesCache.push(texture);
  9800. return texture;
  9801. };
  9802. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9803. var _this = this;
  9804. if (onLoad === void 0) { onLoad = null; }
  9805. if (onError === void 0) { onError = null; }
  9806. var gl = this._gl;
  9807. var texture = gl.createTexture();
  9808. texture.isCube = true;
  9809. texture.url = rootUrl;
  9810. texture.references = 1;
  9811. texture.onLoadedCallbacks = [];
  9812. var isKTX = false;
  9813. var lastDot = rootUrl.lastIndexOf('.');
  9814. var extension = rootUrl.substring(lastDot).toLowerCase();
  9815. if (this._textureFormatInUse) {
  9816. extension = this._textureFormatInUse;
  9817. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9818. isKTX = true;
  9819. }
  9820. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9821. if (isKTX) {
  9822. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9823. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9824. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9825. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9826. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9827. ktx.uploadLevels(_this._gl, !noMipmap);
  9828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9832. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9833. _this.resetTextureCache();
  9834. texture._width = ktx.pixelWidth;
  9835. texture._height = ktx.pixelHeight;
  9836. texture.isReady = true;
  9837. }, null, null, true, onError);
  9838. }
  9839. else if (isDDS) {
  9840. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9841. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9842. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9843. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9844. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9845. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9846. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9848. }
  9849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9853. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9854. _this.resetTextureCache();
  9855. texture._width = info.width;
  9856. texture._height = info.height;
  9857. texture.isReady = true;
  9858. }, null, null, true, onError);
  9859. }
  9860. else {
  9861. cascadeLoad(rootUrl, scene, function (imgs) {
  9862. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9863. var height = width;
  9864. _this._prepareWorkingCanvas();
  9865. _this._workingCanvas.width = width;
  9866. _this._workingCanvas.height = height;
  9867. var faces = [
  9868. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9869. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9870. ];
  9871. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9872. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9873. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9874. for (var index = 0; index < faces.length; index++) {
  9875. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9876. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9877. }
  9878. if (!noMipmap) {
  9879. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9880. }
  9881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9885. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9886. _this.resetTextureCache();
  9887. texture._width = width;
  9888. texture._height = height;
  9889. texture.isReady = true;
  9890. texture.onLoadedCallbacks.forEach(function (callback) {
  9891. callback();
  9892. });
  9893. if (onLoad) {
  9894. onLoad();
  9895. }
  9896. }, files, onError);
  9897. }
  9898. this._loadedTexturesCache.push(texture);
  9899. return texture;
  9900. };
  9901. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9902. texture._width = width;
  9903. texture._height = height;
  9904. texture._size = width * height;
  9905. texture._baseWidth = width;
  9906. texture._baseHeight = height;
  9907. };
  9908. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9909. var _this = this;
  9910. if (onLoad === void 0) { onLoad = null; }
  9911. if (onError === void 0) { onError = null; }
  9912. var gl = this._gl;
  9913. var texture = gl.createTexture();
  9914. scene._addPendingData(texture);
  9915. texture.isCube = true;
  9916. texture.references = 1;
  9917. texture.url = url;
  9918. var textureType = gl.UNSIGNED_BYTE;
  9919. if (type === Engine.TEXTURETYPE_FLOAT) {
  9920. textureType = gl.FLOAT;
  9921. }
  9922. var internalFormat = this._getInternalFormat(format);
  9923. var needConversion = false;
  9924. if (internalFormat === gl.RGB) {
  9925. internalFormat = gl.RGBA;
  9926. needConversion = true;
  9927. }
  9928. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9929. var width = size;
  9930. var height = width;
  9931. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9932. texture._width = width;
  9933. texture._height = height;
  9934. var onerror = function () {
  9935. scene._removePendingData(texture);
  9936. if (onError) {
  9937. onError();
  9938. }
  9939. };
  9940. var internalCallback = function (data) {
  9941. var rgbeDataArrays = callback(data);
  9942. var facesIndex = [
  9943. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9944. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9945. ];
  9946. width = texture._width;
  9947. height = texture._height;
  9948. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9951. if (mipmmapGenerator) {
  9952. var arrayTemp = [];
  9953. // Data are known to be in +X +Y +Z -X -Y -Z
  9954. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9955. arrayTemp.push(rgbeDataArrays[0]); // +X
  9956. arrayTemp.push(rgbeDataArrays[3]); // -X
  9957. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9958. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9959. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9960. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9961. var mipData = mipmmapGenerator(arrayTemp);
  9962. // mipData is order in +X -X +Y -Y +Z -Z
  9963. var mipFaces = [0, 2, 4, 1, 3, 5];
  9964. for (var level = 0; level < mipData.length; level++) {
  9965. var mipSize = width >> level;
  9966. for (var mipIndex in mipFaces) {
  9967. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9968. if (needConversion) {
  9969. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9970. }
  9971. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9972. }
  9973. }
  9974. }
  9975. else {
  9976. // Data are known to be in +X +Y +Z -X -Y -Z
  9977. for (var index = 0; index < facesIndex.length; index++) {
  9978. var faceData = rgbeDataArrays[index];
  9979. if (needConversion) {
  9980. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9981. }
  9982. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9983. }
  9984. if (!noMipmap && isPot) {
  9985. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9986. }
  9987. else {
  9988. noMipmap = true;
  9989. }
  9990. }
  9991. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9994. }
  9995. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9998. }
  9999. else {
  10000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10002. }
  10003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10006. texture.isReady = true;
  10007. _this.resetTextureCache();
  10008. scene._removePendingData(texture);
  10009. if (onLoad) {
  10010. onLoad();
  10011. }
  10012. };
  10013. BABYLON.Tools.LoadFile(url, function (data) {
  10014. internalCallback(data);
  10015. }, onerror, scene.database, true);
  10016. return texture;
  10017. };
  10018. ;
  10019. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10020. // Create new RGBA data container.
  10021. var rgbaData;
  10022. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10023. rgbaData = new Float32Array(width * height * 4);
  10024. }
  10025. else {
  10026. rgbaData = new Uint32Array(width * height * 4);
  10027. }
  10028. // Convert each pixel.
  10029. for (var x = 0; x < width; x++) {
  10030. for (var y = 0; y < height; y++) {
  10031. var index = (y * width + x) * 3;
  10032. var newIndex = (y * width + x) * 4;
  10033. // Map Old Value to new value.
  10034. rgbaData[newIndex + 0] = rgbData[index + 0];
  10035. rgbaData[newIndex + 1] = rgbData[index + 1];
  10036. rgbaData[newIndex + 2] = rgbData[index + 2];
  10037. // Add fully opaque alpha channel.
  10038. rgbaData[newIndex + 3] = 1;
  10039. }
  10040. }
  10041. return rgbaData;
  10042. };
  10043. Engine.prototype._releaseTexture = function (texture) {
  10044. var gl = this._gl;
  10045. if (texture._framebuffer) {
  10046. gl.deleteFramebuffer(texture._framebuffer);
  10047. }
  10048. if (texture._depthBuffer) {
  10049. gl.deleteRenderbuffer(texture._depthBuffer);
  10050. }
  10051. gl.deleteTexture(texture);
  10052. // Unbind channels
  10053. this.unbindAllTextures();
  10054. var index = this._loadedTexturesCache.indexOf(texture);
  10055. if (index !== -1) {
  10056. this._loadedTexturesCache.splice(index, 1);
  10057. }
  10058. };
  10059. Engine.prototype.setProgram = function (program) {
  10060. if (this._currentProgram !== program) {
  10061. this._gl.useProgram(program);
  10062. this._currentProgram = program;
  10063. }
  10064. };
  10065. Engine.prototype.bindSamplers = function (effect) {
  10066. this.setProgram(effect.getProgram());
  10067. var samplers = effect.getSamplers();
  10068. for (var index = 0; index < samplers.length; index++) {
  10069. var uniform = effect.getUniform(samplers[index]);
  10070. this._gl.uniform1i(uniform, index);
  10071. }
  10072. this._currentEffect = null;
  10073. };
  10074. Engine.prototype.activateTexture = function (texture) {
  10075. if (this._activeTexture !== texture) {
  10076. this._gl.activeTexture(texture);
  10077. this._activeTexture = texture;
  10078. }
  10079. };
  10080. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10081. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10082. this._gl.bindTexture(target, texture);
  10083. this._activeTexturesCache[this._activeTexture] = texture;
  10084. }
  10085. };
  10086. Engine.prototype._bindTexture = function (channel, texture) {
  10087. if (channel < 0) {
  10088. return;
  10089. }
  10090. this.activateTexture(this._gl.TEXTURE0 + channel);
  10091. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10092. };
  10093. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10094. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10095. };
  10096. Engine.prototype.unbindAllTextures = function () {
  10097. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10098. this.activateTexture(this._gl["TEXTURE" + channel]);
  10099. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10100. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10101. }
  10102. };
  10103. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10104. if (channel < 0) {
  10105. return;
  10106. }
  10107. this._gl.uniform1i(uniform, channel);
  10108. this._setTexture(channel, texture);
  10109. };
  10110. Engine.prototype._setTexture = function (channel, texture) {
  10111. // Not ready?
  10112. if (!texture || !texture.isReady()) {
  10113. if (this._activeTexturesCache[channel] != null) {
  10114. this.activateTexture(this._gl["TEXTURE" + channel]);
  10115. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10116. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10117. }
  10118. return;
  10119. }
  10120. // Video
  10121. var alreadyActivated = false;
  10122. if (texture instanceof BABYLON.VideoTexture) {
  10123. this.activateTexture(this._gl["TEXTURE" + channel]);
  10124. alreadyActivated = true;
  10125. texture.update();
  10126. }
  10127. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10128. texture.delayLoad();
  10129. return;
  10130. }
  10131. var internalTexture = texture.getInternalTexture();
  10132. if (this._activeTexturesCache[channel] === internalTexture) {
  10133. return;
  10134. }
  10135. if (!alreadyActivated) {
  10136. this.activateTexture(this._gl["TEXTURE" + channel]);
  10137. }
  10138. if (internalTexture.isCube) {
  10139. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10140. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10141. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10142. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10143. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10144. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10145. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10146. }
  10147. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10148. }
  10149. else {
  10150. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10151. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10152. internalTexture._cachedWrapU = texture.wrapU;
  10153. switch (texture.wrapU) {
  10154. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10155. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10156. break;
  10157. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10158. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10159. break;
  10160. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10162. break;
  10163. }
  10164. }
  10165. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10166. internalTexture._cachedWrapV = texture.wrapV;
  10167. switch (texture.wrapV) {
  10168. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10170. break;
  10171. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10172. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10173. break;
  10174. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10175. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10176. break;
  10177. }
  10178. }
  10179. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10180. }
  10181. };
  10182. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10183. if (channel < 0) {
  10184. return;
  10185. }
  10186. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10187. this._textureUnits = new Int32Array(textures.length);
  10188. }
  10189. for (var i = 0; i < textures.length; i++) {
  10190. this._textureUnits[i] = channel + i;
  10191. }
  10192. this._gl.uniform1iv(uniform, this._textureUnits);
  10193. for (var index = 0; index < textures.length; index++) {
  10194. this._setTexture(channel + index, textures[index]);
  10195. }
  10196. };
  10197. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10198. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10199. var value = texture.anisotropicFilteringLevel;
  10200. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10201. value = 1;
  10202. }
  10203. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10204. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10205. texture._cachedAnisotropicFilteringLevel = value;
  10206. }
  10207. };
  10208. Engine.prototype.readPixels = function (x, y, width, height) {
  10209. var data = new Uint8Array(height * width * 4);
  10210. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10211. return data;
  10212. };
  10213. /**
  10214. * Add an externaly attached data from its key.
  10215. * This method call will fail and return false, if such key already exists.
  10216. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10217. * @param key the unique key that identifies the data
  10218. * @param data the data object to associate to the key for this Engine instance
  10219. * @return true if no such key were already present and the data was added successfully, false otherwise
  10220. */
  10221. Engine.prototype.addExternalData = function (key, data) {
  10222. return this._externalData.add(key, data);
  10223. };
  10224. /**
  10225. * Get an externaly attached data from its key
  10226. * @param key the unique key that identifies the data
  10227. * @return the associated data, if present (can be null), or undefined if not present
  10228. */
  10229. Engine.prototype.getExternalData = function (key) {
  10230. return this._externalData.get(key);
  10231. };
  10232. /**
  10233. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10234. * @param key the unique key that identifies the data
  10235. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10236. * @return the associated data, can be null if the factory returned null.
  10237. */
  10238. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10239. return this._externalData.getOrAddWithFactory(key, factory);
  10240. };
  10241. /**
  10242. * Remove an externaly attached data from the Engine instance
  10243. * @param key the unique key that identifies the data
  10244. * @return true if the data was successfully removed, false if it doesn't exist
  10245. */
  10246. Engine.prototype.removeExternalData = function (key) {
  10247. return this._externalData.remove(key);
  10248. };
  10249. Engine.prototype.releaseInternalTexture = function (texture) {
  10250. if (!texture) {
  10251. return;
  10252. }
  10253. texture.references--;
  10254. // Final reference ?
  10255. if (texture.references === 0) {
  10256. var texturesCache = this.getLoadedTexturesCache();
  10257. var index = texturesCache.indexOf(texture);
  10258. if (index > -1) {
  10259. texturesCache.splice(index, 1);
  10260. }
  10261. this._releaseTexture(texture);
  10262. }
  10263. };
  10264. Engine.prototype.unbindAllAttributes = function () {
  10265. if (this._mustWipeVertexAttributes) {
  10266. this._mustWipeVertexAttributes = false;
  10267. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10268. this._gl.disableVertexAttribArray(i);
  10269. this._vertexAttribArraysEnabled[i] = false;
  10270. this._currentBufferPointers[i] = null;
  10271. }
  10272. return;
  10273. }
  10274. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10275. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10276. continue;
  10277. }
  10278. this._gl.disableVertexAttribArray(i);
  10279. this._vertexAttribArraysEnabled[i] = false;
  10280. this._currentBufferPointers[i] = null;
  10281. }
  10282. };
  10283. // Dispose
  10284. Engine.prototype.dispose = function () {
  10285. this.hideLoadingUI();
  10286. this.stopRenderLoop();
  10287. // Release scenes
  10288. while (this.scenes.length) {
  10289. this.scenes[0].dispose();
  10290. }
  10291. // Release audio engine
  10292. Engine.audioEngine.dispose();
  10293. // Release effects
  10294. for (var name in this._compiledEffects) {
  10295. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10296. }
  10297. // Unbind
  10298. this.unbindAllAttributes();
  10299. this._gl = null;
  10300. //WebVR
  10301. this.disableVR();
  10302. // Events
  10303. window.removeEventListener("blur", this._onBlur);
  10304. window.removeEventListener("focus", this._onFocus);
  10305. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10306. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10307. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10308. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10309. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10310. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10311. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10312. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10313. };
  10314. // Loading screen
  10315. Engine.prototype.displayLoadingUI = function () {
  10316. this._loadingScreen.displayLoadingUI();
  10317. };
  10318. Engine.prototype.hideLoadingUI = function () {
  10319. this._loadingScreen.hideLoadingUI();
  10320. };
  10321. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10322. get: function () {
  10323. return this._loadingScreen;
  10324. },
  10325. set: function (loadingScreen) {
  10326. this._loadingScreen = loadingScreen;
  10327. },
  10328. enumerable: true,
  10329. configurable: true
  10330. });
  10331. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10332. set: function (text) {
  10333. this._loadingScreen.loadingUIText = text;
  10334. },
  10335. enumerable: true,
  10336. configurable: true
  10337. });
  10338. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10339. set: function (color) {
  10340. this._loadingScreen.loadingUIBackgroundColor = color;
  10341. },
  10342. enumerable: true,
  10343. configurable: true
  10344. });
  10345. Engine.prototype.attachContextLostEvent = function (callback) {
  10346. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10347. };
  10348. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10349. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10350. };
  10351. Engine.prototype.getVertexShaderSource = function (program) {
  10352. var shaders = this._gl.getAttachedShaders(program);
  10353. return this._gl.getShaderSource(shaders[0]);
  10354. };
  10355. Engine.prototype.getFragmentShaderSource = function (program) {
  10356. var shaders = this._gl.getAttachedShaders(program);
  10357. return this._gl.getShaderSource(shaders[1]);
  10358. };
  10359. // FPS
  10360. Engine.prototype.getFps = function () {
  10361. return this.fps;
  10362. };
  10363. Engine.prototype.getDeltaTime = function () {
  10364. return this.deltaTime;
  10365. };
  10366. Engine.prototype._measureFps = function () {
  10367. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10368. var length = this.previousFramesDuration.length;
  10369. if (length >= 2) {
  10370. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10371. }
  10372. if (length >= this.fpsRange) {
  10373. if (length > this.fpsRange) {
  10374. this.previousFramesDuration.splice(0, 1);
  10375. length = this.previousFramesDuration.length;
  10376. }
  10377. var sum = 0;
  10378. for (var id = 0; id < length - 1; id++) {
  10379. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10380. }
  10381. this.fps = 1000.0 / (sum / (length - 1));
  10382. }
  10383. };
  10384. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10385. if (this._webGLVersion > 1) {
  10386. return this._caps.colorBufferFloat;
  10387. }
  10388. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10389. };
  10390. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10391. if (this._webGLVersion > 1) {
  10392. return this._caps.colorBufferFloat;
  10393. }
  10394. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10395. };
  10396. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10397. Engine.prototype._canRenderToFramebuffer = function (type) {
  10398. var gl = this._gl;
  10399. //clear existing errors
  10400. while (gl.getError() !== gl.NO_ERROR) { }
  10401. var successful = true;
  10402. var texture = gl.createTexture();
  10403. gl.bindTexture(gl.TEXTURE_2D, texture);
  10404. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10407. var fb = gl.createFramebuffer();
  10408. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10409. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10410. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10411. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10412. successful = successful && (gl.getError() === gl.NO_ERROR);
  10413. //try render by clearing frame buffer's color buffer
  10414. if (successful) {
  10415. gl.clear(gl.COLOR_BUFFER_BIT);
  10416. successful = successful && (gl.getError() === gl.NO_ERROR);
  10417. }
  10418. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10419. if (successful) {
  10420. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10421. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10422. var readFormat = gl.RGBA;
  10423. var readType = gl.UNSIGNED_BYTE;
  10424. var buffer = new Uint8Array(4);
  10425. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10426. successful = successful && (gl.getError() === gl.NO_ERROR);
  10427. }
  10428. //clean up
  10429. gl.deleteTexture(texture);
  10430. gl.deleteFramebuffer(fb);
  10431. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10432. //clear accumulated errors
  10433. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10434. return successful;
  10435. };
  10436. Engine.prototype._getWebGLTextureType = function (type) {
  10437. if (type === Engine.TEXTURETYPE_FLOAT) {
  10438. return this._gl.FLOAT;
  10439. }
  10440. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10441. // Add Half Float Constant.
  10442. return Engine.HALF_FLOAT_OES;
  10443. }
  10444. return this._gl.UNSIGNED_BYTE;
  10445. };
  10446. ;
  10447. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10448. if (this._webGLVersion === 1) {
  10449. return this._gl.RGBA;
  10450. }
  10451. if (type === Engine.TEXTURETYPE_FLOAT) {
  10452. return Engine.RGBA32F;
  10453. }
  10454. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10455. return Engine.RGBA16F;
  10456. }
  10457. return this._gl.RGBA;
  10458. };
  10459. ;
  10460. // Statics
  10461. Engine.isSupported = function () {
  10462. try {
  10463. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10464. if (navigator.isCocoonJS) {
  10465. return true;
  10466. }
  10467. var tempcanvas = document.createElement("canvas");
  10468. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10469. return gl != null && !!window.WebGLRenderingContext;
  10470. }
  10471. catch (e) {
  10472. return false;
  10473. }
  10474. };
  10475. return Engine;
  10476. }());
  10477. // Const statics
  10478. Engine._ALPHA_DISABLE = 0;
  10479. Engine._ALPHA_ADD = 1;
  10480. Engine._ALPHA_COMBINE = 2;
  10481. Engine._ALPHA_SUBTRACT = 3;
  10482. Engine._ALPHA_MULTIPLY = 4;
  10483. Engine._ALPHA_MAXIMIZED = 5;
  10484. Engine._ALPHA_ONEONE = 6;
  10485. Engine._ALPHA_PREMULTIPLIED = 7;
  10486. Engine._DELAYLOADSTATE_NONE = 0;
  10487. Engine._DELAYLOADSTATE_LOADED = 1;
  10488. Engine._DELAYLOADSTATE_LOADING = 2;
  10489. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10490. Engine._TEXTUREFORMAT_ALPHA = 0;
  10491. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10492. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10493. Engine._TEXTUREFORMAT_RGB = 4;
  10494. Engine._TEXTUREFORMAT_RGBA = 5;
  10495. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10496. Engine._TEXTURETYPE_FLOAT = 1;
  10497. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10498. // Depht or Stencil test Constants.
  10499. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10500. 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.
  10501. 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.
  10502. 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.
  10503. 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.
  10504. 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.
  10505. 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.
  10506. 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.
  10507. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10508. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10509. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10510. // Stencil Actions Constants.
  10511. Engine._KEEP = 0x1E00;
  10512. Engine._REPLACE = 0x1E01;
  10513. Engine._INCR = 0x1E02;
  10514. Engine._DECR = 0x1E03;
  10515. Engine._INVERT = 0x150A;
  10516. Engine._INCR_WRAP = 0x8507;
  10517. Engine._DECR_WRAP = 0x8508;
  10518. // Updatable statics so stick with vars here
  10519. Engine.CollisionsEpsilon = 0.001;
  10520. Engine.CodeRepository = "src/";
  10521. Engine.ShadersRepository = "src/Shaders/";
  10522. BABYLON.Engine = Engine;
  10523. })(BABYLON || (BABYLON = {}));
  10524. //# sourceMappingURL=babylon.engine.js.map
  10525. /// <reference path="Tools\babylon.decorators.ts" />
  10526. var BABYLON;
  10527. (function (BABYLON) {
  10528. /**
  10529. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10530. */
  10531. var Node = (function () {
  10532. /**
  10533. * @constructor
  10534. * @param {string} name - the name and id to be given to this node
  10535. * @param {BABYLON.Scene} the scene this node will be added to
  10536. */
  10537. function Node(name, scene) {
  10538. this.state = "";
  10539. this.metadata = null;
  10540. this.doNotSerialize = false;
  10541. this.animations = new Array();
  10542. this._ranges = {};
  10543. this._childrenFlag = -1;
  10544. this._isEnabled = true;
  10545. this._isReady = true;
  10546. this._currentRenderId = -1;
  10547. this._parentRenderId = -1;
  10548. /**
  10549. * An event triggered when the mesh is disposed.
  10550. * @type {BABYLON.Observable}
  10551. */
  10552. this.onDisposeObservable = new BABYLON.Observable();
  10553. this.name = name;
  10554. this.id = name;
  10555. this._scene = scene;
  10556. this._initCache();
  10557. }
  10558. Object.defineProperty(Node.prototype, "parent", {
  10559. get: function () {
  10560. return this._parentNode;
  10561. },
  10562. set: function (parent) {
  10563. if (this._parentNode === parent) {
  10564. return;
  10565. }
  10566. if (this._parentNode) {
  10567. var index = this._parentNode._children.indexOf(this);
  10568. if (index !== -1) {
  10569. this._parentNode._children.splice(index, 1);
  10570. }
  10571. }
  10572. this._parentNode = parent;
  10573. if (this._parentNode) {
  10574. if (!this._parentNode._children) {
  10575. this._parentNode._children = new Array();
  10576. }
  10577. this._parentNode._children.push(this);
  10578. }
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Node.prototype.getClassName = function () {
  10584. return "Node";
  10585. };
  10586. Object.defineProperty(Node.prototype, "onDispose", {
  10587. set: function (callback) {
  10588. if (this._onDisposeObserver) {
  10589. this.onDisposeObservable.remove(this._onDisposeObserver);
  10590. }
  10591. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Node.prototype.getScene = function () {
  10597. return this._scene;
  10598. };
  10599. Node.prototype.getEngine = function () {
  10600. return this._scene.getEngine();
  10601. };
  10602. // override it in derived class
  10603. Node.prototype.getWorldMatrix = function () {
  10604. return BABYLON.Matrix.Identity();
  10605. };
  10606. // override it in derived class if you add new variables to the cache
  10607. // and call the parent class method
  10608. Node.prototype._initCache = function () {
  10609. this._cache = {};
  10610. this._cache.parent = undefined;
  10611. };
  10612. Node.prototype.updateCache = function (force) {
  10613. if (!force && this.isSynchronized())
  10614. return;
  10615. this._cache.parent = this.parent;
  10616. this._updateCache();
  10617. };
  10618. // override it in derived class if you add new variables to the cache
  10619. // and call the parent class method if !ignoreParentClass
  10620. Node.prototype._updateCache = function (ignoreParentClass) {
  10621. };
  10622. // override it in derived class if you add new variables to the cache
  10623. Node.prototype._isSynchronized = function () {
  10624. return true;
  10625. };
  10626. Node.prototype._markSyncedWithParent = function () {
  10627. this._parentRenderId = this.parent._currentRenderId;
  10628. };
  10629. Node.prototype.isSynchronizedWithParent = function () {
  10630. if (!this.parent) {
  10631. return true;
  10632. }
  10633. if (this._parentRenderId !== this.parent._currentRenderId) {
  10634. return false;
  10635. }
  10636. return this.parent.isSynchronized();
  10637. };
  10638. Node.prototype.isSynchronized = function (updateCache) {
  10639. var check = this.hasNewParent();
  10640. check = check || !this.isSynchronizedWithParent();
  10641. check = check || !this._isSynchronized();
  10642. if (updateCache)
  10643. this.updateCache(true);
  10644. return !check;
  10645. };
  10646. Node.prototype.hasNewParent = function (update) {
  10647. if (this._cache.parent === this.parent)
  10648. return false;
  10649. if (update)
  10650. this._cache.parent = this.parent;
  10651. return true;
  10652. };
  10653. /**
  10654. * Is this node ready to be used/rendered
  10655. * @return {boolean} is it ready
  10656. */
  10657. Node.prototype.isReady = function () {
  10658. return this._isReady;
  10659. };
  10660. /**
  10661. * Is this node enabled.
  10662. * If the node has a parent and is enabled, the parent will be inspected as well.
  10663. * @return {boolean} whether this node (and its parent) is enabled.
  10664. * @see setEnabled
  10665. */
  10666. Node.prototype.isEnabled = function () {
  10667. if (!this._isEnabled) {
  10668. return false;
  10669. }
  10670. if (this.parent) {
  10671. return this.parent.isEnabled();
  10672. }
  10673. return true;
  10674. };
  10675. /**
  10676. * Set the enabled state of this node.
  10677. * @param {boolean} value - the new enabled state
  10678. * @see isEnabled
  10679. */
  10680. Node.prototype.setEnabled = function (value) {
  10681. this._isEnabled = value;
  10682. };
  10683. /**
  10684. * Is this node a descendant of the given node.
  10685. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10686. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10687. * @see parent
  10688. */
  10689. Node.prototype.isDescendantOf = function (ancestor) {
  10690. if (this.parent) {
  10691. if (this.parent === ancestor) {
  10692. return true;
  10693. }
  10694. return this.parent.isDescendantOf(ancestor);
  10695. }
  10696. return false;
  10697. };
  10698. /**
  10699. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10700. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10701. * @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.
  10702. * @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.
  10703. */
  10704. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10705. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10706. if (!this._children) {
  10707. return;
  10708. }
  10709. for (var index = 0; index < this._children.length; index++) {
  10710. var item = this._children[index];
  10711. if (!predicate || predicate(item)) {
  10712. results.push(item);
  10713. }
  10714. if (!directDescendantsOnly) {
  10715. item._getDescendants(results, false, predicate);
  10716. }
  10717. }
  10718. };
  10719. /**
  10720. * Will return all nodes that have this node as ascendant.
  10721. * @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.
  10722. * @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.
  10723. * @return {BABYLON.Node[]} all children nodes of all types.
  10724. */
  10725. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10726. var results = [];
  10727. this._getDescendants(results, directDescendantsOnly, predicate);
  10728. return results;
  10729. };
  10730. /**
  10731. * @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.
  10732. * @Deprecated, legacy support.
  10733. * use getDecendants instead.
  10734. */
  10735. Node.prototype.getChildren = function (predicate) {
  10736. return this.getDescendants(true, predicate);
  10737. };
  10738. /**
  10739. * Get all child-meshes of this node.
  10740. */
  10741. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10742. var results = [];
  10743. this._getDescendants(results, directDecendantsOnly, function (node) {
  10744. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10745. });
  10746. return results;
  10747. };
  10748. Node.prototype._setReady = function (state) {
  10749. if (state === this._isReady) {
  10750. return;
  10751. }
  10752. if (!state) {
  10753. this._isReady = false;
  10754. return;
  10755. }
  10756. this._isReady = true;
  10757. if (this.onReady) {
  10758. this.onReady(this);
  10759. }
  10760. };
  10761. Node.prototype.getAnimationByName = function (name) {
  10762. for (var i = 0; i < this.animations.length; i++) {
  10763. var animation = this.animations[i];
  10764. if (animation.name === name) {
  10765. return animation;
  10766. }
  10767. }
  10768. return null;
  10769. };
  10770. Node.prototype.createAnimationRange = function (name, from, to) {
  10771. // check name not already in use
  10772. if (!this._ranges[name]) {
  10773. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10774. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10775. if (this.animations[i]) {
  10776. this.animations[i].createRange(name, from, to);
  10777. }
  10778. }
  10779. }
  10780. };
  10781. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10782. if (deleteFrames === void 0) { deleteFrames = true; }
  10783. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10784. if (this.animations[i]) {
  10785. this.animations[i].deleteRange(name, deleteFrames);
  10786. }
  10787. }
  10788. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10789. };
  10790. Node.prototype.getAnimationRange = function (name) {
  10791. return this._ranges[name];
  10792. };
  10793. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10794. var range = this.getAnimationRange(name);
  10795. if (!range) {
  10796. return null;
  10797. }
  10798. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10799. };
  10800. Node.prototype.serializeAnimationRanges = function () {
  10801. var serializationRanges = [];
  10802. for (var name in this._ranges) {
  10803. var range = {};
  10804. range.name = name;
  10805. range.from = this._ranges[name].from;
  10806. range.to = this._ranges[name].to;
  10807. serializationRanges.push(range);
  10808. }
  10809. return serializationRanges;
  10810. };
  10811. Node.prototype.dispose = function () {
  10812. this.parent = null;
  10813. // Callback
  10814. this.onDisposeObservable.notifyObservers(this);
  10815. this.onDisposeObservable.clear();
  10816. };
  10817. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10818. if (parsedNode.ranges) {
  10819. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10820. var data = parsedNode.ranges[index];
  10821. node.createAnimationRange(data.name, data.from, data.to);
  10822. }
  10823. }
  10824. };
  10825. return Node;
  10826. }());
  10827. __decorate([
  10828. BABYLON.serialize()
  10829. ], Node.prototype, "name", void 0);
  10830. __decorate([
  10831. BABYLON.serialize()
  10832. ], Node.prototype, "id", void 0);
  10833. __decorate([
  10834. BABYLON.serialize()
  10835. ], Node.prototype, "uniqueId", void 0);
  10836. __decorate([
  10837. BABYLON.serialize()
  10838. ], Node.prototype, "state", void 0);
  10839. __decorate([
  10840. BABYLON.serialize()
  10841. ], Node.prototype, "metadata", void 0);
  10842. BABYLON.Node = Node;
  10843. })(BABYLON || (BABYLON = {}));
  10844. //# sourceMappingURL=babylon.node.js.map
  10845. var BABYLON;
  10846. (function (BABYLON) {
  10847. var FilesInput = (function () {
  10848. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  10849. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  10850. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  10851. this._engine = p_engine;
  10852. this._canvas = p_canvas;
  10853. this._currentScene = p_scene;
  10854. this._sceneLoadedCallback = p_sceneLoadedCallback;
  10855. this._progressCallback = p_progressCallback;
  10856. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  10857. this._textureLoadingCallback = p_textureLoadingCallback;
  10858. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  10859. }
  10860. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  10861. var _this = this;
  10862. if (p_elementToMonitor) {
  10863. this._elementToMonitor = p_elementToMonitor;
  10864. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  10865. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  10866. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  10867. }
  10868. };
  10869. FilesInput.prototype.renderFunction = function () {
  10870. if (this._additionnalRenderLoopLogicCallback) {
  10871. this._additionnalRenderLoopLogicCallback();
  10872. }
  10873. if (this._currentScene) {
  10874. if (this._textureLoadingCallback) {
  10875. var remaining = this._currentScene.getWaitingItemsCount();
  10876. if (remaining > 0) {
  10877. this._textureLoadingCallback(remaining);
  10878. }
  10879. }
  10880. this._currentScene.render();
  10881. }
  10882. };
  10883. FilesInput.prototype.drag = function (e) {
  10884. e.stopPropagation();
  10885. e.preventDefault();
  10886. };
  10887. FilesInput.prototype.drop = function (eventDrop) {
  10888. eventDrop.stopPropagation();
  10889. eventDrop.preventDefault();
  10890. this.loadFiles(eventDrop);
  10891. };
  10892. FilesInput.prototype.loadFiles = function (event) {
  10893. if (this._startingProcessingFilesCallback)
  10894. this._startingProcessingFilesCallback();
  10895. // Handling data transfer via drag'n'drop
  10896. if (event && event.dataTransfer && event.dataTransfer.files) {
  10897. this._filesToLoad = event.dataTransfer.files;
  10898. }
  10899. // Handling files from input files
  10900. if (event && event.target && event.target.files) {
  10901. this._filesToLoad = event.target.files;
  10902. }
  10903. if (this._filesToLoad && this._filesToLoad.length > 0) {
  10904. for (var i = 0; i < this._filesToLoad.length; i++) {
  10905. var name_1 = this._filesToLoad[i].name.toLowerCase();
  10906. var extension = name_1.split('.').pop();
  10907. var type = this._filesToLoad[i].type;
  10908. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  10909. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  10910. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  10911. }
  10912. else {
  10913. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  10914. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  10915. this._sceneFileToLoad = this._filesToLoad[i];
  10916. }
  10917. else {
  10918. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  10919. }
  10920. }
  10921. }
  10922. this.reload();
  10923. }
  10924. };
  10925. FilesInput.prototype.reload = function () {
  10926. var _this = this;
  10927. var that = this;
  10928. // If a ".babylon" file has been provided
  10929. if (this._sceneFileToLoad) {
  10930. if (this._currentScene) {
  10931. if (BABYLON.Tools.errorsCount > 0) {
  10932. BABYLON.Tools.ClearLogCache();
  10933. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  10934. }
  10935. this._engine.stopRenderLoop();
  10936. this._currentScene.dispose();
  10937. }
  10938. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  10939. that._currentScene = newScene;
  10940. // Wait for textures and shaders to be ready
  10941. that._currentScene.executeWhenReady(function () {
  10942. // Attach camera to canvas inputs
  10943. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  10944. that._currentScene.createDefaultCameraOrLight();
  10945. }
  10946. that._currentScene.activeCamera.attachControl(that._canvas);
  10947. if (that._sceneLoadedCallback) {
  10948. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  10949. }
  10950. that._engine.runRenderLoop(function () { that.renderFunction(); });
  10951. });
  10952. }, function (progress) {
  10953. if (_this._progressCallback) {
  10954. _this._progressCallback(progress);
  10955. }
  10956. });
  10957. }
  10958. else {
  10959. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  10960. }
  10961. };
  10962. return FilesInput;
  10963. }());
  10964. FilesInput.FilesTextures = new Array();
  10965. FilesInput.FilesToLoad = new Array();
  10966. BABYLON.FilesInput = FilesInput;
  10967. })(BABYLON || (BABYLON = {}));
  10968. //# sourceMappingURL=babylon.filesInput.js.map
  10969. var BABYLON;
  10970. (function (BABYLON) {
  10971. var IntersectionInfo = (function () {
  10972. function IntersectionInfo(bu, bv, distance) {
  10973. this.bu = bu;
  10974. this.bv = bv;
  10975. this.distance = distance;
  10976. this.faceId = 0;
  10977. this.subMeshId = 0;
  10978. }
  10979. return IntersectionInfo;
  10980. }());
  10981. BABYLON.IntersectionInfo = IntersectionInfo;
  10982. var PickingInfo = (function () {
  10983. function PickingInfo() {
  10984. this.hit = false;
  10985. this.distance = 0;
  10986. this.pickedPoint = null;
  10987. this.pickedMesh = null;
  10988. this.bu = 0;
  10989. this.bv = 0;
  10990. this.faceId = -1;
  10991. this.subMeshId = 0;
  10992. this.pickedSprite = null;
  10993. }
  10994. // Methods
  10995. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  10996. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  10997. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  10998. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10999. return null;
  11000. }
  11001. var indices = this.pickedMesh.getIndices();
  11002. var result;
  11003. if (useVerticesNormals) {
  11004. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11005. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11006. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11007. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11008. normal0 = normal0.scale(this.bu);
  11009. normal1 = normal1.scale(this.bv);
  11010. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11011. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11012. }
  11013. else {
  11014. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11015. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11016. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11017. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11018. var p1p2 = vertex1.subtract(vertex2);
  11019. var p3p2 = vertex3.subtract(vertex2);
  11020. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11021. }
  11022. if (useWorldCoordinates) {
  11023. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11024. }
  11025. return BABYLON.Vector3.Normalize(result);
  11026. };
  11027. PickingInfo.prototype.getTextureCoordinates = function () {
  11028. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11029. return null;
  11030. }
  11031. var indices = this.pickedMesh.getIndices();
  11032. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11033. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11034. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11035. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11036. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11037. uv1 = uv1.scale(this.bu);
  11038. uv2 = uv2.scale(this.bv);
  11039. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11040. };
  11041. return PickingInfo;
  11042. }());
  11043. BABYLON.PickingInfo = PickingInfo;
  11044. })(BABYLON || (BABYLON = {}));
  11045. //# sourceMappingURL=babylon.pickingInfo.js.map
  11046. var BABYLON;
  11047. (function (BABYLON) {
  11048. var BoundingSphere = (function () {
  11049. function BoundingSphere(minimum, maximum) {
  11050. this.minimum = minimum;
  11051. this.maximum = maximum;
  11052. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11053. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11054. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11055. this.radius = distance * 0.5;
  11056. this.centerWorld = BABYLON.Vector3.Zero();
  11057. this._update(BABYLON.Matrix.Identity());
  11058. }
  11059. // Methods
  11060. BoundingSphere.prototype._update = function (world) {
  11061. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11062. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11063. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11064. };
  11065. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11066. for (var i = 0; i < 6; i++) {
  11067. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11068. return false;
  11069. }
  11070. return true;
  11071. };
  11072. BoundingSphere.prototype.intersectsPoint = function (point) {
  11073. var x = this.centerWorld.x - point.x;
  11074. var y = this.centerWorld.y - point.y;
  11075. var z = this.centerWorld.z - point.z;
  11076. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11077. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11078. return false;
  11079. return true;
  11080. };
  11081. // Statics
  11082. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11083. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11084. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11085. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11086. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11087. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11088. return false;
  11089. return true;
  11090. };
  11091. return BoundingSphere;
  11092. }());
  11093. BABYLON.BoundingSphere = BoundingSphere;
  11094. })(BABYLON || (BABYLON = {}));
  11095. //# sourceMappingURL=babylon.boundingSphere.js.map
  11096. var BABYLON;
  11097. (function (BABYLON) {
  11098. var BoundingBox = (function () {
  11099. function BoundingBox(minimum, maximum) {
  11100. this.minimum = minimum;
  11101. this.maximum = maximum;
  11102. this.vectors = new Array();
  11103. this.vectorsWorld = new Array();
  11104. // Bounding vectors
  11105. this.vectors.push(this.minimum.clone());
  11106. this.vectors.push(this.maximum.clone());
  11107. this.vectors.push(this.minimum.clone());
  11108. this.vectors[2].x = this.maximum.x;
  11109. this.vectors.push(this.minimum.clone());
  11110. this.vectors[3].y = this.maximum.y;
  11111. this.vectors.push(this.minimum.clone());
  11112. this.vectors[4].z = this.maximum.z;
  11113. this.vectors.push(this.maximum.clone());
  11114. this.vectors[5].z = this.minimum.z;
  11115. this.vectors.push(this.maximum.clone());
  11116. this.vectors[6].x = this.minimum.x;
  11117. this.vectors.push(this.maximum.clone());
  11118. this.vectors[7].y = this.minimum.y;
  11119. // OBB
  11120. this.center = this.maximum.add(this.minimum).scale(0.5);
  11121. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11122. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11123. // World
  11124. for (var index = 0; index < this.vectors.length; index++) {
  11125. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11126. }
  11127. this.minimumWorld = BABYLON.Vector3.Zero();
  11128. this.maximumWorld = BABYLON.Vector3.Zero();
  11129. this._update(BABYLON.Matrix.Identity());
  11130. }
  11131. // Methods
  11132. BoundingBox.prototype.getWorldMatrix = function () {
  11133. return this._worldMatrix;
  11134. };
  11135. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11136. this._worldMatrix.copyFrom(matrix);
  11137. return this;
  11138. };
  11139. BoundingBox.prototype._update = function (world) {
  11140. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11141. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11142. for (var index = 0; index < this.vectors.length; index++) {
  11143. var v = this.vectorsWorld[index];
  11144. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11145. if (v.x < this.minimumWorld.x)
  11146. this.minimumWorld.x = v.x;
  11147. if (v.y < this.minimumWorld.y)
  11148. this.minimumWorld.y = v.y;
  11149. if (v.z < this.minimumWorld.z)
  11150. this.minimumWorld.z = v.z;
  11151. if (v.x > this.maximumWorld.x)
  11152. this.maximumWorld.x = v.x;
  11153. if (v.y > this.maximumWorld.y)
  11154. this.maximumWorld.y = v.y;
  11155. if (v.z > this.maximumWorld.z)
  11156. this.maximumWorld.z = v.z;
  11157. }
  11158. // OBB
  11159. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  11160. this.center.scaleInPlace(0.5);
  11161. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11162. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11163. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11164. this._worldMatrix = world;
  11165. };
  11166. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11167. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11168. };
  11169. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11170. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11171. };
  11172. BoundingBox.prototype.intersectsPoint = function (point) {
  11173. var delta = -BABYLON.Epsilon;
  11174. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11175. return false;
  11176. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11177. return false;
  11178. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11179. return false;
  11180. return true;
  11181. };
  11182. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11183. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11184. };
  11185. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11186. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11187. return false;
  11188. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11189. return false;
  11190. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11191. return false;
  11192. return true;
  11193. };
  11194. // Statics
  11195. BoundingBox.Intersects = function (box0, box1) {
  11196. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11197. return false;
  11198. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11199. return false;
  11200. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11201. return false;
  11202. return true;
  11203. };
  11204. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11205. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11206. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11207. return (num <= (sphereRadius * sphereRadius));
  11208. };
  11209. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11210. for (var p = 0; p < 6; p++) {
  11211. for (var i = 0; i < 8; i++) {
  11212. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11213. return false;
  11214. }
  11215. }
  11216. }
  11217. return true;
  11218. };
  11219. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11220. for (var p = 0; p < 6; p++) {
  11221. var inCount = 8;
  11222. for (var i = 0; i < 8; i++) {
  11223. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11224. --inCount;
  11225. }
  11226. else {
  11227. break;
  11228. }
  11229. }
  11230. if (inCount === 0)
  11231. return false;
  11232. }
  11233. return true;
  11234. };
  11235. return BoundingBox;
  11236. }());
  11237. BABYLON.BoundingBox = BoundingBox;
  11238. })(BABYLON || (BABYLON = {}));
  11239. //# sourceMappingURL=babylon.boundingBox.js.map
  11240. var BABYLON;
  11241. (function (BABYLON) {
  11242. var computeBoxExtents = function (axis, box) {
  11243. var p = BABYLON.Vector3.Dot(box.center, axis);
  11244. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11245. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11246. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11247. var r = r0 + r1 + r2;
  11248. return {
  11249. min: p - r,
  11250. max: p + r
  11251. };
  11252. };
  11253. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11254. var axisOverlap = function (axis, box0, box1) {
  11255. var result0 = computeBoxExtents(axis, box0);
  11256. var result1 = computeBoxExtents(axis, box1);
  11257. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11258. };
  11259. var BoundingInfo = (function () {
  11260. function BoundingInfo(minimum, maximum) {
  11261. this.minimum = minimum;
  11262. this.maximum = maximum;
  11263. this._isLocked = false;
  11264. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11265. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11266. }
  11267. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11268. get: function () {
  11269. return this._isLocked;
  11270. },
  11271. set: function (value) {
  11272. this._isLocked = value;
  11273. },
  11274. enumerable: true,
  11275. configurable: true
  11276. });
  11277. // Methods
  11278. BoundingInfo.prototype.update = function (world) {
  11279. if (this._isLocked) {
  11280. return;
  11281. }
  11282. this.boundingBox._update(world);
  11283. this.boundingSphere._update(world);
  11284. };
  11285. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11286. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11287. return false;
  11288. return this.boundingBox.isInFrustum(frustumPlanes);
  11289. };
  11290. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11291. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11292. };
  11293. BoundingInfo.prototype._checkCollision = function (collider) {
  11294. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11295. };
  11296. BoundingInfo.prototype.intersectsPoint = function (point) {
  11297. if (!this.boundingSphere.centerWorld) {
  11298. return false;
  11299. }
  11300. if (!this.boundingSphere.intersectsPoint(point)) {
  11301. return false;
  11302. }
  11303. if (!this.boundingBox.intersectsPoint(point)) {
  11304. return false;
  11305. }
  11306. return true;
  11307. };
  11308. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11309. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11310. return false;
  11311. }
  11312. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11313. return false;
  11314. }
  11315. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11316. return false;
  11317. }
  11318. if (!precise) {
  11319. return true;
  11320. }
  11321. var box0 = this.boundingBox;
  11322. var box1 = boundingInfo.boundingBox;
  11323. if (!axisOverlap(box0.directions[0], box0, box1))
  11324. return false;
  11325. if (!axisOverlap(box0.directions[1], box0, box1))
  11326. return false;
  11327. if (!axisOverlap(box0.directions[2], box0, box1))
  11328. return false;
  11329. if (!axisOverlap(box1.directions[0], box0, box1))
  11330. return false;
  11331. if (!axisOverlap(box1.directions[1], box0, box1))
  11332. return false;
  11333. if (!axisOverlap(box1.directions[2], box0, box1))
  11334. return false;
  11335. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11336. return false;
  11337. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11338. return false;
  11339. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11340. return false;
  11341. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11342. return false;
  11343. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11344. return false;
  11345. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11346. return false;
  11347. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11348. return false;
  11349. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11350. return false;
  11351. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11352. return false;
  11353. return true;
  11354. };
  11355. return BoundingInfo;
  11356. }());
  11357. BABYLON.BoundingInfo = BoundingInfo;
  11358. })(BABYLON || (BABYLON = {}));
  11359. //# sourceMappingURL=babylon.boundingInfo.js.map
  11360. var BABYLON;
  11361. (function (BABYLON) {
  11362. var Ray = (function () {
  11363. function Ray(origin, direction, length) {
  11364. if (length === void 0) { length = Number.MAX_VALUE; }
  11365. this.origin = origin;
  11366. this.direction = direction;
  11367. this.length = length;
  11368. }
  11369. // Methods
  11370. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11371. var d = 0.0;
  11372. var maxValue = Number.MAX_VALUE;
  11373. var inv;
  11374. var min;
  11375. var max;
  11376. var temp;
  11377. if (Math.abs(this.direction.x) < 0.0000001) {
  11378. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11379. return false;
  11380. }
  11381. }
  11382. else {
  11383. inv = 1.0 / this.direction.x;
  11384. min = (minimum.x - this.origin.x) * inv;
  11385. max = (maximum.x - this.origin.x) * inv;
  11386. if (max === -Infinity) {
  11387. max = Infinity;
  11388. }
  11389. if (min > max) {
  11390. temp = min;
  11391. min = max;
  11392. max = temp;
  11393. }
  11394. d = Math.max(min, d);
  11395. maxValue = Math.min(max, maxValue);
  11396. if (d > maxValue) {
  11397. return false;
  11398. }
  11399. }
  11400. if (Math.abs(this.direction.y) < 0.0000001) {
  11401. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11402. return false;
  11403. }
  11404. }
  11405. else {
  11406. inv = 1.0 / this.direction.y;
  11407. min = (minimum.y - this.origin.y) * inv;
  11408. max = (maximum.y - this.origin.y) * inv;
  11409. if (max === -Infinity) {
  11410. max = Infinity;
  11411. }
  11412. if (min > max) {
  11413. temp = min;
  11414. min = max;
  11415. max = temp;
  11416. }
  11417. d = Math.max(min, d);
  11418. maxValue = Math.min(max, maxValue);
  11419. if (d > maxValue) {
  11420. return false;
  11421. }
  11422. }
  11423. if (Math.abs(this.direction.z) < 0.0000001) {
  11424. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11425. return false;
  11426. }
  11427. }
  11428. else {
  11429. inv = 1.0 / this.direction.z;
  11430. min = (minimum.z - this.origin.z) * inv;
  11431. max = (maximum.z - this.origin.z) * inv;
  11432. if (max === -Infinity) {
  11433. max = Infinity;
  11434. }
  11435. if (min > max) {
  11436. temp = min;
  11437. min = max;
  11438. max = temp;
  11439. }
  11440. d = Math.max(min, d);
  11441. maxValue = Math.min(max, maxValue);
  11442. if (d > maxValue) {
  11443. return false;
  11444. }
  11445. }
  11446. return true;
  11447. };
  11448. Ray.prototype.intersectsBox = function (box) {
  11449. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11450. };
  11451. Ray.prototype.intersectsSphere = function (sphere) {
  11452. var x = sphere.center.x - this.origin.x;
  11453. var y = sphere.center.y - this.origin.y;
  11454. var z = sphere.center.z - this.origin.z;
  11455. var pyth = (x * x) + (y * y) + (z * z);
  11456. var rr = sphere.radius * sphere.radius;
  11457. if (pyth <= rr) {
  11458. return true;
  11459. }
  11460. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11461. if (dot < 0.0) {
  11462. return false;
  11463. }
  11464. var temp = pyth - (dot * dot);
  11465. return temp <= rr;
  11466. };
  11467. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11468. if (!this._edge1) {
  11469. this._edge1 = BABYLON.Vector3.Zero();
  11470. this._edge2 = BABYLON.Vector3.Zero();
  11471. this._pvec = BABYLON.Vector3.Zero();
  11472. this._tvec = BABYLON.Vector3.Zero();
  11473. this._qvec = BABYLON.Vector3.Zero();
  11474. }
  11475. vertex1.subtractToRef(vertex0, this._edge1);
  11476. vertex2.subtractToRef(vertex0, this._edge2);
  11477. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11478. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11479. if (det === 0) {
  11480. return null;
  11481. }
  11482. var invdet = 1 / det;
  11483. this.origin.subtractToRef(vertex0, this._tvec);
  11484. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11485. if (bu < 0 || bu > 1.0) {
  11486. return null;
  11487. }
  11488. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11489. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11490. if (bv < 0 || bu + bv > 1.0) {
  11491. return null;
  11492. }
  11493. //check if the distance is longer than the predefined length.
  11494. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11495. if (distance > this.length) {
  11496. return null;
  11497. }
  11498. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11499. };
  11500. Ray.prototype.intersectsPlane = function (plane) {
  11501. var distance;
  11502. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11503. if (Math.abs(result1) < 9.99999997475243E-07) {
  11504. return null;
  11505. }
  11506. else {
  11507. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11508. distance = (-plane.d - result2) / result1;
  11509. if (distance < 0.0) {
  11510. if (distance < -9.99999997475243E-07) {
  11511. return null;
  11512. }
  11513. else {
  11514. return 0;
  11515. }
  11516. }
  11517. return distance;
  11518. }
  11519. };
  11520. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11521. var tm = BABYLON.Tmp.Matrix[0];
  11522. mesh.getWorldMatrix().invertToRef(tm);
  11523. if (this._tmpRay) {
  11524. Ray.TransformToRef(this, tm, this._tmpRay);
  11525. }
  11526. else {
  11527. this._tmpRay = Ray.Transform(this, tm);
  11528. }
  11529. return mesh.intersects(this._tmpRay, fastCheck);
  11530. };
  11531. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11532. if (results) {
  11533. results.length = 0;
  11534. }
  11535. else {
  11536. results = [];
  11537. }
  11538. for (var i = 0; i < meshes.length; i++) {
  11539. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11540. if (pickInfo.hit) {
  11541. results.push(pickInfo);
  11542. }
  11543. }
  11544. results.sort(this._comparePickingInfo);
  11545. return results;
  11546. };
  11547. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11548. if (pickingInfoA.distance < pickingInfoB.distance) {
  11549. return -1;
  11550. }
  11551. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11552. return 1;
  11553. }
  11554. else {
  11555. return 0;
  11556. }
  11557. };
  11558. /**
  11559. * @Deprecated. Use new RayHelper.show() instead.
  11560. * */
  11561. Ray.prototype.show = function (scene, color) {
  11562. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  11563. if (!this._rayHelper) {
  11564. this._rayHelper = new BABYLON.RayHelper(this);
  11565. }
  11566. this._rayHelper.show(scene, color);
  11567. };
  11568. /**
  11569. * @Deprecated. Use new RayHelper.hide() instead.
  11570. * */
  11571. Ray.prototype.hide = function () {
  11572. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  11573. if (this._rayHelper) {
  11574. this._rayHelper.hide();
  11575. this._rayHelper = null;
  11576. }
  11577. };
  11578. /**
  11579. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11580. * @param sega the first point of the segment to test the intersection against
  11581. * @param segb the second point of the segment to test the intersection against
  11582. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11583. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11584. */
  11585. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11586. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11587. var u = segb.subtract(sega);
  11588. var v = rsegb.subtract(this.origin);
  11589. var w = sega.subtract(this.origin);
  11590. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11591. var b = BABYLON.Vector3.Dot(u, v);
  11592. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11593. var d = BABYLON.Vector3.Dot(u, w);
  11594. var e = BABYLON.Vector3.Dot(v, w);
  11595. var D = a * c - b * b; // always >= 0
  11596. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11597. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11598. // compute the line parameters of the two closest points
  11599. if (D < Ray.smallnum) {
  11600. sN = 0.0; // force using point P0 on segment S1
  11601. sD = 1.0; // to prevent possible division by 0.0 later
  11602. tN = e;
  11603. tD = c;
  11604. }
  11605. else {
  11606. sN = (b * e - c * d);
  11607. tN = (a * e - b * d);
  11608. if (sN < 0.0) {
  11609. sN = 0.0;
  11610. tN = e;
  11611. tD = c;
  11612. }
  11613. else if (sN > sD) {
  11614. sN = sD;
  11615. tN = e + b;
  11616. tD = c;
  11617. }
  11618. }
  11619. if (tN < 0.0) {
  11620. tN = 0.0;
  11621. // recompute sc for this edge
  11622. if (-d < 0.0) {
  11623. sN = 0.0;
  11624. }
  11625. else if (-d > a)
  11626. sN = sD;
  11627. else {
  11628. sN = -d;
  11629. sD = a;
  11630. }
  11631. }
  11632. else if (tN > tD) {
  11633. tN = tD;
  11634. // recompute sc for this edge
  11635. if ((-d + b) < 0.0) {
  11636. sN = 0;
  11637. }
  11638. else if ((-d + b) > a) {
  11639. sN = sD;
  11640. }
  11641. else {
  11642. sN = (-d + b);
  11643. sD = a;
  11644. }
  11645. }
  11646. // finally do the division to get sc and tc
  11647. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11648. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11649. // get the difference of the two closest points
  11650. var qtc = v.multiplyByFloats(tc, tc, tc);
  11651. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11652. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11653. if (isIntersected) {
  11654. return qtc.length();
  11655. }
  11656. return -1;
  11657. };
  11658. // Statics
  11659. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11660. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11661. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11662. var direction = end.subtract(start);
  11663. direction.normalize();
  11664. return new Ray(start, direction);
  11665. };
  11666. /**
  11667. * 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
  11668. * transformed to the given world matrix.
  11669. * @param origin The origin point
  11670. * @param end The end point
  11671. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11672. */
  11673. Ray.CreateNewFromTo = function (origin, end, world) {
  11674. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11675. var direction = end.subtract(origin);
  11676. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11677. direction.normalize();
  11678. return Ray.Transform(new Ray(origin, direction, length), world);
  11679. };
  11680. Ray.Transform = function (ray, matrix) {
  11681. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11682. Ray.TransformToRef(ray, matrix, result);
  11683. return result;
  11684. };
  11685. Ray.TransformToRef = function (ray, matrix, result) {
  11686. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11687. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11688. result.length = ray.length;
  11689. var dir = result.direction;
  11690. var len = dir.length();
  11691. if (!(len === 0 || len === 1)) {
  11692. var num = 1.0 / len;
  11693. dir.x *= num;
  11694. dir.y *= num;
  11695. dir.z *= num;
  11696. result.length *= len;
  11697. }
  11698. };
  11699. return Ray;
  11700. }());
  11701. Ray.smallnum = 0.00000001;
  11702. Ray.rayl = 10e8;
  11703. BABYLON.Ray = Ray;
  11704. })(BABYLON || (BABYLON = {}));
  11705. //# sourceMappingURL=babylon.ray.js.map
  11706. var BABYLON;
  11707. (function (BABYLON) {
  11708. var RayHelper = (function () {
  11709. function RayHelper(ray) {
  11710. this.ray = ray;
  11711. }
  11712. RayHelper.prototype.show = function (scene, color) {
  11713. if (!this._renderFunction) {
  11714. var ray = this.ray;
  11715. this._renderFunction = this._render.bind(this);
  11716. this._scene = scene;
  11717. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11718. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11719. this._scene.registerBeforeRender(this._renderFunction);
  11720. }
  11721. if (color) {
  11722. this._renderLine.color.copyFrom(color);
  11723. }
  11724. };
  11725. RayHelper.prototype.hide = function () {
  11726. if (this._renderFunction) {
  11727. this._scene.unregisterBeforeRender(this._renderFunction);
  11728. this._scene = null;
  11729. this._renderFunction = null;
  11730. this._renderLine.dispose();
  11731. this._renderLine = null;
  11732. this._renderPoints = null;
  11733. }
  11734. };
  11735. RayHelper.prototype._render = function () {
  11736. var ray = this.ray;
  11737. var point = this._renderPoints[1];
  11738. var len = Math.min(ray.length, 1000000);
  11739. point.copyFrom(ray.direction);
  11740. point.scaleInPlace(len);
  11741. point.addInPlace(ray.origin);
  11742. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11743. };
  11744. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11745. this._attachedToMesh = mesh;
  11746. var ray = this.ray;
  11747. if (!ray.direction) {
  11748. ray.direction = BABYLON.Vector3.Zero();
  11749. }
  11750. if (!ray.origin) {
  11751. ray.origin = BABYLON.Vector3.Zero();
  11752. }
  11753. if (length) {
  11754. ray.length = length;
  11755. }
  11756. if (!meshSpaceOrigin) {
  11757. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11758. }
  11759. if (!meshSpaceDirection) {
  11760. // -1 so that this will work with Mesh.lookAt
  11761. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11762. }
  11763. if (!this._meshSpaceDirection) {
  11764. this._meshSpaceDirection = meshSpaceDirection.clone();
  11765. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11766. }
  11767. else {
  11768. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11769. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11770. }
  11771. if (!this._updateToMeshFunction) {
  11772. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11773. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11774. }
  11775. this._updateToMesh();
  11776. };
  11777. RayHelper.prototype.detachFromMesh = function () {
  11778. if (this._attachedToMesh) {
  11779. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11780. this._attachedToMesh = null;
  11781. this._updateToMeshFunction = null;
  11782. }
  11783. };
  11784. RayHelper.prototype._updateToMesh = function () {
  11785. var ray = this.ray;
  11786. if (this._attachedToMesh._isDisposed) {
  11787. this.detachFromMesh();
  11788. return;
  11789. }
  11790. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  11791. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  11792. };
  11793. RayHelper.prototype.dispose = function () {
  11794. this.hide();
  11795. this.detachFromMesh();
  11796. this.ray = null;
  11797. };
  11798. return RayHelper;
  11799. }());
  11800. BABYLON.RayHelper = RayHelper;
  11801. })(BABYLON || (BABYLON = {}));
  11802. //# sourceMappingURL=babylon.rayHelper.js.map
  11803. var BABYLON;
  11804. (function (BABYLON) {
  11805. var AbstractMesh = (function (_super) {
  11806. __extends(AbstractMesh, _super);
  11807. // Constructor
  11808. function AbstractMesh(name, scene) {
  11809. var _this = _super.call(this, name, scene) || this;
  11810. _this._facetNb = 0; // facet number
  11811. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11812. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11813. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11814. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11815. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11816. _this._subDiv = {
  11817. max: 1,
  11818. X: 1,
  11819. Y: 1,
  11820. Z: 1
  11821. };
  11822. // Events
  11823. /**
  11824. * An event triggered when this mesh collides with another one
  11825. * @type {BABYLON.Observable}
  11826. */
  11827. _this.onCollideObservable = new BABYLON.Observable();
  11828. /**
  11829. * An event triggered when the collision's position changes
  11830. * @type {BABYLON.Observable}
  11831. */
  11832. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11833. /**
  11834. * An event triggered after the world matrix is updated
  11835. * @type {BABYLON.Observable}
  11836. */
  11837. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11838. // Properties
  11839. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11840. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11841. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11842. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11843. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11844. _this.visibility = 1.0;
  11845. _this.alphaIndex = Number.MAX_VALUE;
  11846. _this.infiniteDistance = false;
  11847. _this.isVisible = true;
  11848. _this.isPickable = true;
  11849. _this.showBoundingBox = false;
  11850. _this.showSubMeshesBoundingBox = false;
  11851. _this.isBlocker = false;
  11852. _this.renderingGroupId = 0;
  11853. _this.receiveShadows = false;
  11854. _this.renderOutline = false;
  11855. _this.outlineColor = BABYLON.Color3.Red();
  11856. _this.outlineWidth = 0.02;
  11857. _this.renderOverlay = false;
  11858. _this.overlayColor = BABYLON.Color3.Red();
  11859. _this.overlayAlpha = 0.5;
  11860. _this.hasVertexAlpha = false;
  11861. _this.useVertexColors = true;
  11862. _this.applyFog = true;
  11863. _this.computeBonesUsingShaders = true;
  11864. _this.scalingDeterminant = 1;
  11865. _this.numBoneInfluencers = 4;
  11866. _this.useOctreeForRenderingSelection = true;
  11867. _this.useOctreeForPicking = true;
  11868. _this.useOctreeForCollisions = true;
  11869. _this.layerMask = 0x0FFFFFFF;
  11870. /**
  11871. * True if the mesh must be rendered in any case.
  11872. */
  11873. _this.alwaysSelectAsActiveMesh = false;
  11874. // Collisions
  11875. _this._checkCollisions = false;
  11876. _this._collisionMask = -1;
  11877. _this._collisionGroup = -1;
  11878. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11879. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11880. _this._collider = new BABYLON.Collider();
  11881. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11882. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11883. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11884. // Edges
  11885. _this.edgesWidth = 1;
  11886. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11887. // Cache
  11888. _this._localWorld = BABYLON.Matrix.Zero();
  11889. _this._worldMatrix = BABYLON.Matrix.Zero();
  11890. _this._absolutePosition = BABYLON.Vector3.Zero();
  11891. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11892. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11893. _this._isDirty = false;
  11894. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11895. _this._isDisposed = false;
  11896. _this._renderId = 0;
  11897. _this._intersectionsInProgress = new Array();
  11898. _this._isWorldMatrixFrozen = false;
  11899. _this._unIndexed = false;
  11900. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11901. if (collidedMesh === void 0) { collidedMesh = null; }
  11902. //TODO move this to the collision coordinator!
  11903. if (_this.getScene().workerCollisions)
  11904. newPosition.multiplyInPlace(_this._collider.radius);
  11905. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11906. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11907. _this.position.addInPlace(_this._diffPositionForCollisions);
  11908. }
  11909. if (collidedMesh) {
  11910. _this.onCollideObservable.notifyObservers(collidedMesh);
  11911. }
  11912. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11913. };
  11914. scene.addMesh(_this);
  11915. return _this;
  11916. }
  11917. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11918. get: function () {
  11919. return AbstractMesh._BILLBOARDMODE_NONE;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11925. get: function () {
  11926. return AbstractMesh._BILLBOARDMODE_X;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11932. get: function () {
  11933. return AbstractMesh._BILLBOARDMODE_Y;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11939. get: function () {
  11940. return AbstractMesh._BILLBOARDMODE_Z;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11946. get: function () {
  11947. return AbstractMesh._BILLBOARDMODE_ALL;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11953. /**
  11954. * Read-only : the number of facets in the mesh
  11955. */
  11956. get: function () {
  11957. return this._facetNb;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11963. /**
  11964. * The number (integer) of subdivisions per axis in the partioning space
  11965. */
  11966. get: function () {
  11967. return this._partitioningSubdivisions;
  11968. },
  11969. set: function (nb) {
  11970. this._partitioningSubdivisions = nb;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11976. /**
  11977. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11978. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11979. */
  11980. get: function () {
  11981. return this._partitioningBBoxRatio;
  11982. },
  11983. set: function (ratio) {
  11984. this._partitioningBBoxRatio = ratio;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11990. /**
  11991. * Read-only boolean : is the feature facetData enabled ?
  11992. */
  11993. get: function () {
  11994. return this._facetDataEnabled;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12000. set: function (callback) {
  12001. if (this._onCollideObserver) {
  12002. this.onCollideObservable.remove(this._onCollideObserver);
  12003. }
  12004. this._onCollideObserver = this.onCollideObservable.add(callback);
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12010. set: function (callback) {
  12011. if (this._onCollisionPositionChangeObserver) {
  12012. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12013. }
  12014. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12020. get: function () {
  12021. return this._collisionMask;
  12022. },
  12023. set: function (mask) {
  12024. this._collisionMask = !isNaN(mask) ? mask : -1;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12030. get: function () {
  12031. return this._collisionGroup;
  12032. },
  12033. set: function (mask) {
  12034. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12040. get: function () {
  12041. return this._skeleton;
  12042. },
  12043. set: function (value) {
  12044. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12045. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12046. }
  12047. if (value && value.needInitialSkinMatrix) {
  12048. value._registerMeshWithPoseMatrix(this);
  12049. }
  12050. this._skeleton = value;
  12051. if (!this._skeleton) {
  12052. this._bonesTransformMatrices = null;
  12053. }
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. /**
  12059. * Returns the string "AbstractMesh"
  12060. */
  12061. AbstractMesh.prototype.getClassName = function () {
  12062. return "AbstractMesh";
  12063. };
  12064. /**
  12065. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12066. */
  12067. AbstractMesh.prototype.toString = function (fullDetails) {
  12068. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12069. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12070. if (this._skeleton) {
  12071. ret += ", skeleton: " + this._skeleton.name;
  12072. }
  12073. if (fullDetails) {
  12074. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12075. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12076. }
  12077. return ret;
  12078. };
  12079. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12080. /**
  12081. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12082. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12083. * Default : (0.0, 0.0, 0.0)
  12084. */
  12085. get: function () {
  12086. return this._rotation;
  12087. },
  12088. set: function (newRotation) {
  12089. this._rotation = newRotation;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12095. /**
  12096. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12097. * Default : (1.0, 1.0, 1.0)
  12098. */
  12099. get: function () {
  12100. return this._scaling;
  12101. },
  12102. set: function (newScaling) {
  12103. this._scaling = newScaling;
  12104. if (this.physicsImpostor) {
  12105. this.physicsImpostor.forceUpdate();
  12106. }
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12112. /**
  12113. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12114. * It's null by default.
  12115. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12116. */
  12117. get: function () {
  12118. return this._rotationQuaternion;
  12119. },
  12120. set: function (quaternion) {
  12121. this._rotationQuaternion = quaternion;
  12122. //reset the rotation vector.
  12123. if (quaternion && this.rotation.length()) {
  12124. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12125. }
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. // Methods
  12131. /**
  12132. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12133. * Returns the AbstractMesh.
  12134. */
  12135. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12136. this._poseMatrix.copyFrom(matrix);
  12137. return this;
  12138. };
  12139. /**
  12140. * Returns the mesh Pose matrix.
  12141. * Returned object : Matrix
  12142. */
  12143. AbstractMesh.prototype.getPoseMatrix = function () {
  12144. return this._poseMatrix;
  12145. };
  12146. /**
  12147. * Disables the mesh edger rendering mode.
  12148. * Returns the AbstractMesh.
  12149. */
  12150. AbstractMesh.prototype.disableEdgesRendering = function () {
  12151. if (this._edgesRenderer !== undefined) {
  12152. this._edgesRenderer.dispose();
  12153. this._edgesRenderer = undefined;
  12154. }
  12155. return this;
  12156. };
  12157. /**
  12158. * Enables the edge rendering mode on the mesh.
  12159. * This mode makes the mesh edges visible.
  12160. * Returns the AbstractMesh.
  12161. */
  12162. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12163. if (epsilon === void 0) { epsilon = 0.95; }
  12164. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12165. this.disableEdgesRendering();
  12166. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12167. return this;
  12168. };
  12169. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12170. /**
  12171. * Returns true if the mesh is blocked. Used by the class Mesh.
  12172. * Returns the boolean `false` by default.
  12173. */
  12174. get: function () {
  12175. return false;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. /**
  12181. * Returns the mesh itself by default, used by the class Mesh.
  12182. * Returned type : AbstractMesh
  12183. */
  12184. AbstractMesh.prototype.getLOD = function (camera) {
  12185. return this;
  12186. };
  12187. /**
  12188. * Returns 0 by default, used by the class Mesh.
  12189. * Returns an integer.
  12190. */
  12191. AbstractMesh.prototype.getTotalVertices = function () {
  12192. return 0;
  12193. };
  12194. /**
  12195. * Returns null by default, used by the class Mesh.
  12196. * Returned type : integer array
  12197. */
  12198. AbstractMesh.prototype.getIndices = function () {
  12199. return null;
  12200. };
  12201. /**
  12202. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12203. * Returned type : float array or Float32Array
  12204. */
  12205. AbstractMesh.prototype.getVerticesData = function (kind) {
  12206. return null;
  12207. };
  12208. /** Returns false by default, used by the class Mesh.
  12209. * Returns a boolean
  12210. */
  12211. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12212. return false;
  12213. };
  12214. /**
  12215. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12216. * Returns a BoundingInfo
  12217. */
  12218. AbstractMesh.prototype.getBoundingInfo = function () {
  12219. if (this._masterMesh) {
  12220. return this._masterMesh.getBoundingInfo();
  12221. }
  12222. if (!this._boundingInfo) {
  12223. this._updateBoundingInfo();
  12224. }
  12225. return this._boundingInfo;
  12226. };
  12227. /**
  12228. * Sets a mesh new object BoundingInfo.
  12229. * Returns the AbstractMesh.
  12230. */
  12231. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12232. this._boundingInfo = boundingInfo;
  12233. return this;
  12234. };
  12235. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12236. get: function () {
  12237. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. AbstractMesh.prototype._preActivate = function () {
  12243. };
  12244. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12245. };
  12246. AbstractMesh.prototype._activate = function (renderId) {
  12247. this._renderId = renderId;
  12248. };
  12249. /**
  12250. * Returns the last update of the World matrix
  12251. * Returns a Matrix.
  12252. */
  12253. AbstractMesh.prototype.getWorldMatrix = function () {
  12254. if (this._masterMesh) {
  12255. return this._masterMesh.getWorldMatrix();
  12256. }
  12257. if (this._currentRenderId !== this.getScene().getRenderId()) {
  12258. this.computeWorldMatrix();
  12259. }
  12260. return this._worldMatrix;
  12261. };
  12262. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12263. /**
  12264. * Returns directly the last state of the mesh World matrix.
  12265. * A Matrix is returned.
  12266. */
  12267. get: function () {
  12268. return this._worldMatrix;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12274. /**
  12275. * Returns the current mesh absolute position.
  12276. * Retuns a Vector3.
  12277. */
  12278. get: function () {
  12279. return this._absolutePosition;
  12280. },
  12281. enumerable: true,
  12282. configurable: true
  12283. });
  12284. /**
  12285. * Prevents the World matrix to be computed any longer.
  12286. * Returns the AbstractMesh.
  12287. */
  12288. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12289. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12290. this.computeWorldMatrix(true);
  12291. this._isWorldMatrixFrozen = true;
  12292. return this;
  12293. };
  12294. /**
  12295. * Allows back the World matrix computation.
  12296. * Returns the AbstractMesh.
  12297. */
  12298. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12299. this._isWorldMatrixFrozen = false;
  12300. this.computeWorldMatrix(true);
  12301. return this;
  12302. };
  12303. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12304. /**
  12305. * True if the World matrix has been frozen.
  12306. * Returns a boolean.
  12307. */
  12308. get: function () {
  12309. return this._isWorldMatrixFrozen;
  12310. },
  12311. enumerable: true,
  12312. configurable: true
  12313. });
  12314. /**
  12315. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12316. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12317. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12318. * The passed axis is also normalized.
  12319. * Returns the AbstractMesh.
  12320. */
  12321. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12322. axis.normalize();
  12323. if (!this.rotationQuaternion) {
  12324. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12325. this.rotation = BABYLON.Vector3.Zero();
  12326. }
  12327. var rotationQuaternion;
  12328. if (!space || space === BABYLON.Space.LOCAL) {
  12329. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12330. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12331. }
  12332. else {
  12333. if (this.parent) {
  12334. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12335. invertParentWorldMatrix.invert();
  12336. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12337. }
  12338. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12339. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12340. }
  12341. return this;
  12342. };
  12343. /**
  12344. * Translates the mesh along the axis vector for the passed distance in the given space.
  12345. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12346. * Returns the AbstractMesh.
  12347. */
  12348. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12349. var displacementVector = axis.scale(distance);
  12350. if (!space || space === BABYLON.Space.LOCAL) {
  12351. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12352. this.setPositionWithLocalVector(tempV3);
  12353. }
  12354. else {
  12355. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12356. }
  12357. return this;
  12358. };
  12359. /**
  12360. * Adds a rotation step to the mesh current rotation.
  12361. * x, y, z are Euler angles expressed in radians.
  12362. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12363. * This means this rotation is made in the mesh local space only.
  12364. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12365. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12366. * ```javascript
  12367. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12368. * ```
  12369. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12370. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12371. * Returns the AbstractMesh.
  12372. */
  12373. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12374. var rotationQuaternion;
  12375. if (this.rotationQuaternion) {
  12376. rotationQuaternion = this.rotationQuaternion;
  12377. }
  12378. else {
  12379. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12380. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12381. }
  12382. var accumulation = BABYLON.Tmp.Quaternion[0];
  12383. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12384. rotationQuaternion.multiplyInPlace(accumulation);
  12385. if (!this.rotationQuaternion) {
  12386. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12387. }
  12388. return this;
  12389. };
  12390. /**
  12391. * Retuns the mesh absolute position in the World.
  12392. * Returns a Vector3.
  12393. */
  12394. AbstractMesh.prototype.getAbsolutePosition = function () {
  12395. this.computeWorldMatrix();
  12396. return this._absolutePosition;
  12397. };
  12398. /**
  12399. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12400. * Returns the AbstractMesh.
  12401. */
  12402. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12403. if (!absolutePosition) {
  12404. return;
  12405. }
  12406. var absolutePositionX;
  12407. var absolutePositionY;
  12408. var absolutePositionZ;
  12409. if (absolutePosition.x === undefined) {
  12410. if (arguments.length < 3) {
  12411. return;
  12412. }
  12413. absolutePositionX = arguments[0];
  12414. absolutePositionY = arguments[1];
  12415. absolutePositionZ = arguments[2];
  12416. }
  12417. else {
  12418. absolutePositionX = absolutePosition.x;
  12419. absolutePositionY = absolutePosition.y;
  12420. absolutePositionZ = absolutePosition.z;
  12421. }
  12422. if (this.parent) {
  12423. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12424. invertParentWorldMatrix.invert();
  12425. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12426. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12427. }
  12428. else {
  12429. this.position.x = absolutePositionX;
  12430. this.position.y = absolutePositionY;
  12431. this.position.z = absolutePositionZ;
  12432. }
  12433. return this;
  12434. };
  12435. // ================================== Point of View Movement =================================
  12436. /**
  12437. * Perform relative position change from the point of view of behind the front of the mesh.
  12438. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12439. * Supports definition of mesh facing forward or backward.
  12440. * @param {number} amountRight
  12441. * @param {number} amountUp
  12442. * @param {number} amountForward
  12443. *
  12444. * Returns the AbstractMesh.
  12445. */
  12446. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12447. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12448. return this;
  12449. };
  12450. /**
  12451. * Calculate relative position change from the point of view of behind the front of the mesh.
  12452. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12453. * Supports definition of mesh facing forward or backward.
  12454. * @param {number} amountRight
  12455. * @param {number} amountUp
  12456. * @param {number} amountForward
  12457. *
  12458. * Returns a new Vector3.
  12459. */
  12460. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12461. var rotMatrix = new BABYLON.Matrix();
  12462. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12463. rotQuaternion.toRotationMatrix(rotMatrix);
  12464. var translationDelta = BABYLON.Vector3.Zero();
  12465. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12466. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12467. return translationDelta;
  12468. };
  12469. // ================================== Point of View Rotation =================================
  12470. /**
  12471. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12472. * Supports definition of mesh facing forward or backward.
  12473. * @param {number} flipBack
  12474. * @param {number} twirlClockwise
  12475. * @param {number} tiltRight
  12476. *
  12477. * Returns the AbstractMesh.
  12478. */
  12479. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12480. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12481. return this;
  12482. };
  12483. /**
  12484. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12485. * Supports definition of mesh facing forward or backward.
  12486. * @param {number} flipBack
  12487. * @param {number} twirlClockwise
  12488. * @param {number} tiltRight
  12489. *
  12490. * Returns a new Vector3.
  12491. */
  12492. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12493. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12494. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12495. };
  12496. /**
  12497. * Sets a new pivot matrix to the mesh.
  12498. * Returns the AbstractMesh.
  12499. */
  12500. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12501. this._pivotMatrix = matrix;
  12502. this._cache.pivotMatrixUpdated = true;
  12503. return this;
  12504. };
  12505. /**
  12506. * Returns the mesh pivot matrix.
  12507. * Default : Identity.
  12508. * A Matrix is returned.
  12509. */
  12510. AbstractMesh.prototype.getPivotMatrix = function () {
  12511. return this._pivotMatrix;
  12512. };
  12513. AbstractMesh.prototype._isSynchronized = function () {
  12514. if (this._isDirty) {
  12515. return false;
  12516. }
  12517. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12518. return false;
  12519. if (this._cache.pivotMatrixUpdated) {
  12520. return false;
  12521. }
  12522. if (this.infiniteDistance) {
  12523. return false;
  12524. }
  12525. if (!this._cache.position.equals(this.position))
  12526. return false;
  12527. if (this.rotationQuaternion) {
  12528. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12529. return false;
  12530. }
  12531. if (!this._cache.rotation.equals(this.rotation))
  12532. return false;
  12533. if (!this._cache.scaling.equals(this.scaling))
  12534. return false;
  12535. return true;
  12536. };
  12537. AbstractMesh.prototype._initCache = function () {
  12538. _super.prototype._initCache.call(this);
  12539. this._cache.localMatrixUpdated = false;
  12540. this._cache.position = BABYLON.Vector3.Zero();
  12541. this._cache.scaling = BABYLON.Vector3.Zero();
  12542. this._cache.rotation = BABYLON.Vector3.Zero();
  12543. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12544. this._cache.billboardMode = -1;
  12545. };
  12546. AbstractMesh.prototype.markAsDirty = function (property) {
  12547. if (property === "rotation") {
  12548. this.rotationQuaternion = null;
  12549. }
  12550. this._currentRenderId = Number.MAX_VALUE;
  12551. this._isDirty = true;
  12552. return this;
  12553. };
  12554. /**
  12555. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12556. * Returns the AbstractMesh.
  12557. */
  12558. AbstractMesh.prototype._updateBoundingInfo = function () {
  12559. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12560. this._boundingInfo.update(this.worldMatrixFromCache);
  12561. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12562. return this;
  12563. };
  12564. /**
  12565. * Update a mesh's children BoundingInfo objects only.
  12566. * Returns the AbstractMesh.
  12567. */
  12568. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12569. if (!this.subMeshes) {
  12570. return;
  12571. }
  12572. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12573. var subMesh = this.subMeshes[subIndex];
  12574. if (!subMesh.IsGlobal) {
  12575. subMesh.updateBoundingInfo(matrix);
  12576. }
  12577. }
  12578. return this;
  12579. };
  12580. /**
  12581. * Computes the mesh World matrix and returns it.
  12582. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12583. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12584. * If the parameter `force`is set to `true`, the actual computation is done.
  12585. * Returns the mesh World Matrix.
  12586. */
  12587. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12588. if (this._isWorldMatrixFrozen) {
  12589. return this._worldMatrix;
  12590. }
  12591. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  12592. this._currentRenderId = this.getScene().getRenderId();
  12593. return this._worldMatrix;
  12594. }
  12595. this._cache.position.copyFrom(this.position);
  12596. this._cache.scaling.copyFrom(this.scaling);
  12597. this._cache.pivotMatrixUpdated = false;
  12598. this._cache.billboardMode = this.billboardMode;
  12599. this._currentRenderId = this.getScene().getRenderId();
  12600. this._isDirty = false;
  12601. // Scaling
  12602. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12603. // Rotation
  12604. //rotate, if quaternion is set and rotation was used
  12605. if (this.rotationQuaternion) {
  12606. var len = this.rotation.length();
  12607. if (len) {
  12608. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12609. this.rotation.copyFromFloats(0, 0, 0);
  12610. }
  12611. }
  12612. if (this.rotationQuaternion) {
  12613. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12614. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12615. }
  12616. else {
  12617. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12618. this._cache.rotation.copyFrom(this.rotation);
  12619. }
  12620. // Translation
  12621. if (this.infiniteDistance && !this.parent) {
  12622. var camera = this.getScene().activeCamera;
  12623. if (camera) {
  12624. var cameraWorldMatrix = camera.getWorldMatrix();
  12625. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12626. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12627. }
  12628. }
  12629. else {
  12630. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12631. }
  12632. // Composing transformations
  12633. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12634. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12635. // Billboarding
  12636. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12637. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12638. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12639. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12640. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12641. // Need to extract rotation vectors
  12642. var scale = BABYLON.Tmp.Vector3[2];
  12643. var rotation = BABYLON.Tmp.Quaternion[0];
  12644. var translation = BABYLON.Tmp.Vector3[3];
  12645. BABYLON.Tmp.Matrix[0].decompose(scale, rotation, translation);
  12646. var finalQuaternion = BABYLON.Tmp.Quaternion[1];
  12647. finalQuaternion.copyFrom(rotation);
  12648. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) !== AbstractMesh.BILLBOARDMODE_X) {
  12649. finalQuaternion.x = 0;
  12650. }
  12651. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) !== AbstractMesh.BILLBOARDMODE_Y) {
  12652. finalQuaternion.y = 0;
  12653. }
  12654. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) !== AbstractMesh.BILLBOARDMODE_Z) {
  12655. finalQuaternion.z = 0;
  12656. }
  12657. BABYLON.Matrix.ComposeToRef(scale, finalQuaternion, translation, BABYLON.Tmp.Matrix[0]);
  12658. }
  12659. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12660. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12661. }
  12662. // Local world
  12663. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12664. // Parent
  12665. if (this.parent && this.parent.getWorldMatrix) {
  12666. this._markSyncedWithParent();
  12667. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12668. if (this._meshToBoneReferal) {
  12669. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[5]);
  12670. }
  12671. else {
  12672. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12673. }
  12674. BABYLON.Tmp.Matrix[5].removeRotationAndScaling();
  12675. this._localWorld.multiplyToRef(BABYLON.Tmp.Matrix[5], this._worldMatrix);
  12676. }
  12677. else {
  12678. if (this._meshToBoneReferal) {
  12679. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12680. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12681. }
  12682. else {
  12683. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12684. }
  12685. }
  12686. }
  12687. else {
  12688. this._worldMatrix.copyFrom(this._localWorld);
  12689. }
  12690. // Bounding info
  12691. this._updateBoundingInfo();
  12692. // Absolute position
  12693. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12694. // Callbacks
  12695. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12696. if (!this._poseMatrix) {
  12697. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12698. }
  12699. return this._worldMatrix;
  12700. };
  12701. /**
  12702. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12703. * @param func: callback function to add
  12704. *
  12705. * Returns the AbstractMesh.
  12706. */
  12707. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12708. this.onAfterWorldMatrixUpdateObservable.add(func);
  12709. return this;
  12710. };
  12711. /**
  12712. * Removes a registered callback function.
  12713. * Returns the AbstractMesh.
  12714. */
  12715. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12716. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12717. return this;
  12718. };
  12719. /**
  12720. * Sets the mesh position in its local space.
  12721. * Returns the AbstractMesh.
  12722. */
  12723. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12724. this.computeWorldMatrix();
  12725. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12726. return this;
  12727. };
  12728. /**
  12729. * Returns the mesh position in the local space from the current World matrix values.
  12730. * Returns a new Vector3.
  12731. */
  12732. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12733. this.computeWorldMatrix();
  12734. var invLocalWorldMatrix = this._localWorld.clone();
  12735. invLocalWorldMatrix.invert();
  12736. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12737. };
  12738. /**
  12739. * Translates the mesh along the passed Vector3 in its local space.
  12740. * Returns the AbstractMesh.
  12741. */
  12742. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12743. this.computeWorldMatrix(true);
  12744. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12745. return this;
  12746. };
  12747. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12748. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12749. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12750. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12751. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12752. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12753. /// <returns>Mesh oriented towards targetMesh</returns>
  12754. if (yawCor === void 0) { yawCor = 0; }
  12755. if (pitchCor === void 0) { pitchCor = 0; }
  12756. if (rollCor === void 0) { rollCor = 0; }
  12757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12758. var dv = AbstractMesh._lookAtVectorCache;
  12759. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12760. targetPoint.subtractToRef(pos, dv);
  12761. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12762. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12763. var pitch = Math.atan2(dv.y, len);
  12764. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12765. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12766. return this;
  12767. };
  12768. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12769. this._meshToBoneReferal = affectedMesh;
  12770. this.parent = bone;
  12771. if (bone.getWorldMatrix().determinant() < 0) {
  12772. this.scalingDeterminant *= -1;
  12773. }
  12774. return this;
  12775. };
  12776. AbstractMesh.prototype.detachFromBone = function () {
  12777. if (this.parent.getWorldMatrix().determinant() < 0) {
  12778. this.scalingDeterminant *= -1;
  12779. }
  12780. this._meshToBoneReferal = null;
  12781. this.parent = null;
  12782. return this;
  12783. };
  12784. /**
  12785. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12786. * A mesh is in the frustum if its bounding box intersects the frustum.
  12787. * Boolean returned.
  12788. */
  12789. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12790. return this._boundingInfo.isInFrustum(frustumPlanes);
  12791. };
  12792. /**
  12793. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12794. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12795. * Boolean returned.
  12796. */
  12797. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12798. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12799. ;
  12800. };
  12801. /**
  12802. * True if the mesh intersects another mesh or a SolidParticle object.
  12803. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  12804. * Returns a boolean.
  12805. */
  12806. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12807. if (!this._boundingInfo || !mesh._boundingInfo) {
  12808. return false;
  12809. }
  12810. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12811. };
  12812. /**
  12813. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12814. * Returns a boolean.
  12815. */
  12816. AbstractMesh.prototype.intersectsPoint = function (point) {
  12817. if (!this._boundingInfo) {
  12818. return false;
  12819. }
  12820. return this._boundingInfo.intersectsPoint(point);
  12821. };
  12822. // Physics
  12823. /**
  12824. * @Deprecated. Use new PhysicsImpostor instead.
  12825. * */
  12826. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  12827. //legacy support
  12828. if (impostor.impostor) {
  12829. options = impostor;
  12830. impostor = impostor.impostor;
  12831. }
  12832. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  12833. return this.physicsImpostor.physicsBody;
  12834. };
  12835. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12836. return this.physicsImpostor;
  12837. };
  12838. /**
  12839. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  12840. */
  12841. AbstractMesh.prototype.getPhysicsMass = function () {
  12842. return this.physicsImpostor.getParam("mass");
  12843. };
  12844. /**
  12845. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  12846. */
  12847. AbstractMesh.prototype.getPhysicsFriction = function () {
  12848. return this.physicsImpostor.getParam("friction");
  12849. };
  12850. /**
  12851. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  12852. */
  12853. AbstractMesh.prototype.getPhysicsRestitution = function () {
  12854. return this.physicsImpostor.getParam("restitution");
  12855. };
  12856. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12857. if (!camera) {
  12858. camera = this.getScene().activeCamera;
  12859. }
  12860. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12861. };
  12862. /**
  12863. * Returns the distance from the mesh to the active camera.
  12864. * Returns a float.
  12865. */
  12866. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12867. if (!camera) {
  12868. camera = this.getScene().activeCamera;
  12869. }
  12870. return this.absolutePosition.subtract(camera.position).length();
  12871. };
  12872. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12873. if (!this.physicsImpostor) {
  12874. return;
  12875. }
  12876. this.physicsImpostor.applyImpulse(force, contactPoint);
  12877. return this;
  12878. };
  12879. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12880. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12881. return;
  12882. }
  12883. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12884. mainPivot: pivot1,
  12885. connectedPivot: pivot2,
  12886. nativeParams: options
  12887. });
  12888. return this;
  12889. };
  12890. /**
  12891. * @Deprecated
  12892. */
  12893. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  12894. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  12895. this.updatePhysicsBody();
  12896. };
  12897. /**
  12898. * @Deprecated
  12899. * Calling this function is not needed anymore.
  12900. * The physics engine takes care of transofmration automatically.
  12901. */
  12902. AbstractMesh.prototype.updatePhysicsBody = function () {
  12903. //Unneeded
  12904. };
  12905. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12906. // Collisions
  12907. /**
  12908. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12909. * Default `false`.
  12910. */
  12911. get: function () {
  12912. return this._checkCollisions;
  12913. },
  12914. set: function (collisionEnabled) {
  12915. this._checkCollisions = collisionEnabled;
  12916. if (this.getScene().workerCollisions) {
  12917. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12918. }
  12919. },
  12920. enumerable: true,
  12921. configurable: true
  12922. });
  12923. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12924. var globalPosition = this.getAbsolutePosition();
  12925. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12926. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12927. this._collider.radius = this.ellipsoid;
  12928. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12929. return this;
  12930. };
  12931. // Submeshes octree
  12932. /**
  12933. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12934. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12935. * Returns an Octree of submeshes.
  12936. */
  12937. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12938. if (maxCapacity === void 0) { maxCapacity = 64; }
  12939. if (maxDepth === void 0) { maxDepth = 2; }
  12940. if (!this._submeshesOctree) {
  12941. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12942. }
  12943. this.computeWorldMatrix(true);
  12944. // Update octree
  12945. var bbox = this.getBoundingInfo().boundingBox;
  12946. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12947. return this._submeshesOctree;
  12948. };
  12949. // Collisions
  12950. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12951. this._generatePointsArray();
  12952. // Transformation
  12953. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12954. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12955. subMesh._lastColliderWorldVertices = [];
  12956. subMesh._trianglePlanes = [];
  12957. var start = subMesh.verticesStart;
  12958. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12959. for (var i = start; i < end; i++) {
  12960. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12961. }
  12962. }
  12963. // Collide
  12964. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12965. if (collider.collisionFound) {
  12966. collider.collidedMesh = this;
  12967. }
  12968. return this;
  12969. };
  12970. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12971. var subMeshes;
  12972. var len;
  12973. // Octrees
  12974. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12975. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12976. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12977. len = intersections.length;
  12978. subMeshes = intersections.data;
  12979. }
  12980. else {
  12981. subMeshes = this.subMeshes;
  12982. len = subMeshes.length;
  12983. }
  12984. for (var index = 0; index < len; index++) {
  12985. var subMesh = subMeshes[index];
  12986. // Bounding test
  12987. if (len > 1 && !subMesh._checkCollision(collider))
  12988. continue;
  12989. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12990. }
  12991. return this;
  12992. };
  12993. AbstractMesh.prototype._checkCollision = function (collider) {
  12994. // Bounding box test
  12995. if (!this._boundingInfo._checkCollision(collider))
  12996. return this;
  12997. // Transformation matrix
  12998. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12999. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13000. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13001. return this;
  13002. };
  13003. // Picking
  13004. AbstractMesh.prototype._generatePointsArray = function () {
  13005. return false;
  13006. };
  13007. /**
  13008. * Checks if the passed Ray intersects with the mesh.
  13009. * Returns an object PickingInfo.
  13010. */
  13011. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13012. var pickingInfo = new BABYLON.PickingInfo();
  13013. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13014. return pickingInfo;
  13015. }
  13016. if (!this._generatePointsArray()) {
  13017. return pickingInfo;
  13018. }
  13019. var intersectInfo = null;
  13020. // Octrees
  13021. var subMeshes;
  13022. var len;
  13023. if (this._submeshesOctree && this.useOctreeForPicking) {
  13024. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13025. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13026. len = intersections.length;
  13027. subMeshes = intersections.data;
  13028. }
  13029. else {
  13030. subMeshes = this.subMeshes;
  13031. len = subMeshes.length;
  13032. }
  13033. for (var index = 0; index < len; index++) {
  13034. var subMesh = subMeshes[index];
  13035. // Bounding test
  13036. if (len > 1 && !subMesh.canIntersects(ray))
  13037. continue;
  13038. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13039. if (currentIntersectInfo) {
  13040. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13041. intersectInfo = currentIntersectInfo;
  13042. intersectInfo.subMeshId = index;
  13043. if (fastCheck) {
  13044. break;
  13045. }
  13046. }
  13047. }
  13048. }
  13049. if (intersectInfo) {
  13050. // Get picked point
  13051. var world = this.getWorldMatrix();
  13052. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13053. var direction = ray.direction.clone();
  13054. direction = direction.scale(intersectInfo.distance);
  13055. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13056. var pickedPoint = worldOrigin.add(worldDirection);
  13057. // Return result
  13058. pickingInfo.hit = true;
  13059. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13060. pickingInfo.pickedPoint = pickedPoint;
  13061. pickingInfo.pickedMesh = this;
  13062. pickingInfo.bu = intersectInfo.bu;
  13063. pickingInfo.bv = intersectInfo.bv;
  13064. pickingInfo.faceId = intersectInfo.faceId;
  13065. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13066. return pickingInfo;
  13067. }
  13068. return pickingInfo;
  13069. };
  13070. /**
  13071. * Clones the mesh, used by the class Mesh.
  13072. * Just returns `null` for an AbstractMesh.
  13073. */
  13074. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13075. return null;
  13076. };
  13077. /**
  13078. * Disposes all the mesh submeshes.
  13079. * Returns the AbstractMesh.
  13080. */
  13081. AbstractMesh.prototype.releaseSubMeshes = function () {
  13082. if (this.subMeshes) {
  13083. while (this.subMeshes.length) {
  13084. this.subMeshes[0].dispose();
  13085. }
  13086. }
  13087. else {
  13088. this.subMeshes = new Array();
  13089. }
  13090. return this;
  13091. };
  13092. /**
  13093. * Disposes the AbstractMesh.
  13094. * Some internal references are kept for further use.
  13095. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13096. * Returns nothing.
  13097. */
  13098. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13099. var _this = this;
  13100. var index;
  13101. // Action manager
  13102. if (this.actionManager) {
  13103. this.actionManager.dispose();
  13104. this.actionManager = null;
  13105. }
  13106. // Skeleton
  13107. this.skeleton = null;
  13108. // Animations
  13109. this.getScene().stopAnimation(this);
  13110. // Physics
  13111. if (this.physicsImpostor) {
  13112. this.physicsImpostor.dispose();
  13113. }
  13114. // Intersections in progress
  13115. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13116. var other = this._intersectionsInProgress[index];
  13117. var pos = other._intersectionsInProgress.indexOf(this);
  13118. other._intersectionsInProgress.splice(pos, 1);
  13119. }
  13120. this._intersectionsInProgress = [];
  13121. // Lights
  13122. var lights = this.getScene().lights;
  13123. lights.forEach(function (light) {
  13124. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13125. if (meshIndex !== -1) {
  13126. light.includedOnlyMeshes.splice(meshIndex, 1);
  13127. }
  13128. meshIndex = light.excludedMeshes.indexOf(_this);
  13129. if (meshIndex !== -1) {
  13130. light.excludedMeshes.splice(meshIndex, 1);
  13131. }
  13132. // Shadow generators
  13133. var generator = light.getShadowGenerator();
  13134. if (generator) {
  13135. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13136. if (meshIndex !== -1) {
  13137. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13138. }
  13139. }
  13140. });
  13141. // Edges
  13142. if (this._edgesRenderer) {
  13143. this._edgesRenderer.dispose();
  13144. this._edgesRenderer = null;
  13145. }
  13146. // SubMeshes
  13147. if (this.getClassName() !== "InstancedMesh") {
  13148. this.releaseSubMeshes();
  13149. }
  13150. // Engine
  13151. this.getScene().getEngine().wipeCaches();
  13152. // Remove from scene
  13153. this.getScene().removeMesh(this);
  13154. if (!doNotRecurse) {
  13155. // Particles
  13156. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13157. if (this.getScene().particleSystems[index].emitter === this) {
  13158. this.getScene().particleSystems[index].dispose();
  13159. index--;
  13160. }
  13161. }
  13162. // Children
  13163. var objects = this.getDescendants(true);
  13164. for (index = 0; index < objects.length; index++) {
  13165. objects[index].dispose();
  13166. }
  13167. }
  13168. else {
  13169. var childMeshes = this.getChildMeshes(true);
  13170. for (index = 0; index < childMeshes.length; index++) {
  13171. var child = childMeshes[index];
  13172. child.parent = null;
  13173. child.computeWorldMatrix(true);
  13174. }
  13175. }
  13176. // facet data
  13177. if (this._facetDataEnabled) {
  13178. this.disableFacetData();
  13179. }
  13180. this.onAfterWorldMatrixUpdateObservable.clear();
  13181. this.onCollideObservable.clear();
  13182. this.onCollisionPositionChangeObservable.clear();
  13183. this._isDisposed = true;
  13184. _super.prototype.dispose.call(this);
  13185. };
  13186. /**
  13187. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13188. * This Vector3 is expressed in the World space.
  13189. */
  13190. AbstractMesh.prototype.getDirection = function (localAxis) {
  13191. var result = BABYLON.Vector3.Zero();
  13192. this.getDirectionToRef(localAxis, result);
  13193. return result;
  13194. };
  13195. /**
  13196. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13197. * localAxis is expressed in the mesh local space.
  13198. * result is computed in the Wordl space from the mesh World matrix.
  13199. * Returns the AbstractMesh.
  13200. */
  13201. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13202. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13203. return this;
  13204. };
  13205. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13207. if (this.getScene().getRenderId() == 0) {
  13208. this.computeWorldMatrix(true);
  13209. }
  13210. var wm = this.getWorldMatrix();
  13211. if (space == BABYLON.Space.WORLD) {
  13212. var tmat = BABYLON.Tmp.Matrix[0];
  13213. wm.invertToRef(tmat);
  13214. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13215. }
  13216. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13217. this._pivotMatrix.m[12] = -point.x;
  13218. this._pivotMatrix.m[13] = -point.y;
  13219. this._pivotMatrix.m[14] = -point.z;
  13220. this._cache.pivotMatrixUpdated = true;
  13221. return this;
  13222. };
  13223. /**
  13224. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13225. */
  13226. AbstractMesh.prototype.getPivotPoint = function () {
  13227. var point = BABYLON.Vector3.Zero();
  13228. this.getPivotPointToRef(point);
  13229. return point;
  13230. };
  13231. /**
  13232. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13233. * Returns the AbstractMesh.
  13234. */
  13235. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13236. result.x = -this._pivotMatrix.m[12];
  13237. result.y = -this._pivotMatrix.m[13];
  13238. result.z = -this._pivotMatrix.m[14];
  13239. return this;
  13240. };
  13241. /**
  13242. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13243. */
  13244. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13245. var point = BABYLON.Vector3.Zero();
  13246. this.getAbsolutePivotPointToRef(point);
  13247. return point;
  13248. };
  13249. /**
  13250. * Defines the passed mesh as the parent of the current mesh.
  13251. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13252. * Returns the AbstractMesh.
  13253. */
  13254. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13255. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13256. var child = this;
  13257. var parent = mesh;
  13258. if (mesh == null) {
  13259. if (child.parent && keepWorldPositionRotation) {
  13260. var rotation = BABYLON.Tmp.Quaternion[0];
  13261. var position = BABYLON.Tmp.Vector3[0];
  13262. var scale = BABYLON.Tmp.Vector3[1];
  13263. child.getWorldMatrix().decompose(scale, rotation, position);
  13264. if (child.rotationQuaternion) {
  13265. child.rotationQuaternion.copyFrom(rotation);
  13266. }
  13267. else {
  13268. rotation.toEulerAnglesToRef(child.rotation);
  13269. }
  13270. child.position.x = position.x;
  13271. child.position.y = position.y;
  13272. child.position.z = position.z;
  13273. }
  13274. }
  13275. else {
  13276. if (keepWorldPositionRotation) {
  13277. var rotation = BABYLON.Tmp.Quaternion[0];
  13278. var position = BABYLON.Tmp.Vector3[0];
  13279. var scale = BABYLON.Tmp.Vector3[1];
  13280. var m1 = BABYLON.Tmp.Matrix[0];
  13281. var m2 = BABYLON.Tmp.Matrix[1];
  13282. parent.getWorldMatrix().decompose(scale, rotation, position);
  13283. rotation.toRotationMatrix(m1);
  13284. m2.setTranslation(position);
  13285. m2.multiplyToRef(m1, m1);
  13286. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13287. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13288. m.decompose(scale, rotation, position);
  13289. if (child.rotationQuaternion) {
  13290. child.rotationQuaternion.copyFrom(rotation);
  13291. }
  13292. else {
  13293. rotation.toEulerAnglesToRef(child.rotation);
  13294. }
  13295. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13296. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13297. m.decompose(scale, rotation, position);
  13298. child.position.x = position.x;
  13299. child.position.y = position.y;
  13300. child.position.z = position.z;
  13301. }
  13302. }
  13303. child.parent = parent;
  13304. return this;
  13305. };
  13306. /**
  13307. * Adds the passed mesh as a child to the current mesh.
  13308. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13309. * Returns the AbstractMesh.
  13310. */
  13311. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13312. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13313. mesh.setParent(this, keepWorldPositionRotation);
  13314. return this;
  13315. };
  13316. /**
  13317. * Removes the passed mesh from the current mesh children list.
  13318. * Returns the AbstractMesh.
  13319. */
  13320. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13321. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13322. mesh.setParent(null, keepWorldPositionRotation);
  13323. return this;
  13324. };
  13325. /**
  13326. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13327. * Returns the AbstractMesh.
  13328. */
  13329. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13330. result.x = this._pivotMatrix.m[12];
  13331. result.y = this._pivotMatrix.m[13];
  13332. result.z = this._pivotMatrix.m[14];
  13333. this.getPivotPointToRef(result);
  13334. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13335. return this;
  13336. };
  13337. // Facet data
  13338. /**
  13339. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13340. * Returns the AbstractMesh.
  13341. */
  13342. AbstractMesh.prototype._initFacetData = function () {
  13343. if (!this._facetNormals) {
  13344. this._facetNormals = new Array();
  13345. }
  13346. if (!this._facetPositions) {
  13347. this._facetPositions = new Array();
  13348. }
  13349. if (!this._facetPartitioning) {
  13350. this._facetPartitioning = new Array();
  13351. }
  13352. this._facetNb = this.getIndices().length / 3;
  13353. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13354. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13355. for (var f = 0; f < this._facetNb; f++) {
  13356. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13357. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13358. }
  13359. this._facetDataEnabled = true;
  13360. return this;
  13361. };
  13362. /**
  13363. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13364. * This method can be called within the render loop.
  13365. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  13366. * Returns the AbstractMesh.
  13367. */
  13368. AbstractMesh.prototype.updateFacetData = function () {
  13369. if (!this._facetDataEnabled) {
  13370. this._initFacetData();
  13371. }
  13372. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13373. var indices = this.getIndices();
  13374. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13375. var bInfo = this.getBoundingInfo();
  13376. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13377. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13378. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13379. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13380. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13381. this._subDiv.max = this._partitioningSubdivisions;
  13382. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13383. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13384. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13385. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13386. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13387. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13388. // set the parameters for ComputeNormals()
  13389. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13390. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13391. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13392. this._facetParameters.bInfo = bInfo;
  13393. this._facetParameters.bbSize = this._bbSize;
  13394. this._facetParameters.subDiv = this._subDiv;
  13395. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13396. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13397. return this;
  13398. };
  13399. /**
  13400. * Returns the facetLocalNormals array.
  13401. * The normals are expressed in the mesh local space.
  13402. */
  13403. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13404. if (!this._facetNormals) {
  13405. this.updateFacetData();
  13406. }
  13407. return this._facetNormals;
  13408. };
  13409. /**
  13410. * Returns the facetLocalPositions array.
  13411. * The facet positions are expressed in the mesh local space.
  13412. */
  13413. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13414. if (!this._facetPositions) {
  13415. this.updateFacetData();
  13416. }
  13417. return this._facetPositions;
  13418. };
  13419. /**
  13420. * Returns the facetLocalPartioning array.
  13421. */
  13422. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13423. if (!this._facetPartitioning) {
  13424. this.updateFacetData();
  13425. }
  13426. return this._facetPartitioning;
  13427. };
  13428. /**
  13429. * Returns the i-th facet position in the world system.
  13430. * This method allocates a new Vector3 per call.
  13431. */
  13432. AbstractMesh.prototype.getFacetPosition = function (i) {
  13433. var pos = BABYLON.Vector3.Zero();
  13434. this.getFacetPositionToRef(i, pos);
  13435. return pos;
  13436. };
  13437. /**
  13438. * Sets the reference Vector3 with the i-th facet position in the world system.
  13439. * Returns the AbstractMesh.
  13440. */
  13441. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13442. var localPos = (this.getFacetLocalPositions())[i];
  13443. var world = this.getWorldMatrix();
  13444. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13445. return this;
  13446. };
  13447. /**
  13448. * Returns the i-th facet normal in the world system.
  13449. * This method allocates a new Vector3 per call.
  13450. */
  13451. AbstractMesh.prototype.getFacetNormal = function (i) {
  13452. var norm = BABYLON.Vector3.Zero();
  13453. this.getFacetNormalToRef(i, norm);
  13454. return norm;
  13455. };
  13456. /**
  13457. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13458. * Returns the AbstractMesh.
  13459. */
  13460. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13461. var localNorm = (this.getFacetLocalNormals())[i];
  13462. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13463. return this;
  13464. };
  13465. /**
  13466. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  13467. */
  13468. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13469. var bInfo = this.getBoundingInfo();
  13470. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13471. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13472. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13473. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13474. return null;
  13475. }
  13476. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13477. };
  13478. /**
  13479. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13480. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13481. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13482. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13483. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13484. */
  13485. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13486. if (checkFace === void 0) { checkFace = false; }
  13487. if (facing === void 0) { facing = true; }
  13488. var world = this.getWorldMatrix();
  13489. var invMat = BABYLON.Tmp.Matrix[5];
  13490. world.invertToRef(invMat);
  13491. var invVect = BABYLON.Tmp.Vector3[8];
  13492. var closest = null;
  13493. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13494. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13495. if (projected) {
  13496. // tranform the local computed projected vector to world coordinates
  13497. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13498. }
  13499. return closest;
  13500. };
  13501. /**
  13502. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13503. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13504. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13505. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13506. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13507. */
  13508. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13509. if (checkFace === void 0) { checkFace = false; }
  13510. if (facing === void 0) { facing = true; }
  13511. var closest = null;
  13512. var tmpx = 0.0;
  13513. var tmpy = 0.0;
  13514. var tmpz = 0.0;
  13515. var d = 0.0; // tmp dot facet normal * facet position
  13516. var t0 = 0.0;
  13517. var projx = 0.0;
  13518. var projy = 0.0;
  13519. var projz = 0.0;
  13520. // Get all the facets in the same partitioning block than (x, y, z)
  13521. var facetPositions = this.getFacetLocalPositions();
  13522. var facetNormals = this.getFacetLocalNormals();
  13523. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13524. if (!facetsInBlock) {
  13525. return null;
  13526. }
  13527. // Get the closest facet to (x, y, z)
  13528. var shortest = Number.MAX_VALUE; // init distance vars
  13529. var tmpDistance = shortest;
  13530. var fib; // current facet in the block
  13531. var norm; // current facet normal
  13532. var p0; // current facet barycenter position
  13533. // loop on all the facets in the current partitioning block
  13534. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13535. fib = facetsInBlock[idx];
  13536. norm = facetNormals[fib];
  13537. p0 = facetPositions[fib];
  13538. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13539. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13540. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13541. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13542. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13543. projx = x + norm.x * t0;
  13544. projy = y + norm.y * t0;
  13545. projz = z + norm.z * t0;
  13546. tmpx = projx - x;
  13547. tmpy = projy - y;
  13548. tmpz = projz - z;
  13549. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13550. if (tmpDistance < shortest) {
  13551. shortest = tmpDistance;
  13552. closest = fib;
  13553. if (projected) {
  13554. projected.x = projx;
  13555. projected.y = projy;
  13556. projected.z = projz;
  13557. }
  13558. }
  13559. }
  13560. }
  13561. return closest;
  13562. };
  13563. /**
  13564. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13565. */
  13566. AbstractMesh.prototype.getFacetDataParameters = function () {
  13567. return this._facetParameters;
  13568. };
  13569. /**
  13570. * Disables the feature FacetData and frees the related memory.
  13571. * Returns the AbstractMesh.
  13572. */
  13573. AbstractMesh.prototype.disableFacetData = function () {
  13574. if (this._facetDataEnabled) {
  13575. this._facetDataEnabled = false;
  13576. this._facetPositions = null;
  13577. this._facetNormals = null;
  13578. this._facetPartitioning = null;
  13579. this._facetParameters = null;
  13580. }
  13581. return this;
  13582. };
  13583. return AbstractMesh;
  13584. }(BABYLON.Node));
  13585. // Statics
  13586. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13587. AbstractMesh._BILLBOARDMODE_X = 1;
  13588. AbstractMesh._BILLBOARDMODE_Y = 2;
  13589. AbstractMesh._BILLBOARDMODE_Z = 4;
  13590. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13591. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13592. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13593. BABYLON.AbstractMesh = AbstractMesh;
  13594. })(BABYLON || (BABYLON = {}));
  13595. //# sourceMappingURL=babylon.abstractMesh.js.map
  13596. var BABYLON;
  13597. (function (BABYLON) {
  13598. var Light = (function (_super) {
  13599. __extends(Light, _super);
  13600. /**
  13601. * Creates a Light object in the scene.
  13602. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13603. */
  13604. function Light(name, scene) {
  13605. var _this = _super.call(this, name, scene) || this;
  13606. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13607. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13608. _this.intensity = 1.0;
  13609. _this.range = Number.MAX_VALUE;
  13610. _this.includeOnlyWithLayerMask = 0;
  13611. _this.includedOnlyMeshes = new Array();
  13612. _this.excludedMeshes = new Array();
  13613. _this.excludeWithLayerMask = 0;
  13614. _this.lightmapMode = 0;
  13615. // PBR Properties.
  13616. _this.radius = 0.00001;
  13617. _this._excludedMeshesIds = new Array();
  13618. _this._includedOnlyMeshesIds = new Array();
  13619. scene.addLight(_this);
  13620. return _this;
  13621. }
  13622. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13623. /**
  13624. * If every light affecting the material is in this lightmapMode,
  13625. * material.lightmapTexture adds or multiplies
  13626. * (depends on material.useLightmapAsShadowmap)
  13627. * after every other light calculations.
  13628. */
  13629. get: function () {
  13630. return Light._LIGHTMAP_DEFAULT;
  13631. },
  13632. enumerable: true,
  13633. configurable: true
  13634. });
  13635. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13636. /**
  13637. * material.lightmapTexture as only diffuse lighting from this light
  13638. * adds pnly specular lighting from this light
  13639. * adds dynamic shadows
  13640. */
  13641. get: function () {
  13642. return Light._LIGHTMAP_SPECULAR;
  13643. },
  13644. enumerable: true,
  13645. configurable: true
  13646. });
  13647. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13648. /**
  13649. * material.lightmapTexture as only lighting
  13650. * no light calculation from this light
  13651. * only adds dynamic shadows from this light
  13652. */
  13653. get: function () {
  13654. return Light._LIGHTMAP_SHADOWSONLY;
  13655. },
  13656. enumerable: true,
  13657. configurable: true
  13658. });
  13659. /**
  13660. * Returns the string "Light".
  13661. */
  13662. Light.prototype.getClassName = function () {
  13663. return "Light";
  13664. };
  13665. /**
  13666. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13667. */
  13668. Light.prototype.toString = function (fullDetails) {
  13669. var ret = "Name: " + this.name;
  13670. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13671. if (this.animations) {
  13672. for (var i = 0; i < this.animations.length; i++) {
  13673. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13674. }
  13675. }
  13676. if (fullDetails) {
  13677. }
  13678. return ret;
  13679. };
  13680. /**
  13681. * Returns the Light associated shadow generator.
  13682. */
  13683. Light.prototype.getShadowGenerator = function () {
  13684. return this._shadowGenerator;
  13685. };
  13686. /**
  13687. * Returns a Vector3, the absolute light position in the World.
  13688. */
  13689. Light.prototype.getAbsolutePosition = function () {
  13690. return BABYLON.Vector3.Zero();
  13691. };
  13692. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13693. };
  13694. Light.prototype._getWorldMatrix = function () {
  13695. return BABYLON.Matrix.Identity();
  13696. };
  13697. /**
  13698. * Boolean : True if the light will affect the passed mesh.
  13699. */
  13700. Light.prototype.canAffectMesh = function (mesh) {
  13701. if (!mesh) {
  13702. return true;
  13703. }
  13704. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13705. return false;
  13706. }
  13707. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13708. return false;
  13709. }
  13710. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13711. return false;
  13712. }
  13713. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13714. return false;
  13715. }
  13716. return true;
  13717. };
  13718. /**
  13719. * Returns the light World matrix.
  13720. */
  13721. Light.prototype.getWorldMatrix = function () {
  13722. this._currentRenderId = this.getScene().getRenderId();
  13723. var worldMatrix = this._getWorldMatrix();
  13724. if (this.parent && this.parent.getWorldMatrix) {
  13725. if (!this._parentedWorldMatrix) {
  13726. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13727. }
  13728. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13729. this._markSyncedWithParent();
  13730. return this._parentedWorldMatrix;
  13731. }
  13732. return worldMatrix;
  13733. };
  13734. /**
  13735. * Disposes the light.
  13736. */
  13737. Light.prototype.dispose = function () {
  13738. if (this._shadowGenerator) {
  13739. this._shadowGenerator.dispose();
  13740. this._shadowGenerator = null;
  13741. }
  13742. // Animations
  13743. this.getScene().stopAnimation(this);
  13744. // Remove from scene
  13745. this.getScene().removeLight(this);
  13746. _super.prototype.dispose.call(this);
  13747. };
  13748. /**
  13749. * Returns the light type ID (integer).
  13750. */
  13751. Light.prototype.getTypeID = function () {
  13752. return 0;
  13753. };
  13754. /**
  13755. * Returns a new Light object, named "name", from the current one.
  13756. */
  13757. Light.prototype.clone = function (name) {
  13758. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13759. };
  13760. /**
  13761. * Serializes the current light into a Serialization object.
  13762. * Returns the serialized object.
  13763. */
  13764. Light.prototype.serialize = function () {
  13765. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13766. // Type
  13767. serializationObject.type = this.getTypeID();
  13768. // Parent
  13769. if (this.parent) {
  13770. serializationObject.parentId = this.parent.id;
  13771. }
  13772. // Inclusion / exclusions
  13773. if (this.excludedMeshes.length > 0) {
  13774. serializationObject.excludedMeshesIds = [];
  13775. this.excludedMeshes.forEach(function (mesh) {
  13776. serializationObject.excludedMeshesIds.push(mesh.id);
  13777. });
  13778. }
  13779. if (this.includedOnlyMeshes.length > 0) {
  13780. serializationObject.includedOnlyMeshesIds = [];
  13781. this.includedOnlyMeshes.forEach(function (mesh) {
  13782. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13783. });
  13784. }
  13785. // Animations
  13786. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13787. serializationObject.ranges = this.serializeAnimationRanges();
  13788. return serializationObject;
  13789. };
  13790. /**
  13791. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13792. * This new light is named "name" and added to the passed scene.
  13793. */
  13794. Light.GetConstructorFromName = function (type, name, scene) {
  13795. switch (type) {
  13796. case 0:
  13797. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13798. case 1:
  13799. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13800. case 2:
  13801. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13802. case 3:
  13803. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13804. }
  13805. };
  13806. /**
  13807. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13808. */
  13809. Light.Parse = function (parsedLight, scene) {
  13810. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13811. // Inclusion / exclusions
  13812. if (parsedLight.excludedMeshesIds) {
  13813. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13814. }
  13815. if (parsedLight.includedOnlyMeshesIds) {
  13816. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13817. }
  13818. // Parent
  13819. if (parsedLight.parentId) {
  13820. light._waitingParentId = parsedLight.parentId;
  13821. }
  13822. // Animations
  13823. if (parsedLight.animations) {
  13824. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13825. var parsedAnimation = parsedLight.animations[animationIndex];
  13826. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13827. }
  13828. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13829. }
  13830. if (parsedLight.autoAnimate) {
  13831. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13832. }
  13833. return light;
  13834. };
  13835. return Light;
  13836. }(BABYLON.Node));
  13837. //lightmapMode Consts
  13838. Light._LIGHTMAP_DEFAULT = 0;
  13839. Light._LIGHTMAP_SPECULAR = 1;
  13840. Light._LIGHTMAP_SHADOWSONLY = 2;
  13841. __decorate([
  13842. BABYLON.serializeAsColor3()
  13843. ], Light.prototype, "diffuse", void 0);
  13844. __decorate([
  13845. BABYLON.serializeAsColor3()
  13846. ], Light.prototype, "specular", void 0);
  13847. __decorate([
  13848. BABYLON.serialize()
  13849. ], Light.prototype, "intensity", void 0);
  13850. __decorate([
  13851. BABYLON.serialize()
  13852. ], Light.prototype, "range", void 0);
  13853. __decorate([
  13854. BABYLON.serialize()
  13855. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  13856. __decorate([
  13857. BABYLON.serialize()
  13858. ], Light.prototype, "excludeWithLayerMask", void 0);
  13859. __decorate([
  13860. BABYLON.serialize()
  13861. ], Light.prototype, "lightmapMode", void 0);
  13862. __decorate([
  13863. BABYLON.serialize()
  13864. ], Light.prototype, "radius", void 0);
  13865. BABYLON.Light = Light;
  13866. })(BABYLON || (BABYLON = {}));
  13867. //# sourceMappingURL=babylon.light.js.map
  13868. var BABYLON;
  13869. (function (BABYLON) {
  13870. var PointLight = (function (_super) {
  13871. __extends(PointLight, _super);
  13872. /**
  13873. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  13874. * A PointLight emits the light in every direction.
  13875. * It can cast shadows.
  13876. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  13877. * ```javascript
  13878. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  13879. * ```
  13880. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13881. */
  13882. function PointLight(name, position, scene) {
  13883. var _this = _super.call(this, name, scene) || this;
  13884. _this.position = position;
  13885. return _this;
  13886. }
  13887. /**
  13888. * Returns the string "PointLight"
  13889. */
  13890. PointLight.prototype.getClassName = function () {
  13891. return "PointLight";
  13892. };
  13893. /**
  13894. * Returns a Vector3, the PointLight absolute position in the World.
  13895. */
  13896. PointLight.prototype.getAbsolutePosition = function () {
  13897. return this.transformedPosition ? this.transformedPosition : this.position;
  13898. };
  13899. /**
  13900. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  13901. */
  13902. PointLight.prototype.computeTransformedPosition = function () {
  13903. if (this.parent && this.parent.getWorldMatrix) {
  13904. if (!this.transformedPosition) {
  13905. this.transformedPosition = BABYLON.Vector3.Zero();
  13906. }
  13907. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  13908. return true;
  13909. }
  13910. return false;
  13911. };
  13912. /**
  13913. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  13914. * Returns the PointLight.
  13915. */
  13916. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  13917. if (this.parent && this.parent.getWorldMatrix) {
  13918. this.computeTransformedPosition();
  13919. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  13920. return this;
  13921. }
  13922. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  13923. return this;
  13924. };
  13925. /**
  13926. * Boolean : returns true by default.
  13927. */
  13928. PointLight.prototype.needCube = function () {
  13929. return true;
  13930. };
  13931. /**
  13932. * Boolean : returns false by default.
  13933. */
  13934. PointLight.prototype.supportsVSM = function () {
  13935. return false;
  13936. };
  13937. /**
  13938. * Boolean : returns false by default.
  13939. */
  13940. PointLight.prototype.needRefreshPerFrame = function () {
  13941. return false;
  13942. };
  13943. /**
  13944. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  13945. */
  13946. PointLight.prototype.getShadowDirection = function (faceIndex) {
  13947. switch (faceIndex) {
  13948. case 0:
  13949. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  13950. case 1:
  13951. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  13952. case 2:
  13953. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  13954. case 3:
  13955. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  13956. case 4:
  13957. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  13958. case 5:
  13959. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  13960. }
  13961. return BABYLON.Vector3.Zero();
  13962. };
  13963. /**
  13964. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  13965. * - fov = PI / 2
  13966. * - aspect ratio : 1.0
  13967. * - z-near and far equal to the active camera minZ and maxZ.
  13968. * Returns the PointLight.
  13969. */
  13970. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  13971. var activeCamera = this.getScene().activeCamera;
  13972. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  13973. return this;
  13974. };
  13975. PointLight.prototype._getWorldMatrix = function () {
  13976. if (!this._worldMatrix) {
  13977. this._worldMatrix = BABYLON.Matrix.Identity();
  13978. }
  13979. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  13980. return this._worldMatrix;
  13981. };
  13982. /**
  13983. * Returns the integer 0.
  13984. */
  13985. PointLight.prototype.getTypeID = function () {
  13986. return 0;
  13987. };
  13988. return PointLight;
  13989. }(BABYLON.Light));
  13990. __decorate([
  13991. BABYLON.serializeAsVector3()
  13992. ], PointLight.prototype, "position", void 0);
  13993. BABYLON.PointLight = PointLight;
  13994. })(BABYLON || (BABYLON = {}));
  13995. //# sourceMappingURL=babylon.pointLight.js.map
  13996. var BABYLON;
  13997. (function (BABYLON) {
  13998. var SpotLight = (function (_super) {
  13999. __extends(SpotLight, _super);
  14000. /**
  14001. * Creates a SpotLight object in the scene with the passed parameters :
  14002. * - `position` (Vector3) is the initial SpotLight position,
  14003. * - `direction` (Vector3) is the initial SpotLight direction,
  14004. * - `angle` (float, in radians) is the spot light cone angle,
  14005. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14006. * A spot light is a simply light oriented cone.
  14007. * It can cast shadows.
  14008. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14009. */
  14010. function SpotLight(name, position, direction, angle, exponent, scene) {
  14011. var _this = _super.call(this, name, scene) || this;
  14012. _this.position = position;
  14013. _this.direction = direction;
  14014. _this.angle = angle;
  14015. _this.exponent = exponent;
  14016. return _this;
  14017. }
  14018. /**
  14019. * Returns the string "SpotLight".
  14020. */
  14021. SpotLight.prototype.getClassName = function () {
  14022. return "SpotLight";
  14023. };
  14024. /**
  14025. * Returns the SpotLight absolute position in the World (Vector3).
  14026. */
  14027. SpotLight.prototype.getAbsolutePosition = function () {
  14028. return this.transformedPosition ? this.transformedPosition : this.position;
  14029. };
  14030. /**
  14031. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  14032. * Returns the SpotLight.
  14033. */
  14034. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14035. var activeCamera = this.getScene().activeCamera;
  14036. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14037. return this;
  14038. };
  14039. /**
  14040. * Boolean : false by default.
  14041. */
  14042. SpotLight.prototype.needCube = function () {
  14043. return false;
  14044. };
  14045. /**
  14046. * Boolean : true by default.
  14047. */
  14048. SpotLight.prototype.supportsVSM = function () {
  14049. return true;
  14050. };
  14051. /**
  14052. * Boolean : false by default.
  14053. */
  14054. SpotLight.prototype.needRefreshPerFrame = function () {
  14055. return false;
  14056. };
  14057. /**
  14058. * Returns the SpotLight direction (Vector3) for any passed face index.
  14059. */
  14060. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14061. return this.direction;
  14062. };
  14063. /**
  14064. * Updates the SpotLight direction towards the passed target (Vector3).
  14065. * Returns the updated direction.
  14066. */
  14067. SpotLight.prototype.setDirectionToTarget = function (target) {
  14068. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14069. return this.direction;
  14070. };
  14071. /**
  14072. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14073. */
  14074. SpotLight.prototype.computeTransformedPosition = function () {
  14075. if (this.parent && this.parent.getWorldMatrix) {
  14076. if (!this.transformedPosition) {
  14077. this.transformedPosition = BABYLON.Vector3.Zero();
  14078. }
  14079. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14080. return true;
  14081. }
  14082. return false;
  14083. };
  14084. /**
  14085. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14086. * Return the SpotLight.
  14087. */
  14088. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14089. var normalizeDirection;
  14090. if (this.parent && this.parent.getWorldMatrix) {
  14091. if (!this._transformedDirection) {
  14092. this._transformedDirection = BABYLON.Vector3.Zero();
  14093. }
  14094. this.computeTransformedPosition();
  14095. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14096. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14097. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14098. }
  14099. else {
  14100. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14101. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14102. }
  14103. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14104. return this;
  14105. };
  14106. SpotLight.prototype._getWorldMatrix = function () {
  14107. if (!this._worldMatrix) {
  14108. this._worldMatrix = BABYLON.Matrix.Identity();
  14109. }
  14110. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14111. return this._worldMatrix;
  14112. };
  14113. /**
  14114. * Returns the integer 2.
  14115. */
  14116. SpotLight.prototype.getTypeID = function () {
  14117. return 2;
  14118. };
  14119. /**
  14120. * Returns the SpotLight rotation (Vector3).
  14121. */
  14122. SpotLight.prototype.getRotation = function () {
  14123. this.direction.normalize();
  14124. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14125. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14126. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14127. };
  14128. return SpotLight;
  14129. }(BABYLON.Light));
  14130. __decorate([
  14131. BABYLON.serializeAsVector3()
  14132. ], SpotLight.prototype, "position", void 0);
  14133. __decorate([
  14134. BABYLON.serializeAsVector3()
  14135. ], SpotLight.prototype, "direction", void 0);
  14136. __decorate([
  14137. BABYLON.serialize()
  14138. ], SpotLight.prototype, "angle", void 0);
  14139. __decorate([
  14140. BABYLON.serialize()
  14141. ], SpotLight.prototype, "exponent", void 0);
  14142. BABYLON.SpotLight = SpotLight;
  14143. })(BABYLON || (BABYLON = {}));
  14144. //# sourceMappingURL=babylon.spotLight.js.map
  14145. var BABYLON;
  14146. (function (BABYLON) {
  14147. var HemisphericLight = (function (_super) {
  14148. __extends(HemisphericLight, _super);
  14149. /**
  14150. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14151. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14152. * The HemisphericLight can't cast shadows.
  14153. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14154. */
  14155. function HemisphericLight(name, direction, scene) {
  14156. var _this = _super.call(this, name, scene) || this;
  14157. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14158. _this.direction = direction;
  14159. return _this;
  14160. }
  14161. /**
  14162. * Returns the string "HemisphericLight".
  14163. */
  14164. HemisphericLight.prototype.getClassName = function () {
  14165. return "HemisphericLight";
  14166. };
  14167. /**
  14168. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14169. * Returns the updated direction.
  14170. */
  14171. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14172. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14173. return this.direction;
  14174. };
  14175. HemisphericLight.prototype.getShadowGenerator = function () {
  14176. return null;
  14177. };
  14178. /**
  14179. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14180. * Returns the HemisphericLight.
  14181. */
  14182. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14183. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14184. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14185. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14186. return this;
  14187. };
  14188. HemisphericLight.prototype._getWorldMatrix = function () {
  14189. if (!this._worldMatrix) {
  14190. this._worldMatrix = BABYLON.Matrix.Identity();
  14191. }
  14192. return this._worldMatrix;
  14193. };
  14194. /**
  14195. * Returns the integer 3.
  14196. */
  14197. HemisphericLight.prototype.getTypeID = function () {
  14198. return 3;
  14199. };
  14200. return HemisphericLight;
  14201. }(BABYLON.Light));
  14202. __decorate([
  14203. BABYLON.serializeAsColor3()
  14204. ], HemisphericLight.prototype, "groundColor", void 0);
  14205. __decorate([
  14206. BABYLON.serializeAsVector3()
  14207. ], HemisphericLight.prototype, "direction", void 0);
  14208. BABYLON.HemisphericLight = HemisphericLight;
  14209. })(BABYLON || (BABYLON = {}));
  14210. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14211. /// <reference path="babylon.light.ts" />
  14212. var BABYLON;
  14213. (function (BABYLON) {
  14214. var DirectionalLight = (function (_super) {
  14215. __extends(DirectionalLight, _super);
  14216. /**
  14217. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14218. * The directional light is emitted from everywhere in the given direction.
  14219. * It can cast shawdows.
  14220. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14221. */
  14222. function DirectionalLight(name, direction, scene) {
  14223. var _this = _super.call(this, name, scene) || this;
  14224. _this.shadowOrthoScale = 0.5;
  14225. _this.autoUpdateExtends = true;
  14226. // Cache
  14227. _this._orthoLeft = Number.MAX_VALUE;
  14228. _this._orthoRight = Number.MIN_VALUE;
  14229. _this._orthoTop = Number.MIN_VALUE;
  14230. _this._orthoBottom = Number.MAX_VALUE;
  14231. _this.position = direction.scale(-1.0);
  14232. _this.direction = direction;
  14233. return _this;
  14234. }
  14235. /**
  14236. * Returns the string "DirectionalLight".
  14237. */
  14238. DirectionalLight.prototype.getClassName = function () {
  14239. return "DirectionalLight";
  14240. };
  14241. /**
  14242. * Returns the DirectionalLight absolute position in the World.
  14243. */
  14244. DirectionalLight.prototype.getAbsolutePosition = function () {
  14245. return this.transformedPosition ? this.transformedPosition : this.position;
  14246. };
  14247. /**
  14248. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14249. * Returns the updated DirectionalLight direction (Vector3).
  14250. */
  14251. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14252. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14253. return this.direction;
  14254. };
  14255. /**
  14256. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14257. * Returns the DirectionalLight.
  14258. */
  14259. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14260. var activeCamera = this.getScene().activeCamera;
  14261. // Check extends
  14262. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14263. var tempVector3 = BABYLON.Vector3.Zero();
  14264. this._orthoLeft = Number.MAX_VALUE;
  14265. this._orthoRight = Number.MIN_VALUE;
  14266. this._orthoTop = Number.MIN_VALUE;
  14267. this._orthoBottom = Number.MAX_VALUE;
  14268. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14269. var mesh = renderList[meshIndex];
  14270. if (!mesh) {
  14271. continue;
  14272. }
  14273. var boundingInfo = mesh.getBoundingInfo();
  14274. if (!boundingInfo) {
  14275. continue;
  14276. }
  14277. var boundingBox = boundingInfo.boundingBox;
  14278. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14279. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14280. if (tempVector3.x < this._orthoLeft)
  14281. this._orthoLeft = tempVector3.x;
  14282. if (tempVector3.y < this._orthoBottom)
  14283. this._orthoBottom = tempVector3.y;
  14284. if (tempVector3.x > this._orthoRight)
  14285. this._orthoRight = tempVector3.x;
  14286. if (tempVector3.y > this._orthoTop)
  14287. this._orthoTop = tempVector3.y;
  14288. }
  14289. }
  14290. }
  14291. var xOffset = this._orthoRight - this._orthoLeft;
  14292. var yOffset = this._orthoTop - this._orthoBottom;
  14293. 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);
  14294. return this;
  14295. };
  14296. /**
  14297. * Boolean : true by default.
  14298. */
  14299. DirectionalLight.prototype.supportsVSM = function () {
  14300. return true;
  14301. };
  14302. /**
  14303. * Boolean : true by default.
  14304. */
  14305. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14306. return true;
  14307. };
  14308. /**
  14309. * Boolean : false by default.
  14310. */
  14311. DirectionalLight.prototype.needCube = function () {
  14312. return false;
  14313. };
  14314. /**
  14315. * Returns the light direction (Vector3) for any passed face index.
  14316. */
  14317. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14318. return this.direction;
  14319. };
  14320. /**
  14321. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14322. */
  14323. DirectionalLight.prototype.computeTransformedPosition = function () {
  14324. if (this.parent && this.parent.getWorldMatrix) {
  14325. if (!this.transformedPosition) {
  14326. this.transformedPosition = BABYLON.Vector3.Zero();
  14327. }
  14328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14329. return true;
  14330. }
  14331. return false;
  14332. };
  14333. /**
  14334. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14335. * Returns the DirectionalLight.
  14336. */
  14337. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14338. if (this.parent && this.parent.getWorldMatrix) {
  14339. if (!this._transformedDirection) {
  14340. this._transformedDirection = BABYLON.Vector3.Zero();
  14341. }
  14342. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14343. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14344. return this;
  14345. }
  14346. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14347. return this;
  14348. };
  14349. DirectionalLight.prototype._getWorldMatrix = function () {
  14350. if (!this._worldMatrix) {
  14351. this._worldMatrix = BABYLON.Matrix.Identity();
  14352. }
  14353. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14354. return this._worldMatrix;
  14355. };
  14356. /**
  14357. * Returns the integer 1.
  14358. */
  14359. DirectionalLight.prototype.getTypeID = function () {
  14360. return 1;
  14361. };
  14362. return DirectionalLight;
  14363. }(BABYLON.Light));
  14364. __decorate([
  14365. BABYLON.serializeAsVector3()
  14366. ], DirectionalLight.prototype, "position", void 0);
  14367. __decorate([
  14368. BABYLON.serializeAsVector3()
  14369. ], DirectionalLight.prototype, "direction", void 0);
  14370. __decorate([
  14371. BABYLON.serialize()
  14372. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14373. __decorate([
  14374. BABYLON.serialize()
  14375. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14376. BABYLON.DirectionalLight = DirectionalLight;
  14377. })(BABYLON || (BABYLON = {}));
  14378. //# sourceMappingURL=babylon.directionalLight.js.map
  14379. var BABYLON;
  14380. (function (BABYLON) {
  14381. var ShadowGenerator = (function () {
  14382. /**
  14383. * Creates a ShadowGenerator object.
  14384. * A ShadowGenerator is the required tool to use the shadows.
  14385. * Each light casting shadows needs to use its own ShadowGenerator.
  14386. * Required parameters :
  14387. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14388. * - `light` : the light object generating the shadows.
  14389. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14390. */
  14391. function ShadowGenerator(mapSize, light) {
  14392. var _this = this;
  14393. // Members
  14394. this._filter = ShadowGenerator.FILTER_NONE;
  14395. this.blurScale = 2;
  14396. this._blurBoxOffset = 0;
  14397. this._bias = 0.00005;
  14398. this._lightDirection = BABYLON.Vector3.Zero();
  14399. this.forceBackFacesOnly = false;
  14400. this._darkness = 0;
  14401. this._transparencyShadow = false;
  14402. this._viewMatrix = BABYLON.Matrix.Zero();
  14403. this._projectionMatrix = BABYLON.Matrix.Zero();
  14404. this._transformMatrix = BABYLON.Matrix.Zero();
  14405. this._worldViewProjection = BABYLON.Matrix.Zero();
  14406. this._currentFaceIndex = 0;
  14407. this._currentFaceIndexCache = 0;
  14408. this._useFullFloat = true;
  14409. this._light = light;
  14410. this._scene = light.getScene();
  14411. this._mapSize = mapSize;
  14412. light._shadowGenerator = this;
  14413. // Texture type fallback from float to int if not supported.
  14414. var textureType;
  14415. var caps = this._scene.getEngine().getCaps();
  14416. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14417. this._useFullFloat = true;
  14418. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14419. }
  14420. else {
  14421. this._useFullFloat = false;
  14422. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14423. }
  14424. // Render target
  14425. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14426. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14427. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14428. this._shadowMap.anisotropicFilteringLevel = 1;
  14429. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14430. this._shadowMap.renderParticles = false;
  14431. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14432. _this._currentFaceIndex = faceIndex;
  14433. });
  14434. this._shadowMap.onAfterUnbindObservable.add(function () {
  14435. if (!_this.useBlurVarianceShadowMap) {
  14436. return;
  14437. }
  14438. if (!_this._shadowMap2) {
  14439. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14440. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14441. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14442. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14443. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14444. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14445. effect.setTexture("textureSampler", _this._shadowMap);
  14446. });
  14447. _this.blurBoxOffset = 1;
  14448. }
  14449. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14450. });
  14451. // Custom render function
  14452. var renderSubMesh = function (subMesh) {
  14453. var mesh = subMesh.getRenderingMesh();
  14454. var scene = _this._scene;
  14455. var engine = scene.getEngine();
  14456. // Culling
  14457. engine.setState(subMesh.getMaterial().backFaceCulling);
  14458. // Managing instances
  14459. var batch = mesh._getInstancesRenderList(subMesh._id);
  14460. if (batch.mustReturn) {
  14461. return;
  14462. }
  14463. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14464. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14465. engine.enableEffect(_this._effect);
  14466. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14467. var material = subMesh.getMaterial();
  14468. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14469. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14470. if (_this.getLight().needCube()) {
  14471. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14472. }
  14473. // Alpha test
  14474. if (material && material.needAlphaTesting()) {
  14475. var alphaTexture = material.getAlphaTestTexture();
  14476. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14477. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14478. }
  14479. // Bones
  14480. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14481. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14482. }
  14483. if (_this.forceBackFacesOnly) {
  14484. engine.setState(true, 0, false, true);
  14485. }
  14486. // Draw
  14487. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14488. if (_this.forceBackFacesOnly) {
  14489. engine.setState(true, 0, false, false);
  14490. }
  14491. }
  14492. else {
  14493. // Need to reset refresh rate of the shadowMap
  14494. _this._shadowMap.resetRefreshCounter();
  14495. }
  14496. };
  14497. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14498. var index;
  14499. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14500. renderSubMesh(opaqueSubMeshes.data[index]);
  14501. }
  14502. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14503. renderSubMesh(alphaTestSubMeshes.data[index]);
  14504. }
  14505. if (_this._transparencyShadow) {
  14506. for (index = 0; index < transparentSubMeshes.length; index++) {
  14507. renderSubMesh(transparentSubMeshes.data[index]);
  14508. }
  14509. }
  14510. };
  14511. this._shadowMap.onClearObservable.add(function (engine) {
  14512. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14513. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14514. }
  14515. else {
  14516. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14517. }
  14518. });
  14519. }
  14520. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14521. // Static
  14522. get: function () {
  14523. return ShadowGenerator._FILTER_NONE;
  14524. },
  14525. enumerable: true,
  14526. configurable: true
  14527. });
  14528. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14529. get: function () {
  14530. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14536. get: function () {
  14537. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14543. get: function () {
  14544. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14550. get: function () {
  14551. return this._bias;
  14552. },
  14553. set: function (bias) {
  14554. this._bias = bias;
  14555. },
  14556. enumerable: true,
  14557. configurable: true
  14558. });
  14559. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14560. get: function () {
  14561. return this._blurBoxOffset;
  14562. },
  14563. set: function (value) {
  14564. var _this = this;
  14565. if (this._blurBoxOffset === value) {
  14566. return;
  14567. }
  14568. this._blurBoxOffset = value;
  14569. if (this._boxBlurPostprocess) {
  14570. this._boxBlurPostprocess.dispose();
  14571. }
  14572. 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);
  14573. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14574. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14575. });
  14576. },
  14577. enumerable: true,
  14578. configurable: true
  14579. });
  14580. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14581. get: function () {
  14582. return this._filter;
  14583. },
  14584. set: function (value) {
  14585. if (this._filter === value) {
  14586. return;
  14587. }
  14588. this._filter = value;
  14589. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14590. this._shadowMap.anisotropicFilteringLevel = 16;
  14591. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14592. }
  14593. else {
  14594. this._shadowMap.anisotropicFilteringLevel = 1;
  14595. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14596. }
  14597. },
  14598. enumerable: true,
  14599. configurable: true
  14600. });
  14601. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14602. get: function () {
  14603. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14604. },
  14605. set: function (value) {
  14606. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14607. },
  14608. enumerable: true,
  14609. configurable: true
  14610. });
  14611. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14612. get: function () {
  14613. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14614. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14615. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14616. },
  14617. set: function (value) {
  14618. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14619. },
  14620. enumerable: true,
  14621. configurable: true
  14622. });
  14623. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14624. get: function () {
  14625. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14626. },
  14627. set: function (value) {
  14628. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14629. },
  14630. enumerable: true,
  14631. configurable: true
  14632. });
  14633. /**
  14634. * Boolean : true when the ShadowGenerator is finally computed.
  14635. */
  14636. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14637. var defines = [];
  14638. if (this._useFullFloat) {
  14639. defines.push("#define FULLFLOAT");
  14640. }
  14641. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14642. defines.push("#define VSM");
  14643. }
  14644. if (this.getLight().needCube()) {
  14645. defines.push("#define CUBEMAP");
  14646. }
  14647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14648. var mesh = subMesh.getMesh();
  14649. var material = subMesh.getMaterial();
  14650. // Alpha test
  14651. if (material && material.needAlphaTesting()) {
  14652. defines.push("#define ALPHATEST");
  14653. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14654. attribs.push(BABYLON.VertexBuffer.UVKind);
  14655. defines.push("#define UV1");
  14656. }
  14657. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14658. var alphaTexture = material.getAlphaTestTexture();
  14659. if (alphaTexture.coordinatesIndex === 1) {
  14660. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14661. defines.push("#define UV2");
  14662. }
  14663. }
  14664. }
  14665. // Bones
  14666. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14669. if (mesh.numBoneInfluencers > 4) {
  14670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14672. }
  14673. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14674. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14675. }
  14676. else {
  14677. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14678. }
  14679. // Instances
  14680. if (useInstances) {
  14681. defines.push("#define INSTANCES");
  14682. attribs.push("world0");
  14683. attribs.push("world1");
  14684. attribs.push("world2");
  14685. attribs.push("world3");
  14686. }
  14687. // Get correct effect
  14688. var join = defines.join("\n");
  14689. if (this._cachedDefines !== join) {
  14690. this._cachedDefines = join;
  14691. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14692. }
  14693. return this._effect.isReady();
  14694. };
  14695. /**
  14696. * Returns a RenderTargetTexture object : the shadow map texture.
  14697. */
  14698. ShadowGenerator.prototype.getShadowMap = function () {
  14699. return this._shadowMap;
  14700. };
  14701. /**
  14702. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14703. */
  14704. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14705. if (this._shadowMap2) {
  14706. return this._shadowMap2;
  14707. }
  14708. return this._shadowMap;
  14709. };
  14710. /**
  14711. * Returns the associated light object.
  14712. */
  14713. ShadowGenerator.prototype.getLight = function () {
  14714. return this._light;
  14715. };
  14716. // Methods
  14717. /**
  14718. * Returns a Matrix object : the updated transformation matrix.
  14719. */
  14720. ShadowGenerator.prototype.getTransformMatrix = function () {
  14721. var scene = this._scene;
  14722. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14723. return this._transformMatrix;
  14724. }
  14725. this._currentRenderID = scene.getRenderId();
  14726. this._currentFaceIndexCache = this._currentFaceIndex;
  14727. var lightPosition = this._light.position;
  14728. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14729. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14730. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14731. }
  14732. if (this._light.computeTransformedPosition()) {
  14733. lightPosition = this._light.transformedPosition;
  14734. }
  14735. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14736. this._cachedPosition = lightPosition.clone();
  14737. this._cachedDirection = this._lightDirection.clone();
  14738. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14739. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14740. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14741. }
  14742. return this._transformMatrix;
  14743. };
  14744. /**
  14745. * Returns the darkness value (float).
  14746. */
  14747. ShadowGenerator.prototype.getDarkness = function () {
  14748. return this._darkness;
  14749. };
  14750. /**
  14751. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14752. * Returns the ShadowGenerator.
  14753. */
  14754. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14755. if (darkness >= 1.0)
  14756. this._darkness = 1.0;
  14757. else if (darkness <= 0.0)
  14758. this._darkness = 0.0;
  14759. else
  14760. this._darkness = darkness;
  14761. return this;
  14762. };
  14763. /**
  14764. * Sets the ability to have transparent shadow (boolean).
  14765. * Returns the ShadowGenerator.
  14766. */
  14767. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14768. this._transparencyShadow = hasShadow;
  14769. return this;
  14770. };
  14771. ShadowGenerator.prototype._packHalf = function (depth) {
  14772. var scale = depth * 255.0;
  14773. var fract = scale - Math.floor(scale);
  14774. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14775. };
  14776. /**
  14777. * Disposes the ShadowGenerator.
  14778. * Returns nothing.
  14779. */
  14780. ShadowGenerator.prototype.dispose = function () {
  14781. this._shadowMap.dispose();
  14782. if (this._shadowMap2) {
  14783. this._shadowMap2.dispose();
  14784. }
  14785. if (this._downSamplePostprocess) {
  14786. this._downSamplePostprocess.dispose();
  14787. }
  14788. if (this._boxBlurPostprocess) {
  14789. this._boxBlurPostprocess.dispose();
  14790. }
  14791. this._light._shadowGenerator = null;
  14792. };
  14793. /**
  14794. * Serializes the ShadowGenerator and returns a serializationObject.
  14795. */
  14796. ShadowGenerator.prototype.serialize = function () {
  14797. var serializationObject = {};
  14798. serializationObject.lightId = this._light.id;
  14799. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  14800. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  14801. serializationObject.usePoissonSampling = this.usePoissonSampling;
  14802. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  14803. serializationObject.renderList = [];
  14804. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  14805. var mesh = this.getShadowMap().renderList[meshIndex];
  14806. serializationObject.renderList.push(mesh.id);
  14807. }
  14808. return serializationObject;
  14809. };
  14810. /**
  14811. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  14812. */
  14813. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  14814. //casting to point light, as light is missing the position attr and typescript complains.
  14815. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14816. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14817. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14818. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  14819. meshes.forEach(function (mesh) {
  14820. shadowGenerator.getShadowMap().renderList.push(mesh);
  14821. });
  14822. }
  14823. if (parsedShadowGenerator.usePoissonSampling) {
  14824. shadowGenerator.usePoissonSampling = true;
  14825. }
  14826. else if (parsedShadowGenerator.useVarianceShadowMap) {
  14827. shadowGenerator.useVarianceShadowMap = true;
  14828. }
  14829. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  14830. shadowGenerator.useBlurVarianceShadowMap = true;
  14831. if (parsedShadowGenerator.blurScale) {
  14832. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  14833. }
  14834. if (parsedShadowGenerator.blurBoxOffset) {
  14835. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  14836. }
  14837. }
  14838. if (parsedShadowGenerator.bias !== undefined) {
  14839. shadowGenerator.bias = parsedShadowGenerator.bias;
  14840. }
  14841. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  14842. return shadowGenerator;
  14843. };
  14844. return ShadowGenerator;
  14845. }());
  14846. ShadowGenerator._FILTER_NONE = 0;
  14847. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  14848. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  14849. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  14850. BABYLON.ShadowGenerator = ShadowGenerator;
  14851. })(BABYLON || (BABYLON = {}));
  14852. //# sourceMappingURL=babylon.shadowGenerator.js.map
  14853. var BABYLON;
  14854. (function (BABYLON) {
  14855. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  14856. if (boxMin.x > sphereCenter.x + sphereRadius)
  14857. return false;
  14858. if (sphereCenter.x - sphereRadius > boxMax.x)
  14859. return false;
  14860. if (boxMin.y > sphereCenter.y + sphereRadius)
  14861. return false;
  14862. if (sphereCenter.y - sphereRadius > boxMax.y)
  14863. return false;
  14864. if (boxMin.z > sphereCenter.z + sphereRadius)
  14865. return false;
  14866. if (sphereCenter.z - sphereRadius > boxMax.z)
  14867. return false;
  14868. return true;
  14869. };
  14870. var getLowestRoot = (function () {
  14871. var result = { root: 0, found: false };
  14872. return function (a, b, c, maxR) {
  14873. result.root = 0;
  14874. result.found = false;
  14875. var determinant = b * b - 4.0 * a * c;
  14876. if (determinant < 0)
  14877. return result;
  14878. var sqrtD = Math.sqrt(determinant);
  14879. var r1 = (-b - sqrtD) / (2.0 * a);
  14880. var r2 = (-b + sqrtD) / (2.0 * a);
  14881. if (r1 > r2) {
  14882. var temp = r2;
  14883. r2 = r1;
  14884. r1 = temp;
  14885. }
  14886. if (r1 > 0 && r1 < maxR) {
  14887. result.root = r1;
  14888. result.found = true;
  14889. return result;
  14890. }
  14891. if (r2 > 0 && r2 < maxR) {
  14892. result.root = r2;
  14893. result.found = true;
  14894. return result;
  14895. }
  14896. return result;
  14897. };
  14898. })();
  14899. var Collider = (function () {
  14900. function Collider() {
  14901. this.radius = new BABYLON.Vector3(1, 1, 1);
  14902. this.retry = 0;
  14903. this.basePointWorld = BABYLON.Vector3.Zero();
  14904. this.velocityWorld = BABYLON.Vector3.Zero();
  14905. this.normalizedVelocity = BABYLON.Vector3.Zero();
  14906. this._collisionPoint = BABYLON.Vector3.Zero();
  14907. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  14908. this._tempVector = BABYLON.Vector3.Zero();
  14909. this._tempVector2 = BABYLON.Vector3.Zero();
  14910. this._tempVector3 = BABYLON.Vector3.Zero();
  14911. this._tempVector4 = BABYLON.Vector3.Zero();
  14912. this._edge = BABYLON.Vector3.Zero();
  14913. this._baseToVertex = BABYLON.Vector3.Zero();
  14914. this._destinationPoint = BABYLON.Vector3.Zero();
  14915. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  14916. this._displacementVector = BABYLON.Vector3.Zero();
  14917. this._collisionMask = -1;
  14918. }
  14919. Object.defineProperty(Collider.prototype, "collisionMask", {
  14920. get: function () {
  14921. return this._collisionMask;
  14922. },
  14923. set: function (mask) {
  14924. this._collisionMask = !isNaN(mask) ? mask : -1;
  14925. },
  14926. enumerable: true,
  14927. configurable: true
  14928. });
  14929. // Methods
  14930. Collider.prototype._initialize = function (source, dir, e) {
  14931. this.velocity = dir;
  14932. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  14933. this.basePoint = source;
  14934. source.multiplyToRef(this.radius, this.basePointWorld);
  14935. dir.multiplyToRef(this.radius, this.velocityWorld);
  14936. this.velocityWorldLength = this.velocityWorld.length();
  14937. this.epsilon = e;
  14938. this.collisionFound = false;
  14939. };
  14940. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  14941. pa.subtractToRef(point, this._tempVector);
  14942. pb.subtractToRef(point, this._tempVector2);
  14943. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  14944. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14945. if (d < 0)
  14946. return false;
  14947. pc.subtractToRef(point, this._tempVector3);
  14948. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  14949. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14950. if (d < 0)
  14951. return false;
  14952. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  14953. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  14954. return d >= 0;
  14955. };
  14956. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  14957. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  14958. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  14959. if (distance > this.velocityWorldLength + max + sphereRadius) {
  14960. return false;
  14961. }
  14962. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  14963. return false;
  14964. return true;
  14965. };
  14966. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  14967. var t0;
  14968. var embeddedInPlane = false;
  14969. //defensive programming, actually not needed.
  14970. if (!trianglePlaneArray) {
  14971. trianglePlaneArray = [];
  14972. }
  14973. if (!trianglePlaneArray[faceIndex]) {
  14974. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  14975. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  14976. }
  14977. var trianglePlane = trianglePlaneArray[faceIndex];
  14978. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  14979. return;
  14980. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  14981. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  14982. if (normalDotVelocity == 0) {
  14983. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  14984. return;
  14985. embeddedInPlane = true;
  14986. t0 = 0;
  14987. }
  14988. else {
  14989. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  14990. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  14991. if (t0 > t1) {
  14992. var temp = t1;
  14993. t1 = t0;
  14994. t0 = temp;
  14995. }
  14996. if (t0 > 1.0 || t1 < 0.0)
  14997. return;
  14998. if (t0 < 0)
  14999. t0 = 0;
  15000. if (t0 > 1.0)
  15001. t0 = 1.0;
  15002. }
  15003. this._collisionPoint.copyFromFloats(0, 0, 0);
  15004. var found = false;
  15005. var t = 1.0;
  15006. if (!embeddedInPlane) {
  15007. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15008. this.velocity.scaleToRef(t0, this._tempVector);
  15009. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15010. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15011. found = true;
  15012. t = t0;
  15013. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15014. }
  15015. }
  15016. if (!found) {
  15017. var velocitySquaredLength = this.velocity.lengthSquared();
  15018. var a = velocitySquaredLength;
  15019. this.basePoint.subtractToRef(p1, this._tempVector);
  15020. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15021. var c = this._tempVector.lengthSquared() - 1.0;
  15022. var lowestRoot = getLowestRoot(a, b, c, t);
  15023. if (lowestRoot.found) {
  15024. t = lowestRoot.root;
  15025. found = true;
  15026. this._collisionPoint.copyFrom(p1);
  15027. }
  15028. this.basePoint.subtractToRef(p2, this._tempVector);
  15029. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15030. c = this._tempVector.lengthSquared() - 1.0;
  15031. lowestRoot = getLowestRoot(a, b, c, t);
  15032. if (lowestRoot.found) {
  15033. t = lowestRoot.root;
  15034. found = true;
  15035. this._collisionPoint.copyFrom(p2);
  15036. }
  15037. this.basePoint.subtractToRef(p3, this._tempVector);
  15038. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15039. c = this._tempVector.lengthSquared() - 1.0;
  15040. lowestRoot = getLowestRoot(a, b, c, t);
  15041. if (lowestRoot.found) {
  15042. t = lowestRoot.root;
  15043. found = true;
  15044. this._collisionPoint.copyFrom(p3);
  15045. }
  15046. p2.subtractToRef(p1, this._edge);
  15047. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15048. var edgeSquaredLength = this._edge.lengthSquared();
  15049. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15050. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15051. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15052. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15053. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15054. lowestRoot = getLowestRoot(a, b, c, t);
  15055. if (lowestRoot.found) {
  15056. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15057. if (f >= 0.0 && f <= 1.0) {
  15058. t = lowestRoot.root;
  15059. found = true;
  15060. this._edge.scaleInPlace(f);
  15061. p1.addToRef(this._edge, this._collisionPoint);
  15062. }
  15063. }
  15064. p3.subtractToRef(p2, this._edge);
  15065. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15066. edgeSquaredLength = this._edge.lengthSquared();
  15067. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15068. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15069. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15070. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15071. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15072. lowestRoot = getLowestRoot(a, b, c, t);
  15073. if (lowestRoot.found) {
  15074. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15075. if (f >= 0.0 && f <= 1.0) {
  15076. t = lowestRoot.root;
  15077. found = true;
  15078. this._edge.scaleInPlace(f);
  15079. p2.addToRef(this._edge, this._collisionPoint);
  15080. }
  15081. }
  15082. p1.subtractToRef(p3, this._edge);
  15083. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15084. edgeSquaredLength = this._edge.lengthSquared();
  15085. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15086. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15087. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15088. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15089. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15090. lowestRoot = getLowestRoot(a, b, c, t);
  15091. if (lowestRoot.found) {
  15092. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15093. if (f >= 0.0 && f <= 1.0) {
  15094. t = lowestRoot.root;
  15095. found = true;
  15096. this._edge.scaleInPlace(f);
  15097. p3.addToRef(this._edge, this._collisionPoint);
  15098. }
  15099. }
  15100. }
  15101. if (found) {
  15102. var distToCollision = t * this.velocity.length();
  15103. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15104. if (!this.intersectionPoint) {
  15105. this.intersectionPoint = this._collisionPoint.clone();
  15106. }
  15107. else {
  15108. this.intersectionPoint.copyFrom(this._collisionPoint);
  15109. }
  15110. this.nearestDistance = distToCollision;
  15111. this.collisionFound = true;
  15112. }
  15113. }
  15114. };
  15115. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15116. for (var i = indexStart; i < indexEnd; i += 3) {
  15117. var p1 = pts[indices[i] - decal];
  15118. var p2 = pts[indices[i + 1] - decal];
  15119. var p3 = pts[indices[i + 2] - decal];
  15120. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15121. }
  15122. };
  15123. Collider.prototype._getResponse = function (pos, vel) {
  15124. pos.addToRef(vel, this._destinationPoint);
  15125. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15126. this.basePoint.addToRef(vel, pos);
  15127. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15128. this._slidePlaneNormal.normalize();
  15129. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15130. pos.addInPlace(this._displacementVector);
  15131. this.intersectionPoint.addInPlace(this._displacementVector);
  15132. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15133. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15134. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15135. };
  15136. return Collider;
  15137. }());
  15138. BABYLON.Collider = Collider;
  15139. })(BABYLON || (BABYLON = {}));
  15140. //# sourceMappingURL=babylon.collider.js.map
  15141. var BABYLON;
  15142. (function (BABYLON) {
  15143. //WebWorker code will be inserted to this variable.
  15144. BABYLON.CollisionWorker = "";
  15145. var WorkerTaskType;
  15146. (function (WorkerTaskType) {
  15147. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15148. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15149. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15150. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15151. var WorkerReplyType;
  15152. (function (WorkerReplyType) {
  15153. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15154. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15155. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15156. var CollisionCoordinatorWorker = (function () {
  15157. function CollisionCoordinatorWorker() {
  15158. var _this = this;
  15159. this._scaledPosition = BABYLON.Vector3.Zero();
  15160. this._scaledVelocity = BABYLON.Vector3.Zero();
  15161. this.onMeshUpdated = function (mesh) {
  15162. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15163. };
  15164. this.onGeometryUpdated = function (geometry) {
  15165. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15166. };
  15167. this._afterRender = function () {
  15168. if (!_this._init)
  15169. return;
  15170. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15171. return;
  15172. }
  15173. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15174. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15175. if (_this._runningUpdated > 4) {
  15176. return;
  15177. }
  15178. ++_this._runningUpdated;
  15179. var payload = {
  15180. updatedMeshes: _this._addUpdateMeshesList,
  15181. updatedGeometries: _this._addUpdateGeometriesList,
  15182. removedGeometries: _this._toRemoveGeometryArray,
  15183. removedMeshes: _this._toRemoveMeshesArray
  15184. };
  15185. var message = {
  15186. payload: payload,
  15187. taskType: WorkerTaskType.UPDATE
  15188. };
  15189. var serializable = [];
  15190. for (var id in payload.updatedGeometries) {
  15191. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15192. //prepare transferables
  15193. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15194. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15195. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15196. }
  15197. }
  15198. _this._worker.postMessage(message, serializable);
  15199. _this._addUpdateMeshesList = {};
  15200. _this._addUpdateGeometriesList = {};
  15201. _this._toRemoveGeometryArray = [];
  15202. _this._toRemoveMeshesArray = [];
  15203. };
  15204. this._onMessageFromWorker = function (e) {
  15205. var returnData = e.data;
  15206. if (returnData.error != WorkerReplyType.SUCCESS) {
  15207. //TODO what errors can be returned from the worker?
  15208. BABYLON.Tools.Warn("error returned from worker!");
  15209. return;
  15210. }
  15211. switch (returnData.taskType) {
  15212. case WorkerTaskType.INIT:
  15213. _this._init = true;
  15214. //Update the worked with ALL of the scene's current state
  15215. _this._scene.meshes.forEach(function (mesh) {
  15216. _this.onMeshAdded(mesh);
  15217. });
  15218. _this._scene.getGeometries().forEach(function (geometry) {
  15219. _this.onGeometryAdded(geometry);
  15220. });
  15221. break;
  15222. case WorkerTaskType.UPDATE:
  15223. _this._runningUpdated--;
  15224. break;
  15225. case WorkerTaskType.COLLIDE:
  15226. _this._runningCollisionTask = false;
  15227. var returnPayload = returnData.payload;
  15228. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15229. return;
  15230. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15231. //cleanup
  15232. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15233. break;
  15234. }
  15235. };
  15236. this._collisionsCallbackArray = [];
  15237. this._init = false;
  15238. this._runningUpdated = 0;
  15239. this._runningCollisionTask = false;
  15240. this._addUpdateMeshesList = {};
  15241. this._addUpdateGeometriesList = {};
  15242. this._toRemoveGeometryArray = [];
  15243. this._toRemoveMeshesArray = [];
  15244. }
  15245. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15246. if (!this._init)
  15247. return;
  15248. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15249. return;
  15250. position.divideToRef(collider.radius, this._scaledPosition);
  15251. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15252. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15253. var payload = {
  15254. collider: {
  15255. position: this._scaledPosition.asArray(),
  15256. velocity: this._scaledVelocity.asArray(),
  15257. radius: collider.radius.asArray()
  15258. },
  15259. collisionId: collisionIndex,
  15260. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15261. maximumRetry: maximumRetry
  15262. };
  15263. var message = {
  15264. payload: payload,
  15265. taskType: WorkerTaskType.COLLIDE
  15266. };
  15267. this._worker.postMessage(message);
  15268. };
  15269. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15270. this._scene = scene;
  15271. this._scene.registerAfterRender(this._afterRender);
  15272. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15273. this._worker = new Worker(workerUrl);
  15274. this._worker.onmessage = this._onMessageFromWorker;
  15275. var message = {
  15276. payload: {},
  15277. taskType: WorkerTaskType.INIT
  15278. };
  15279. this._worker.postMessage(message);
  15280. };
  15281. CollisionCoordinatorWorker.prototype.destroy = function () {
  15282. this._scene.unregisterAfterRender(this._afterRender);
  15283. this._worker.terminate();
  15284. };
  15285. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15286. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15287. this.onMeshUpdated(mesh);
  15288. };
  15289. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15290. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15291. };
  15292. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15293. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15294. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15295. this.onGeometryUpdated(geometry);
  15296. };
  15297. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15298. this._toRemoveGeometryArray.push(geometry.id);
  15299. };
  15300. return CollisionCoordinatorWorker;
  15301. }());
  15302. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15303. var submeshes = [];
  15304. if (mesh.subMeshes) {
  15305. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15306. return {
  15307. position: idx,
  15308. verticesStart: sm.verticesStart,
  15309. verticesCount: sm.verticesCount,
  15310. indexStart: sm.indexStart,
  15311. indexCount: sm.indexCount,
  15312. hasMaterial: !!sm.getMaterial(),
  15313. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15314. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15315. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15316. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15317. };
  15318. });
  15319. }
  15320. var geometryId = null;
  15321. if (mesh instanceof BABYLON.Mesh) {
  15322. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15323. }
  15324. else if (mesh instanceof BABYLON.InstancedMesh) {
  15325. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15326. }
  15327. return {
  15328. uniqueId: mesh.uniqueId,
  15329. id: mesh.id,
  15330. name: mesh.name,
  15331. geometryId: geometryId,
  15332. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15333. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15334. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15335. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15336. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15337. subMeshes: submeshes,
  15338. checkCollisions: mesh.checkCollisions
  15339. };
  15340. };
  15341. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15342. return {
  15343. id: geometry.id,
  15344. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15345. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15346. indices: new Uint32Array(geometry.getIndices() || []),
  15347. };
  15348. };
  15349. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15350. var CollisionCoordinatorLegacy = (function () {
  15351. function CollisionCoordinatorLegacy() {
  15352. this._scaledPosition = BABYLON.Vector3.Zero();
  15353. this._scaledVelocity = BABYLON.Vector3.Zero();
  15354. this._finalPosition = BABYLON.Vector3.Zero();
  15355. }
  15356. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15357. position.divideToRef(collider.radius, this._scaledPosition);
  15358. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15359. collider.collidedMesh = null;
  15360. collider.retry = 0;
  15361. collider.initialVelocity = this._scaledVelocity;
  15362. collider.initialPosition = this._scaledPosition;
  15363. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15364. this._finalPosition.multiplyInPlace(collider.radius);
  15365. //run the callback
  15366. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15367. };
  15368. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15369. this._scene = scene;
  15370. };
  15371. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15372. //Legacy need no destruction method.
  15373. };
  15374. //No update in legacy mode
  15375. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15376. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15377. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15378. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15379. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15380. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15381. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15382. if (excludedMesh === void 0) { excludedMesh = null; }
  15383. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15384. if (collider.retry >= maximumRetry) {
  15385. finalPosition.copyFrom(position);
  15386. return;
  15387. }
  15388. // Check if this is a mesh else camera or -1
  15389. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15390. collider._initialize(position, velocity, closeDistance);
  15391. // Check all meshes
  15392. for (var index = 0; index < this._scene.meshes.length; index++) {
  15393. var mesh = this._scene.meshes[index];
  15394. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15395. mesh._checkCollision(collider);
  15396. }
  15397. }
  15398. if (!collider.collisionFound) {
  15399. position.addToRef(velocity, finalPosition);
  15400. return;
  15401. }
  15402. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15403. collider._getResponse(position, velocity);
  15404. }
  15405. if (velocity.length() <= closeDistance) {
  15406. finalPosition.copyFrom(position);
  15407. return;
  15408. }
  15409. collider.retry++;
  15410. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15411. };
  15412. return CollisionCoordinatorLegacy;
  15413. }());
  15414. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15415. })(BABYLON || (BABYLON = {}));
  15416. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15417. var BABYLON;
  15418. (function (BABYLON) {
  15419. var Camera = (function (_super) {
  15420. __extends(Camera, _super);
  15421. function Camera(name, position, scene) {
  15422. var _this = _super.call(this, name, scene) || this;
  15423. _this.upVector = BABYLON.Vector3.Up();
  15424. _this.orthoLeft = null;
  15425. _this.orthoRight = null;
  15426. _this.orthoBottom = null;
  15427. _this.orthoTop = null;
  15428. _this.fov = 0.8;
  15429. _this.minZ = 1.0;
  15430. _this.maxZ = 10000.0;
  15431. _this.inertia = 0.9;
  15432. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15433. _this.isIntermediate = false;
  15434. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15435. _this.layerMask = 0x0FFFFFFF;
  15436. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15437. // Camera rig members
  15438. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15439. _this._rigCameras = new Array();
  15440. // Cache
  15441. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15442. _this._projectionMatrix = new BABYLON.Matrix();
  15443. _this._doNotComputeProjectionMatrix = false;
  15444. _this._postProcesses = new Array();
  15445. _this._transformMatrix = BABYLON.Matrix.Zero();
  15446. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15447. _this._activeMeshes = new BABYLON.SmartArray(256);
  15448. _this._globalPosition = BABYLON.Vector3.Zero();
  15449. _this._refreshFrustumPlanes = true;
  15450. scene.addCamera(_this);
  15451. if (!scene.activeCamera) {
  15452. scene.activeCamera = _this;
  15453. }
  15454. _this.position = position;
  15455. return _this;
  15456. }
  15457. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15458. get: function () {
  15459. return Camera._PERSPECTIVE_CAMERA;
  15460. },
  15461. enumerable: true,
  15462. configurable: true
  15463. });
  15464. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15465. get: function () {
  15466. return Camera._ORTHOGRAPHIC_CAMERA;
  15467. },
  15468. enumerable: true,
  15469. configurable: true
  15470. });
  15471. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15472. get: function () {
  15473. return Camera._FOVMODE_VERTICAL_FIXED;
  15474. },
  15475. enumerable: true,
  15476. configurable: true
  15477. });
  15478. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15479. get: function () {
  15480. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15481. },
  15482. enumerable: true,
  15483. configurable: true
  15484. });
  15485. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15486. get: function () {
  15487. return Camera._RIG_MODE_NONE;
  15488. },
  15489. enumerable: true,
  15490. configurable: true
  15491. });
  15492. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15493. get: function () {
  15494. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15495. },
  15496. enumerable: true,
  15497. configurable: true
  15498. });
  15499. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15500. get: function () {
  15501. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15502. },
  15503. enumerable: true,
  15504. configurable: true
  15505. });
  15506. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15507. get: function () {
  15508. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15509. },
  15510. enumerable: true,
  15511. configurable: true
  15512. });
  15513. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15514. get: function () {
  15515. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15516. },
  15517. enumerable: true,
  15518. configurable: true
  15519. });
  15520. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15521. get: function () {
  15522. return Camera._RIG_MODE_VR;
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15528. get: function () {
  15529. return Camera._RIG_MODE_WEBVR;
  15530. },
  15531. enumerable: true,
  15532. configurable: true
  15533. });
  15534. Camera.prototype.getClassName = function () {
  15535. return "Camera";
  15536. };
  15537. /**
  15538. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15539. */
  15540. Camera.prototype.toString = function (fullDetails) {
  15541. var ret = "Name: " + this.name;
  15542. ret += ", type: " + this.getClassName();
  15543. if (this.animations) {
  15544. for (var i = 0; i < this.animations.length; i++) {
  15545. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15546. }
  15547. }
  15548. if (fullDetails) {
  15549. }
  15550. return ret;
  15551. };
  15552. Object.defineProperty(Camera.prototype, "globalPosition", {
  15553. get: function () {
  15554. return this._globalPosition;
  15555. },
  15556. enumerable: true,
  15557. configurable: true
  15558. });
  15559. Camera.prototype.getActiveMeshes = function () {
  15560. return this._activeMeshes;
  15561. };
  15562. Camera.prototype.isActiveMesh = function (mesh) {
  15563. return (this._activeMeshes.indexOf(mesh) !== -1);
  15564. };
  15565. //Cache
  15566. Camera.prototype._initCache = function () {
  15567. _super.prototype._initCache.call(this);
  15568. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15569. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15570. this._cache.mode = undefined;
  15571. this._cache.minZ = undefined;
  15572. this._cache.maxZ = undefined;
  15573. this._cache.fov = undefined;
  15574. this._cache.fovMode = undefined;
  15575. this._cache.aspectRatio = undefined;
  15576. this._cache.orthoLeft = undefined;
  15577. this._cache.orthoRight = undefined;
  15578. this._cache.orthoBottom = undefined;
  15579. this._cache.orthoTop = undefined;
  15580. this._cache.renderWidth = undefined;
  15581. this._cache.renderHeight = undefined;
  15582. };
  15583. Camera.prototype._updateCache = function (ignoreParentClass) {
  15584. if (!ignoreParentClass) {
  15585. _super.prototype._updateCache.call(this);
  15586. }
  15587. var engine = this.getEngine();
  15588. this._cache.position.copyFrom(this.position);
  15589. this._cache.upVector.copyFrom(this.upVector);
  15590. this._cache.mode = this.mode;
  15591. this._cache.minZ = this.minZ;
  15592. this._cache.maxZ = this.maxZ;
  15593. this._cache.fov = this.fov;
  15594. this._cache.fovMode = this.fovMode;
  15595. this._cache.aspectRatio = engine.getAspectRatio(this);
  15596. this._cache.orthoLeft = this.orthoLeft;
  15597. this._cache.orthoRight = this.orthoRight;
  15598. this._cache.orthoBottom = this.orthoBottom;
  15599. this._cache.orthoTop = this.orthoTop;
  15600. this._cache.renderWidth = engine.getRenderWidth();
  15601. this._cache.renderHeight = engine.getRenderHeight();
  15602. };
  15603. Camera.prototype._updateFromScene = function () {
  15604. this.updateCache();
  15605. this.update();
  15606. };
  15607. // Synchronized
  15608. Camera.prototype._isSynchronized = function () {
  15609. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15610. };
  15611. Camera.prototype._isSynchronizedViewMatrix = function () {
  15612. if (!_super.prototype._isSynchronized.call(this))
  15613. return false;
  15614. return this._cache.position.equals(this.position)
  15615. && this._cache.upVector.equals(this.upVector)
  15616. && this.isSynchronizedWithParent();
  15617. };
  15618. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15619. var check = this._cache.mode === this.mode
  15620. && this._cache.minZ === this.minZ
  15621. && this._cache.maxZ === this.maxZ;
  15622. if (!check) {
  15623. return false;
  15624. }
  15625. var engine = this.getEngine();
  15626. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15627. check = this._cache.fov === this.fov
  15628. && this._cache.fovMode === this.fovMode
  15629. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15630. }
  15631. else {
  15632. check = this._cache.orthoLeft === this.orthoLeft
  15633. && this._cache.orthoRight === this.orthoRight
  15634. && this._cache.orthoBottom === this.orthoBottom
  15635. && this._cache.orthoTop === this.orthoTop
  15636. && this._cache.renderWidth === engine.getRenderWidth()
  15637. && this._cache.renderHeight === engine.getRenderHeight();
  15638. }
  15639. return check;
  15640. };
  15641. // Controls
  15642. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15643. };
  15644. Camera.prototype.detachControl = function (element) {
  15645. };
  15646. Camera.prototype.update = function () {
  15647. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15648. this._updateRigCameras();
  15649. }
  15650. this._checkInputs();
  15651. };
  15652. Camera.prototype._checkInputs = function () {
  15653. };
  15654. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15655. // invalidate framebuffer
  15656. if (this._postProcesses.length > 0) {
  15657. this._postProcesses[0].markTextureDirty();
  15658. }
  15659. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15660. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15661. var cam = this._rigCameras[i];
  15662. var rigPostProcess = cam._rigPostProcess;
  15663. // for VR rig, there does not have to be a post process
  15664. if (rigPostProcess) {
  15665. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15666. if (isPass) {
  15667. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15668. cam.isIntermediate = this._postProcesses.length === 0;
  15669. }
  15670. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15671. rigPostProcess.markTextureDirty();
  15672. }
  15673. else {
  15674. cam._postProcesses = this._postProcesses.slice(0);
  15675. }
  15676. }
  15677. };
  15678. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15679. if (insertAt === void 0) { insertAt = null; }
  15680. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15681. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15682. return 0;
  15683. }
  15684. if (insertAt == null || insertAt < 0) {
  15685. this._postProcesses.push(postProcess);
  15686. }
  15687. else {
  15688. this._postProcesses.splice(insertAt, 0, postProcess);
  15689. }
  15690. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15691. return this._postProcesses.indexOf(postProcess);
  15692. };
  15693. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15694. if (atIndices === void 0) { atIndices = null; }
  15695. var result = [];
  15696. var i;
  15697. var index;
  15698. if (!atIndices) {
  15699. var idx = this._postProcesses.indexOf(postProcess);
  15700. if (idx !== -1) {
  15701. this._postProcesses.splice(idx, 1);
  15702. }
  15703. }
  15704. else {
  15705. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15706. // iterate descending, so can just splice as we go
  15707. for (i = atIndices.length - 1; i >= 0; i--) {
  15708. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15709. result.push(i);
  15710. continue;
  15711. }
  15712. index = atIndices[i];
  15713. this._postProcesses.splice(index, 1);
  15714. }
  15715. }
  15716. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15717. return result;
  15718. };
  15719. Camera.prototype.getWorldMatrix = function () {
  15720. if (!this._worldMatrix) {
  15721. this._worldMatrix = BABYLON.Matrix.Identity();
  15722. }
  15723. var viewMatrix = this.getViewMatrix();
  15724. viewMatrix.invertToRef(this._worldMatrix);
  15725. return this._worldMatrix;
  15726. };
  15727. Camera.prototype._getViewMatrix = function () {
  15728. return BABYLON.Matrix.Identity();
  15729. };
  15730. Camera.prototype.getViewMatrix = function (force) {
  15731. this._computedViewMatrix = this._computeViewMatrix(force);
  15732. if (!force && this._isSynchronizedViewMatrix()) {
  15733. return this._computedViewMatrix;
  15734. }
  15735. this._refreshFrustumPlanes = true;
  15736. if (!this.parent || !this.parent.getWorldMatrix) {
  15737. this._globalPosition.copyFrom(this.position);
  15738. }
  15739. else {
  15740. if (!this._worldMatrix) {
  15741. this._worldMatrix = BABYLON.Matrix.Identity();
  15742. }
  15743. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15744. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15745. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15746. this._computedViewMatrix.invert();
  15747. this._markSyncedWithParent();
  15748. }
  15749. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15750. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15751. }
  15752. this._currentRenderId = this.getScene().getRenderId();
  15753. return this._computedViewMatrix;
  15754. };
  15755. Camera.prototype._computeViewMatrix = function (force) {
  15756. if (!force && this._isSynchronizedViewMatrix()) {
  15757. return this._computedViewMatrix;
  15758. }
  15759. this._computedViewMatrix = this._getViewMatrix();
  15760. this._currentRenderId = this.getScene().getRenderId();
  15761. return this._computedViewMatrix;
  15762. };
  15763. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15764. this._doNotComputeProjectionMatrix = true;
  15765. if (projection !== undefined) {
  15766. this._projectionMatrix = projection;
  15767. }
  15768. };
  15769. ;
  15770. Camera.prototype.unfreezeProjectionMatrix = function () {
  15771. this._doNotComputeProjectionMatrix = false;
  15772. };
  15773. ;
  15774. Camera.prototype.getProjectionMatrix = function (force) {
  15775. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15776. return this._projectionMatrix;
  15777. }
  15778. this._refreshFrustumPlanes = true;
  15779. var engine = this.getEngine();
  15780. var scene = this.getScene();
  15781. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15782. if (this.minZ <= 0) {
  15783. this.minZ = 0.1;
  15784. }
  15785. if (scene.useRightHandedSystem) {
  15786. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15787. }
  15788. else {
  15789. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15790. }
  15791. return this._projectionMatrix;
  15792. }
  15793. var halfWidth = engine.getRenderWidth() / 2.0;
  15794. var halfHeight = engine.getRenderHeight() / 2.0;
  15795. if (scene.useRightHandedSystem) {
  15796. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15797. }
  15798. else {
  15799. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15800. }
  15801. return this._projectionMatrix;
  15802. };
  15803. Camera.prototype.getTranformationMatrix = function () {
  15804. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15805. return this._transformMatrix;
  15806. };
  15807. Camera.prototype.updateFrustumPlanes = function () {
  15808. if (!this._refreshFrustumPlanes) {
  15809. return;
  15810. }
  15811. this.getTranformationMatrix();
  15812. if (!this._frustumPlanes) {
  15813. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15814. }
  15815. else {
  15816. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15817. }
  15818. this._refreshFrustumPlanes = false;
  15819. };
  15820. Camera.prototype.isInFrustum = function (target) {
  15821. this.updateFrustumPlanes();
  15822. return target.isInFrustum(this._frustumPlanes);
  15823. };
  15824. Camera.prototype.isCompletelyInFrustum = function (target) {
  15825. this.updateFrustumPlanes();
  15826. return target.isCompletelyInFrustum(this._frustumPlanes);
  15827. };
  15828. Camera.prototype.dispose = function () {
  15829. // Animations
  15830. this.getScene().stopAnimation(this);
  15831. // Remove from scene
  15832. this.getScene().removeCamera(this);
  15833. while (this._rigCameras.length > 0) {
  15834. this._rigCameras.pop().dispose();
  15835. }
  15836. // Postprocesses
  15837. var i = this._postProcesses.length;
  15838. while (--i >= 0) {
  15839. this._postProcesses[i].dispose(this);
  15840. }
  15841. _super.prototype.dispose.call(this);
  15842. };
  15843. // ---- Camera rigs section ----
  15844. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15845. while (this._rigCameras.length > 0) {
  15846. this._rigCameras.pop().dispose();
  15847. }
  15848. this.cameraRigMode = mode;
  15849. this._cameraRigParams = {};
  15850. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15851. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15852. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15853. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15854. // create the rig cameras, unless none
  15855. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15856. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15857. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15858. }
  15859. switch (this.cameraRigMode) {
  15860. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15861. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15862. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15863. break;
  15864. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15865. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15866. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15867. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15868. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15869. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15870. break;
  15871. case Camera.RIG_MODE_VR:
  15872. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15873. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15874. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15875. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15876. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15877. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15878. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15879. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15880. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15881. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15882. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15883. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15884. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15885. if (metrics.compensateDistortion) {
  15886. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15887. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15888. }
  15889. break;
  15890. case Camera.RIG_MODE_WEBVR:
  15891. if (rigParams.vrDisplay) {
  15892. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15893. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15894. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15895. this._rigCameras[0].setCameraRigParameter("left", true);
  15896. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15897. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  15898. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15899. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15900. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15901. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15902. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15903. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  15904. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15905. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15906. }
  15907. break;
  15908. }
  15909. this._cascadePostProcessesToRigCams();
  15910. this.
  15911. update();
  15912. };
  15913. Camera.prototype._getVRProjectionMatrix = function () {
  15914. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15915. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15916. return this._projectionMatrix;
  15917. };
  15918. Camera.prototype._getWebVRProjectionMatrix = function () {
  15919. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  15920. //babylon compatible matrix
  15921. [8, 9, 10, 11].forEach(function (num) {
  15922. projectionArray[num] *= -1;
  15923. });
  15924. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  15925. return this._projectionMatrix;
  15926. };
  15927. //Can be used, but we'll use the free camera's view matrix calculation
  15928. Camera.prototype._getWebVRViewMatrix = function () {
  15929. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  15930. //babylon compatible matrix
  15931. [8, 9, 10, 11].forEach(function (num) {
  15932. projectionArray[num] *= -1;
  15933. });
  15934. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  15935. return this._webvrViewMatrix;
  15936. };
  15937. Camera.prototype.setCameraRigParameter = function (name, value) {
  15938. if (!this._cameraRigParams) {
  15939. this._cameraRigParams = {};
  15940. }
  15941. this._cameraRigParams[name] = value;
  15942. //provisionnally:
  15943. if (name === "interaxialDistance") {
  15944. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15945. }
  15946. };
  15947. /**
  15948. * needs to be overridden by children so sub has required properties to be copied
  15949. */
  15950. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15951. return null;
  15952. };
  15953. /**
  15954. * May need to be overridden by children
  15955. */
  15956. Camera.prototype._updateRigCameras = function () {
  15957. for (var i = 0; i < this._rigCameras.length; i++) {
  15958. this._rigCameras[i].minZ = this.minZ;
  15959. this._rigCameras[i].maxZ = this.maxZ;
  15960. this._rigCameras[i].fov = this.fov;
  15961. }
  15962. // only update viewport when ANAGLYPH
  15963. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15964. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15965. }
  15966. };
  15967. Camera.prototype._setupInputs = function () {
  15968. };
  15969. Camera.prototype.serialize = function () {
  15970. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15971. // Type
  15972. serializationObject.type = this.getClassName();
  15973. // Parent
  15974. if (this.parent) {
  15975. serializationObject.parentId = this.parent.id;
  15976. }
  15977. if (this.inputs) {
  15978. this.inputs.serialize(serializationObject);
  15979. }
  15980. // Animations
  15981. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15982. serializationObject.ranges = this.serializeAnimationRanges();
  15983. return serializationObject;
  15984. };
  15985. Camera.prototype.clone = function (name) {
  15986. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15987. };
  15988. Camera.prototype.getDirection = function (localAxis) {
  15989. var result = BABYLON.Vector3.Zero();
  15990. this.getDirectionToRef(localAxis, result);
  15991. return result;
  15992. };
  15993. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15994. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15995. };
  15996. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15997. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15998. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15999. switch (type) {
  16000. case "ArcRotateCamera":
  16001. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16002. case "DeviceOrientationCamera":
  16003. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16004. case "FollowCamera":
  16005. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16006. case "ArcFollowCamera":
  16007. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16008. case "GamepadCamera":
  16009. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16010. case "TouchCamera":
  16011. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16012. case "VirtualJoysticksCamera":
  16013. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16014. case "WebVRFreeCamera":
  16015. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16016. case "WebVRGamepadCamera":
  16017. return function () { return new BABYLON.WebVRGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16018. case "VRDeviceOrientationFreeCamera":
  16019. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16020. case "VRDeviceOrientationGamepadCamera":
  16021. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16022. case "AnaglyphArcRotateCamera":
  16023. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16024. case "AnaglyphFreeCamera":
  16025. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16026. case "AnaglyphGamepadCamera":
  16027. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16028. case "AnaglyphUniversalCamera":
  16029. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16030. case "StereoscopicArcRotateCamera":
  16031. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16032. case "StereoscopicFreeCamera":
  16033. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16034. case "StereoscopicGamepadCamera":
  16035. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16036. case "StereoscopicUniversalCamera":
  16037. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16038. case "FreeCamera":
  16039. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16040. default:
  16041. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16042. }
  16043. };
  16044. Camera.Parse = function (parsedCamera, scene) {
  16045. var type = parsedCamera.type;
  16046. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16047. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16048. // Parent
  16049. if (parsedCamera.parentId) {
  16050. camera._waitingParentId = parsedCamera.parentId;
  16051. }
  16052. //If camera has an input manager, let it parse inputs settings
  16053. if (camera.inputs) {
  16054. camera.inputs.parse(parsedCamera);
  16055. camera._setupInputs();
  16056. }
  16057. // Target
  16058. if (parsedCamera.target) {
  16059. if (camera.setTarget) {
  16060. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16061. }
  16062. }
  16063. // Apply 3d rig, when found
  16064. if (parsedCamera.cameraRigMode) {
  16065. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16066. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16067. }
  16068. // Animations
  16069. if (parsedCamera.animations) {
  16070. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16071. var parsedAnimation = parsedCamera.animations[animationIndex];
  16072. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16073. }
  16074. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16075. }
  16076. if (parsedCamera.autoAnimate) {
  16077. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16078. }
  16079. return camera;
  16080. };
  16081. return Camera;
  16082. }(BABYLON.Node));
  16083. // Statics
  16084. Camera._PERSPECTIVE_CAMERA = 0;
  16085. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16086. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16087. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16088. Camera._RIG_MODE_NONE = 0;
  16089. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16090. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16091. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16092. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16093. Camera._RIG_MODE_VR = 20;
  16094. Camera._RIG_MODE_WEBVR = 21;
  16095. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16096. __decorate([
  16097. BABYLON.serializeAsVector3()
  16098. ], Camera.prototype, "position", void 0);
  16099. __decorate([
  16100. BABYLON.serializeAsVector3()
  16101. ], Camera.prototype, "upVector", void 0);
  16102. __decorate([
  16103. BABYLON.serialize()
  16104. ], Camera.prototype, "orthoLeft", void 0);
  16105. __decorate([
  16106. BABYLON.serialize()
  16107. ], Camera.prototype, "orthoRight", void 0);
  16108. __decorate([
  16109. BABYLON.serialize()
  16110. ], Camera.prototype, "orthoBottom", void 0);
  16111. __decorate([
  16112. BABYLON.serialize()
  16113. ], Camera.prototype, "orthoTop", void 0);
  16114. __decorate([
  16115. BABYLON.serialize()
  16116. ], Camera.prototype, "fov", void 0);
  16117. __decorate([
  16118. BABYLON.serialize()
  16119. ], Camera.prototype, "minZ", void 0);
  16120. __decorate([
  16121. BABYLON.serialize()
  16122. ], Camera.prototype, "maxZ", void 0);
  16123. __decorate([
  16124. BABYLON.serialize()
  16125. ], Camera.prototype, "inertia", void 0);
  16126. __decorate([
  16127. BABYLON.serialize()
  16128. ], Camera.prototype, "mode", void 0);
  16129. __decorate([
  16130. BABYLON.serialize()
  16131. ], Camera.prototype, "layerMask", void 0);
  16132. __decorate([
  16133. BABYLON.serialize()
  16134. ], Camera.prototype, "fovMode", void 0);
  16135. __decorate([
  16136. BABYLON.serialize()
  16137. ], Camera.prototype, "cameraRigMode", void 0);
  16138. __decorate([
  16139. BABYLON.serialize()
  16140. ], Camera.prototype, "interaxialDistance", void 0);
  16141. __decorate([
  16142. BABYLON.serialize()
  16143. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16144. BABYLON.Camera = Camera;
  16145. })(BABYLON || (BABYLON = {}));
  16146. //# sourceMappingURL=babylon.camera.js.map
  16147. var BABYLON;
  16148. (function (BABYLON) {
  16149. BABYLON.CameraInputTypes = {};
  16150. var CameraInputsManager = (function () {
  16151. function CameraInputsManager(camera) {
  16152. this.attached = {};
  16153. this.camera = camera;
  16154. this.checkInputs = function () { };
  16155. }
  16156. CameraInputsManager.prototype.add = function (input) {
  16157. var type = input.getSimpleName();
  16158. if (this.attached[type]) {
  16159. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16160. return;
  16161. }
  16162. this.attached[type] = input;
  16163. input.camera = this.camera;
  16164. //for checkInputs, we are dynamically creating a function
  16165. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16166. if (input.checkInputs) {
  16167. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16168. }
  16169. if (this.attachedElement) {
  16170. input.attachControl(this.attachedElement);
  16171. }
  16172. };
  16173. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16174. for (var cam in this.attached) {
  16175. var input = this.attached[cam];
  16176. if (input === inputToRemove) {
  16177. input.detachControl(this.attachedElement);
  16178. delete this.attached[cam];
  16179. this.rebuildInputCheck();
  16180. }
  16181. }
  16182. };
  16183. CameraInputsManager.prototype.removeByType = function (inputType) {
  16184. for (var cam in this.attached) {
  16185. var input = this.attached[cam];
  16186. if (input.getTypeName() === inputType) {
  16187. input.detachControl(this.attachedElement);
  16188. delete this.attached[cam];
  16189. this.rebuildInputCheck();
  16190. }
  16191. }
  16192. };
  16193. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16194. var current = this.checkInputs;
  16195. return function () {
  16196. current();
  16197. fn();
  16198. };
  16199. };
  16200. CameraInputsManager.prototype.attachInput = function (input) {
  16201. input.attachControl(this.attachedElement, this.noPreventDefault);
  16202. };
  16203. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16204. if (this.attachedElement) {
  16205. return;
  16206. }
  16207. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16208. this.attachedElement = element;
  16209. this.noPreventDefault = noPreventDefault;
  16210. for (var cam in this.attached) {
  16211. var input = this.attached[cam];
  16212. this.attached[cam].attachControl(element, noPreventDefault);
  16213. }
  16214. };
  16215. CameraInputsManager.prototype.detachElement = function (element) {
  16216. if (this.attachedElement !== element) {
  16217. return;
  16218. }
  16219. for (var cam in this.attached) {
  16220. var input = this.attached[cam];
  16221. this.attached[cam].detachControl(element);
  16222. }
  16223. this.attachedElement = null;
  16224. };
  16225. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16226. this.checkInputs = function () { };
  16227. for (var cam in this.attached) {
  16228. var input = this.attached[cam];
  16229. if (input.checkInputs) {
  16230. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16231. }
  16232. }
  16233. };
  16234. CameraInputsManager.prototype.clear = function () {
  16235. if (this.attachedElement) {
  16236. this.detachElement(this.attachedElement);
  16237. }
  16238. this.attached = {};
  16239. this.attachedElement = null;
  16240. this.checkInputs = function () { };
  16241. };
  16242. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16243. var inputs = {};
  16244. for (var cam in this.attached) {
  16245. var input = this.attached[cam];
  16246. var res = BABYLON.SerializationHelper.Serialize(input);
  16247. inputs[input.getTypeName()] = res;
  16248. }
  16249. serializedCamera.inputsmgr = inputs;
  16250. };
  16251. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16252. var parsedInputs = parsedCamera.inputsmgr;
  16253. if (parsedInputs) {
  16254. this.clear();
  16255. for (var n in parsedInputs) {
  16256. var construct = BABYLON.CameraInputTypes[n];
  16257. if (construct) {
  16258. var parsedinput = parsedInputs[n];
  16259. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16260. this.add(input);
  16261. }
  16262. }
  16263. }
  16264. else {
  16265. //2016-03-08 this part is for managing backward compatibility
  16266. for (var n in this.attached) {
  16267. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16268. if (construct) {
  16269. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16270. this.remove(this.attached[n]);
  16271. this.add(input);
  16272. }
  16273. }
  16274. }
  16275. };
  16276. return CameraInputsManager;
  16277. }());
  16278. BABYLON.CameraInputsManager = CameraInputsManager;
  16279. })(BABYLON || (BABYLON = {}));
  16280. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16281. var BABYLON;
  16282. (function (BABYLON) {
  16283. var FreeCameraMouseInput = (function () {
  16284. function FreeCameraMouseInput(touchEnabled) {
  16285. if (touchEnabled === void 0) { touchEnabled = true; }
  16286. this.touchEnabled = touchEnabled;
  16287. this.buttons = [0, 1, 2];
  16288. this.angularSensibility = 2000.0;
  16289. }
  16290. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16291. var _this = this;
  16292. var engine = this.camera.getEngine();
  16293. if (!this._pointerInput) {
  16294. this._pointerInput = function (p, s) {
  16295. var evt = p.event;
  16296. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16297. return;
  16298. }
  16299. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16300. return;
  16301. }
  16302. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16303. try {
  16304. evt.srcElement.setPointerCapture(evt.pointerId);
  16305. }
  16306. catch (e) {
  16307. }
  16308. _this.previousPosition = {
  16309. x: evt.clientX,
  16310. y: evt.clientY
  16311. };
  16312. if (!noPreventDefault) {
  16313. evt.preventDefault();
  16314. element.focus();
  16315. }
  16316. }
  16317. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16318. try {
  16319. evt.srcElement.releasePointerCapture(evt.pointerId);
  16320. }
  16321. catch (e) {
  16322. }
  16323. _this.previousPosition = null;
  16324. if (!noPreventDefault) {
  16325. evt.preventDefault();
  16326. }
  16327. }
  16328. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16329. if (!_this.previousPosition || engine.isPointerLock) {
  16330. return;
  16331. }
  16332. var offsetX = evt.clientX - _this.previousPosition.x;
  16333. var offsetY = evt.clientY - _this.previousPosition.y;
  16334. if (_this.camera.getScene().useRightHandedSystem) {
  16335. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16336. }
  16337. else {
  16338. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16339. }
  16340. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16341. _this.previousPosition = {
  16342. x: evt.clientX,
  16343. y: evt.clientY
  16344. };
  16345. if (!noPreventDefault) {
  16346. evt.preventDefault();
  16347. }
  16348. }
  16349. };
  16350. }
  16351. this._onMouseMove = function (evt) {
  16352. if (!engine.isPointerLock) {
  16353. return;
  16354. }
  16355. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16356. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16357. if (_this.camera.getScene().useRightHandedSystem) {
  16358. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16359. }
  16360. else {
  16361. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16362. }
  16363. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16364. _this.previousPosition = null;
  16365. if (!noPreventDefault) {
  16366. evt.preventDefault();
  16367. }
  16368. };
  16369. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16370. element.addEventListener("mousemove", this._onMouseMove, false);
  16371. };
  16372. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16373. if (this._observer && element) {
  16374. this.camera.getScene().onPointerObservable.remove(this._observer);
  16375. element.removeEventListener("mousemove", this._onMouseMove);
  16376. this._observer = null;
  16377. this._onMouseMove = null;
  16378. this.previousPosition = null;
  16379. }
  16380. };
  16381. FreeCameraMouseInput.prototype.getTypeName = function () {
  16382. return "FreeCameraMouseInput";
  16383. };
  16384. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16385. return "mouse";
  16386. };
  16387. return FreeCameraMouseInput;
  16388. }());
  16389. __decorate([
  16390. BABYLON.serialize()
  16391. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16392. __decorate([
  16393. BABYLON.serialize()
  16394. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16395. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16396. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16397. })(BABYLON || (BABYLON = {}));
  16398. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16399. var BABYLON;
  16400. (function (BABYLON) {
  16401. var FreeCameraKeyboardMoveInput = (function () {
  16402. function FreeCameraKeyboardMoveInput() {
  16403. this._keys = [];
  16404. this.keysUp = [38];
  16405. this.keysDown = [40];
  16406. this.keysLeft = [37];
  16407. this.keysRight = [39];
  16408. }
  16409. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16410. var _this = this;
  16411. if (!this._onKeyDown) {
  16412. element.tabIndex = 1;
  16413. this._onKeyDown = function (evt) {
  16414. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16415. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16416. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16417. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16418. var index = _this._keys.indexOf(evt.keyCode);
  16419. if (index === -1) {
  16420. _this._keys.push(evt.keyCode);
  16421. }
  16422. if (!noPreventDefault) {
  16423. evt.preventDefault();
  16424. }
  16425. }
  16426. };
  16427. this._onKeyUp = function (evt) {
  16428. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16429. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16430. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16431. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16432. var index = _this._keys.indexOf(evt.keyCode);
  16433. if (index >= 0) {
  16434. _this._keys.splice(index, 1);
  16435. }
  16436. if (!noPreventDefault) {
  16437. evt.preventDefault();
  16438. }
  16439. }
  16440. };
  16441. element.addEventListener("keydown", this._onKeyDown, false);
  16442. element.addEventListener("keyup", this._onKeyUp, false);
  16443. BABYLON.Tools.RegisterTopRootEvents([
  16444. { name: "blur", handler: this._onLostFocus }
  16445. ]);
  16446. }
  16447. };
  16448. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16449. if (this._onKeyDown) {
  16450. element.removeEventListener("keydown", this._onKeyDown);
  16451. element.removeEventListener("keyup", this._onKeyUp);
  16452. BABYLON.Tools.UnregisterTopRootEvents([
  16453. { name: "blur", handler: this._onLostFocus }
  16454. ]);
  16455. this._keys = [];
  16456. this._onKeyDown = null;
  16457. this._onKeyUp = null;
  16458. }
  16459. };
  16460. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16461. if (this._onKeyDown) {
  16462. var camera = this.camera;
  16463. // Keyboard
  16464. for (var index = 0; index < this._keys.length; index++) {
  16465. var keyCode = this._keys[index];
  16466. var speed = camera._computeLocalCameraSpeed();
  16467. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16468. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16469. }
  16470. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16471. camera._localDirection.copyFromFloats(0, 0, speed);
  16472. }
  16473. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16474. camera._localDirection.copyFromFloats(speed, 0, 0);
  16475. }
  16476. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16477. camera._localDirection.copyFromFloats(0, 0, -speed);
  16478. }
  16479. if (camera.getScene().useRightHandedSystem) {
  16480. camera._localDirection.z *= -1;
  16481. }
  16482. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16483. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16484. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16485. }
  16486. }
  16487. };
  16488. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16489. return "FreeCameraKeyboardMoveInput";
  16490. };
  16491. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16492. this._keys = [];
  16493. };
  16494. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16495. return "keyboard";
  16496. };
  16497. return FreeCameraKeyboardMoveInput;
  16498. }());
  16499. __decorate([
  16500. BABYLON.serialize()
  16501. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16502. __decorate([
  16503. BABYLON.serialize()
  16504. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16505. __decorate([
  16506. BABYLON.serialize()
  16507. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16508. __decorate([
  16509. BABYLON.serialize()
  16510. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16511. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16512. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16513. })(BABYLON || (BABYLON = {}));
  16514. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16515. var BABYLON;
  16516. (function (BABYLON) {
  16517. var FreeCameraTouchInput = (function () {
  16518. function FreeCameraTouchInput() {
  16519. this._offsetX = null;
  16520. this._offsetY = null;
  16521. this._pointerCount = 0;
  16522. this._pointerPressed = [];
  16523. this.touchAngularSensibility = 200000.0;
  16524. this.touchMoveSensibility = 250.0;
  16525. }
  16526. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16527. var _this = this;
  16528. var previousPosition;
  16529. if (this._pointerInput === undefined) {
  16530. this._onLostFocus = function (evt) {
  16531. _this._offsetX = null;
  16532. _this._offsetY = null;
  16533. };
  16534. this._pointerInput = function (p, s) {
  16535. var evt = p.event;
  16536. if (evt.pointerType === "mouse") {
  16537. return;
  16538. }
  16539. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16540. if (!noPreventDefault) {
  16541. evt.preventDefault();
  16542. }
  16543. _this._pointerPressed.push(evt.pointerId);
  16544. if (_this._pointerPressed.length !== 1) {
  16545. return;
  16546. }
  16547. previousPosition = {
  16548. x: evt.clientX,
  16549. y: evt.clientY
  16550. };
  16551. }
  16552. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16553. if (!noPreventDefault) {
  16554. evt.preventDefault();
  16555. }
  16556. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16557. if (index === -1) {
  16558. return;
  16559. }
  16560. _this._pointerPressed.splice(index, 1);
  16561. if (index != 0) {
  16562. return;
  16563. }
  16564. previousPosition = null;
  16565. _this._offsetX = null;
  16566. _this._offsetY = null;
  16567. }
  16568. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16569. if (!noPreventDefault) {
  16570. evt.preventDefault();
  16571. }
  16572. if (!previousPosition) {
  16573. return;
  16574. }
  16575. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16576. if (index != 0) {
  16577. return;
  16578. }
  16579. _this._offsetX = evt.clientX - previousPosition.x;
  16580. _this._offsetY = -(evt.clientY - previousPosition.y);
  16581. }
  16582. };
  16583. }
  16584. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16585. element.addEventListener("blur", this._onLostFocus);
  16586. };
  16587. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16588. if (this._pointerInput && element) {
  16589. this.camera.getScene().onPointerObservable.remove(this._observer);
  16590. this._observer = null;
  16591. element.removeEventListener("blur", this._onLostFocus);
  16592. this._onLostFocus = null;
  16593. this._pointerPressed = [];
  16594. this._offsetX = null;
  16595. this._offsetY = null;
  16596. this._pointerCount = 0;
  16597. }
  16598. };
  16599. FreeCameraTouchInput.prototype.checkInputs = function () {
  16600. if (this._offsetX) {
  16601. var camera = this.camera;
  16602. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16603. if (this._pointerPressed.length > 1) {
  16604. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16605. }
  16606. else {
  16607. var speed = camera._computeLocalCameraSpeed();
  16608. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16609. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16610. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16611. }
  16612. }
  16613. };
  16614. FreeCameraTouchInput.prototype.getTypeName = function () {
  16615. return "FreeCameraTouchInput";
  16616. };
  16617. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16618. return "touch";
  16619. };
  16620. return FreeCameraTouchInput;
  16621. }());
  16622. __decorate([
  16623. BABYLON.serialize()
  16624. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16625. __decorate([
  16626. BABYLON.serialize()
  16627. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16628. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16629. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16630. })(BABYLON || (BABYLON = {}));
  16631. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16632. var BABYLON;
  16633. (function (BABYLON) {
  16634. var FreeCameraDeviceOrientationInput = (function () {
  16635. function FreeCameraDeviceOrientationInput() {
  16636. var _this = this;
  16637. this._screenOrientationAngle = 0;
  16638. this._screenQuaternion = new BABYLON.Quaternion();
  16639. this._alpha = 0;
  16640. this._beta = 0;
  16641. this._gamma = 0;
  16642. this._orientationChanged = function () {
  16643. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16644. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16645. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16646. };
  16647. this._deviceOrientation = function (evt) {
  16648. _this._alpha = evt.alpha;
  16649. _this._beta = evt.beta;
  16650. _this._gamma = evt.gamma;
  16651. };
  16652. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16653. this._orientationChanged();
  16654. }
  16655. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16656. get: function () {
  16657. return this._camera;
  16658. },
  16659. set: function (camera) {
  16660. this._camera = camera;
  16661. if (!this._camera.rotationQuaternion)
  16662. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16663. },
  16664. enumerable: true,
  16665. configurable: true
  16666. });
  16667. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16668. window.addEventListener("orientationchange", this._orientationChanged);
  16669. window.addEventListener("deviceorientation", this._deviceOrientation);
  16670. //In certain cases, the attach control is called AFTER orientation was changed,
  16671. //So this is needed.
  16672. this._orientationChanged();
  16673. };
  16674. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16675. window.removeEventListener("orientationchange", this._orientationChanged);
  16676. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16677. };
  16678. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16679. //if no device orientation provided, don't update the rotation.
  16680. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16681. if (!this._alpha)
  16682. return;
  16683. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16684. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16685. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16686. //Mirror on XY Plane
  16687. this._camera.rotationQuaternion.z *= -1;
  16688. this._camera.rotationQuaternion.w *= -1;
  16689. };
  16690. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16691. return "FreeCameraDeviceOrientationInput";
  16692. };
  16693. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16694. return "deviceOrientation";
  16695. };
  16696. return FreeCameraDeviceOrientationInput;
  16697. }());
  16698. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16699. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16700. })(BABYLON || (BABYLON = {}));
  16701. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16702. var BABYLON;
  16703. (function (BABYLON) {
  16704. var FreeCameraGamepadInput = (function () {
  16705. function FreeCameraGamepadInput() {
  16706. this.gamepadAngularSensibility = 200;
  16707. this.gamepadMoveSensibility = 40;
  16708. }
  16709. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16710. var _this = this;
  16711. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16712. };
  16713. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16714. if (this._gamepads) {
  16715. this._gamepads.dispose();
  16716. }
  16717. this.gamepad = null;
  16718. };
  16719. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16720. if (this.gamepad) {
  16721. var camera = this.camera;
  16722. var LSValues = this.gamepad.leftStick;
  16723. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16724. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16725. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16726. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16727. var RSValues = this.gamepad.rightStick;
  16728. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16729. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16730. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16731. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16732. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  16733. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16734. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  16735. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  16736. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  16737. }
  16738. };
  16739. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16740. // Only the first gamepad can control the camera
  16741. if (gamepad.index === 0) {
  16742. this.gamepad = gamepad;
  16743. }
  16744. };
  16745. FreeCameraGamepadInput.prototype.getTypeName = function () {
  16746. return "FreeCameraGamepadInput";
  16747. };
  16748. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  16749. return "gamepad";
  16750. };
  16751. return FreeCameraGamepadInput;
  16752. }());
  16753. __decorate([
  16754. BABYLON.serialize()
  16755. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  16756. __decorate([
  16757. BABYLON.serialize()
  16758. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  16759. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  16760. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  16761. })(BABYLON || (BABYLON = {}));
  16762. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  16763. var BABYLON;
  16764. (function (BABYLON) {
  16765. var ArcRotateCameraKeyboardMoveInput = (function () {
  16766. function ArcRotateCameraKeyboardMoveInput() {
  16767. this._keys = [];
  16768. this.keysUp = [38];
  16769. this.keysDown = [40];
  16770. this.keysLeft = [37];
  16771. this.keysRight = [39];
  16772. }
  16773. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16774. var _this = this;
  16775. element.tabIndex = 1;
  16776. this._onKeyDown = function (evt) {
  16777. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16778. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16779. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16780. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16781. var index = _this._keys.indexOf(evt.keyCode);
  16782. if (index === -1) {
  16783. _this._keys.push(evt.keyCode);
  16784. }
  16785. if (evt.preventDefault) {
  16786. if (!noPreventDefault) {
  16787. evt.preventDefault();
  16788. }
  16789. }
  16790. }
  16791. };
  16792. this._onKeyUp = function (evt) {
  16793. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16794. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16795. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16796. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16797. var index = _this._keys.indexOf(evt.keyCode);
  16798. if (index >= 0) {
  16799. _this._keys.splice(index, 1);
  16800. }
  16801. if (evt.preventDefault) {
  16802. if (!noPreventDefault) {
  16803. evt.preventDefault();
  16804. }
  16805. }
  16806. }
  16807. };
  16808. this._onLostFocus = function () {
  16809. _this._keys = [];
  16810. };
  16811. element.addEventListener("keydown", this._onKeyDown, false);
  16812. element.addEventListener("keyup", this._onKeyUp, false);
  16813. BABYLON.Tools.RegisterTopRootEvents([
  16814. { name: "blur", handler: this._onLostFocus }
  16815. ]);
  16816. };
  16817. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16818. if (element) {
  16819. element.removeEventListener("keydown", this._onKeyDown);
  16820. element.removeEventListener("keyup", this._onKeyUp);
  16821. }
  16822. BABYLON.Tools.UnregisterTopRootEvents([
  16823. { name: "blur", handler: this._onLostFocus }
  16824. ]);
  16825. this._keys = [];
  16826. this._onKeyDown = null;
  16827. this._onKeyUp = null;
  16828. this._onLostFocus = null;
  16829. };
  16830. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16831. if (this._onKeyDown) {
  16832. var camera = this.camera;
  16833. for (var index = 0; index < this._keys.length; index++) {
  16834. var keyCode = this._keys[index];
  16835. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16836. camera.inertialAlphaOffset -= 0.01;
  16837. }
  16838. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16839. camera.inertialBetaOffset -= 0.01;
  16840. }
  16841. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16842. camera.inertialAlphaOffset += 0.01;
  16843. }
  16844. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16845. camera.inertialBetaOffset += 0.01;
  16846. }
  16847. }
  16848. }
  16849. };
  16850. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16851. return "ArcRotateCameraKeyboardMoveInput";
  16852. };
  16853. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16854. return "keyboard";
  16855. };
  16856. return ArcRotateCameraKeyboardMoveInput;
  16857. }());
  16858. __decorate([
  16859. BABYLON.serialize()
  16860. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16861. __decorate([
  16862. BABYLON.serialize()
  16863. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16864. __decorate([
  16865. BABYLON.serialize()
  16866. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16867. __decorate([
  16868. BABYLON.serialize()
  16869. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16870. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  16871. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  16872. })(BABYLON || (BABYLON = {}));
  16873. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  16874. var BABYLON;
  16875. (function (BABYLON) {
  16876. var ArcRotateCameraMouseWheelInput = (function () {
  16877. function ArcRotateCameraMouseWheelInput() {
  16878. this.wheelPrecision = 3.0;
  16879. }
  16880. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  16881. var _this = this;
  16882. this._wheel = function (p, s) {
  16883. //sanity check - this should be a PointerWheel event.
  16884. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  16885. return;
  16886. var event = p.event;
  16887. var delta = 0;
  16888. if (event.wheelDelta) {
  16889. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  16890. }
  16891. else if (event.detail) {
  16892. delta = -event.detail / _this.wheelPrecision;
  16893. }
  16894. if (delta)
  16895. _this.camera.inertialRadiusOffset += delta;
  16896. if (event.preventDefault) {
  16897. if (!noPreventDefault) {
  16898. event.preventDefault();
  16899. }
  16900. }
  16901. };
  16902. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  16903. };
  16904. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  16905. if (this._observer && element) {
  16906. this.camera.getScene().onPointerObservable.remove(this._observer);
  16907. this._observer = null;
  16908. this._wheel = null;
  16909. }
  16910. };
  16911. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  16912. return "ArcRotateCameraMouseWheelInput";
  16913. };
  16914. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  16915. return "mousewheel";
  16916. };
  16917. return ArcRotateCameraMouseWheelInput;
  16918. }());
  16919. __decorate([
  16920. BABYLON.serialize()
  16921. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  16922. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  16923. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  16924. })(BABYLON || (BABYLON = {}));
  16925. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  16926. var BABYLON;
  16927. (function (BABYLON) {
  16928. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16929. var ArcRotateCameraPointersInput = (function () {
  16930. function ArcRotateCameraPointersInput() {
  16931. this.buttons = [0, 1, 2];
  16932. this.angularSensibilityX = 1000.0;
  16933. this.angularSensibilityY = 1000.0;
  16934. this.pinchPrecision = 6.0;
  16935. this.panningSensibility = 50.0;
  16936. this._isPanClick = false;
  16937. this.pinchInwards = true;
  16938. }
  16939. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  16940. var _this = this;
  16941. var engine = this.camera.getEngine();
  16942. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  16943. var pointA, pointB;
  16944. var previousPinchDistance = 0;
  16945. this._pointerInput = function (p, s) {
  16946. var evt = p.event;
  16947. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16948. return;
  16949. }
  16950. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16951. try {
  16952. evt.srcElement.setPointerCapture(evt.pointerId);
  16953. }
  16954. catch (e) {
  16955. }
  16956. // Manage panning with pan button click
  16957. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  16958. // manage pointers
  16959. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  16960. if (pointA === undefined) {
  16961. pointA = cacheSoloPointer;
  16962. }
  16963. else if (pointB === undefined) {
  16964. pointB = cacheSoloPointer;
  16965. }
  16966. if (!noPreventDefault) {
  16967. evt.preventDefault();
  16968. element.focus();
  16969. }
  16970. }
  16971. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16972. try {
  16973. evt.srcElement.releasePointerCapture(evt.pointerId);
  16974. }
  16975. catch (e) {
  16976. }
  16977. cacheSoloPointer = null;
  16978. previousPinchDistance = 0;
  16979. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  16980. //but emptying completly pointers collection is required to fix a bug on iPhone :
  16981. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  16982. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  16983. pointA = pointB = undefined;
  16984. if (!noPreventDefault) {
  16985. evt.preventDefault();
  16986. }
  16987. }
  16988. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16989. if (!noPreventDefault) {
  16990. evt.preventDefault();
  16991. }
  16992. // One button down
  16993. if (pointA && pointB === undefined) {
  16994. if (_this.panningSensibility !== 0 &&
  16995. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  16996. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  16997. _this.camera
  16998. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  16999. _this.camera
  17000. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17001. }
  17002. else {
  17003. var offsetX = evt.clientX - cacheSoloPointer.x;
  17004. var offsetY = evt.clientY - cacheSoloPointer.y;
  17005. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17006. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17007. }
  17008. cacheSoloPointer.x = evt.clientX;
  17009. cacheSoloPointer.y = evt.clientY;
  17010. }
  17011. else if (pointA && pointB) {
  17012. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17013. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17014. ed.x = evt.clientX;
  17015. ed.y = evt.clientY;
  17016. var direction = _this.pinchInwards ? 1 : -1;
  17017. var distX = pointA.x - pointB.x;
  17018. var distY = pointA.y - pointB.y;
  17019. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17020. if (previousPinchDistance === 0) {
  17021. previousPinchDistance = pinchSquaredDistance;
  17022. return;
  17023. }
  17024. if (pinchSquaredDistance !== previousPinchDistance) {
  17025. _this.camera
  17026. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17027. (_this.pinchPrecision *
  17028. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17029. direction);
  17030. previousPinchDistance = pinchSquaredDistance;
  17031. }
  17032. }
  17033. }
  17034. };
  17035. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17036. this._onContextMenu = function (evt) {
  17037. evt.preventDefault();
  17038. };
  17039. if (!this.camera._useCtrlForPanning) {
  17040. element.addEventListener("contextmenu", this._onContextMenu, false);
  17041. }
  17042. this._onLostFocus = function () {
  17043. //this._keys = [];
  17044. pointA = pointB = undefined;
  17045. previousPinchDistance = 0;
  17046. cacheSoloPointer = null;
  17047. };
  17048. this._onMouseMove = function (evt) {
  17049. if (!engine.isPointerLock) {
  17050. return;
  17051. }
  17052. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17053. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17054. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17055. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17056. if (!noPreventDefault) {
  17057. evt.preventDefault();
  17058. }
  17059. };
  17060. this._onGestureStart = function (e) {
  17061. if (window.MSGesture === undefined) {
  17062. return;
  17063. }
  17064. if (!_this._MSGestureHandler) {
  17065. _this._MSGestureHandler = new MSGesture();
  17066. _this._MSGestureHandler.target = element;
  17067. }
  17068. _this._MSGestureHandler.addPointer(e.pointerId);
  17069. };
  17070. this._onGesture = function (e) {
  17071. _this.camera.radius *= e.scale;
  17072. if (e.preventDefault) {
  17073. if (!noPreventDefault) {
  17074. e.stopPropagation();
  17075. e.preventDefault();
  17076. }
  17077. }
  17078. };
  17079. element.addEventListener("mousemove", this._onMouseMove, false);
  17080. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17081. element.addEventListener("MSGestureChange", this._onGesture, false);
  17082. element.addEventListener("keydown", this._onKeyDown, false);
  17083. element.addEventListener("keyup", this._onKeyUp, false);
  17084. BABYLON.Tools.RegisterTopRootEvents([
  17085. { name: "blur", handler: this._onLostFocus }
  17086. ]);
  17087. };
  17088. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17089. if (element && this._observer) {
  17090. this.camera.getScene().onPointerObservable.remove(this._observer);
  17091. this._observer = null;
  17092. element.removeEventListener("contextmenu", this._onContextMenu);
  17093. element.removeEventListener("mousemove", this._onMouseMove);
  17094. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17095. element.removeEventListener("MSGestureChange", this._onGesture);
  17096. element.removeEventListener("keydown", this._onKeyDown);
  17097. element.removeEventListener("keyup", this._onKeyUp);
  17098. this._isPanClick = false;
  17099. this.pinchInwards = true;
  17100. this._onKeyDown = null;
  17101. this._onKeyUp = null;
  17102. this._onMouseMove = null;
  17103. this._onGestureStart = null;
  17104. this._onGesture = null;
  17105. this._MSGestureHandler = null;
  17106. this._onLostFocus = null;
  17107. this._onContextMenu = null;
  17108. }
  17109. BABYLON.Tools.UnregisterTopRootEvents([
  17110. { name: "blur", handler: this._onLostFocus }
  17111. ]);
  17112. };
  17113. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17114. return "ArcRotateCameraPointersInput";
  17115. };
  17116. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17117. return "pointers";
  17118. };
  17119. return ArcRotateCameraPointersInput;
  17120. }());
  17121. __decorate([
  17122. BABYLON.serialize()
  17123. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17124. __decorate([
  17125. BABYLON.serialize()
  17126. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17127. __decorate([
  17128. BABYLON.serialize()
  17129. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17130. __decorate([
  17131. BABYLON.serialize()
  17132. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17133. __decorate([
  17134. BABYLON.serialize()
  17135. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17136. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17137. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17138. })(BABYLON || (BABYLON = {}));
  17139. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17140. var BABYLON;
  17141. (function (BABYLON) {
  17142. var ArcRotateCameraGamepadInput = (function () {
  17143. function ArcRotateCameraGamepadInput() {
  17144. this.gamepadRotationSensibility = 80;
  17145. this.gamepadMoveSensibility = 40;
  17146. }
  17147. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17148. var _this = this;
  17149. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17150. };
  17151. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17152. if (this._gamepads) {
  17153. this._gamepads.dispose();
  17154. }
  17155. this.gamepad = null;
  17156. };
  17157. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17158. if (this.gamepad) {
  17159. var camera = this.camera;
  17160. var RSValues = this.gamepad.rightStick;
  17161. if (RSValues.x != 0) {
  17162. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17163. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17164. camera.inertialAlphaOffset += normalizedRX;
  17165. }
  17166. }
  17167. if (RSValues.y != 0) {
  17168. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17169. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17170. camera.inertialBetaOffset += normalizedRY;
  17171. }
  17172. }
  17173. var LSValues = this.gamepad.leftStick;
  17174. if (LSValues.y != 0) {
  17175. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17176. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17177. this.camera.inertialRadiusOffset -= normalizedLY;
  17178. }
  17179. }
  17180. }
  17181. };
  17182. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17183. // Only the first gamepad can control the camera
  17184. if (gamepad.index === 0) {
  17185. this.gamepad = gamepad;
  17186. }
  17187. };
  17188. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17189. return "ArcRotateCameraGamepadInput";
  17190. };
  17191. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17192. return "gamepad";
  17193. };
  17194. return ArcRotateCameraGamepadInput;
  17195. }());
  17196. __decorate([
  17197. BABYLON.serialize()
  17198. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17199. __decorate([
  17200. BABYLON.serialize()
  17201. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17202. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17203. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17204. })(BABYLON || (BABYLON = {}));
  17205. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17206. var BABYLON;
  17207. (function (BABYLON) {
  17208. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17209. function ArcRotateCameraVRDeviceOrientationInput() {
  17210. this.alphaCorrection = 1;
  17211. this.betaCorrection = 1;
  17212. this.gammaCorrection = 1;
  17213. this._alpha = 0;
  17214. this._beta = 0;
  17215. this._gamma = 0;
  17216. this._dirty = false;
  17217. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17218. }
  17219. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17220. this.camera.attachControl(element, noPreventDefault);
  17221. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17222. };
  17223. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17224. var camera = this.camera;
  17225. this._alpha = +evt.alpha | 0;
  17226. this._beta = +evt.beta | 0;
  17227. this._gamma = +evt.gamma | 0;
  17228. this._dirty = true;
  17229. };
  17230. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17231. if (this._dirty) {
  17232. this._dirty = false;
  17233. if (this._gamma < 0) {
  17234. this._gamma = 180 + this._gamma;
  17235. }
  17236. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17237. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17238. }
  17239. };
  17240. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17241. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17242. };
  17243. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17244. return "ArcRotateCameraVRDeviceOrientationInput";
  17245. };
  17246. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17247. return "VRDeviceOrientation";
  17248. };
  17249. return ArcRotateCameraVRDeviceOrientationInput;
  17250. }());
  17251. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17252. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17253. })(BABYLON || (BABYLON = {}));
  17254. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17255. /// <reference path="babylon.camera.ts" />
  17256. var BABYLON;
  17257. (function (BABYLON) {
  17258. var TargetCamera = (function (_super) {
  17259. __extends(TargetCamera, _super);
  17260. function TargetCamera(name, position, scene) {
  17261. var _this = _super.call(this, name, position, scene) || this;
  17262. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17263. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17264. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17265. _this.speed = 2.0;
  17266. _this.noRotationConstraint = false;
  17267. _this.lockedTarget = null;
  17268. _this._currentTarget = BABYLON.Vector3.Zero();
  17269. _this._viewMatrix = BABYLON.Matrix.Zero();
  17270. _this._camMatrix = BABYLON.Matrix.Zero();
  17271. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17272. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17273. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17274. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17275. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17276. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17277. _this._tempMatrix = BABYLON.Matrix.Zero();
  17278. return _this;
  17279. }
  17280. TargetCamera.prototype.getFrontPosition = function (distance) {
  17281. var direction = this.getTarget().subtract(this.position);
  17282. direction.normalize();
  17283. direction.scaleInPlace(distance);
  17284. return this.globalPosition.add(direction);
  17285. };
  17286. TargetCamera.prototype._getLockedTargetPosition = function () {
  17287. if (!this.lockedTarget) {
  17288. return null;
  17289. }
  17290. if (this.lockedTarget.absolutePosition) {
  17291. this.lockedTarget.computeWorldMatrix();
  17292. }
  17293. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17294. };
  17295. // Cache
  17296. TargetCamera.prototype._initCache = function () {
  17297. _super.prototype._initCache.call(this);
  17298. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17299. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17300. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17301. };
  17302. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17303. if (!ignoreParentClass) {
  17304. _super.prototype._updateCache.call(this);
  17305. }
  17306. var lockedTargetPosition = this._getLockedTargetPosition();
  17307. if (!lockedTargetPosition) {
  17308. this._cache.lockedTarget = null;
  17309. }
  17310. else {
  17311. if (!this._cache.lockedTarget) {
  17312. this._cache.lockedTarget = lockedTargetPosition.clone();
  17313. }
  17314. else {
  17315. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17316. }
  17317. }
  17318. this._cache.rotation.copyFrom(this.rotation);
  17319. if (this.rotationQuaternion)
  17320. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17321. };
  17322. // Synchronized
  17323. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17324. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17325. return false;
  17326. }
  17327. var lockedTargetPosition = this._getLockedTargetPosition();
  17328. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17329. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17330. };
  17331. // Methods
  17332. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17333. var engine = this.getEngine();
  17334. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17335. };
  17336. // Target
  17337. TargetCamera.prototype.setTarget = function (target) {
  17338. this.upVector.normalize();
  17339. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17340. this._camMatrix.invert();
  17341. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17342. var vDir = target.subtract(this.position);
  17343. if (vDir.x >= 0.0) {
  17344. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17345. }
  17346. else {
  17347. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17348. }
  17349. this.rotation.z = 0;
  17350. if (isNaN(this.rotation.x)) {
  17351. this.rotation.x = 0;
  17352. }
  17353. if (isNaN(this.rotation.y)) {
  17354. this.rotation.y = 0;
  17355. }
  17356. if (isNaN(this.rotation.z)) {
  17357. this.rotation.z = 0;
  17358. }
  17359. if (this.rotationQuaternion) {
  17360. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17361. }
  17362. };
  17363. TargetCamera.prototype.getTarget = function () {
  17364. return this._currentTarget;
  17365. };
  17366. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17367. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17368. };
  17369. TargetCamera.prototype._updatePosition = function () {
  17370. this.position.addInPlace(this.cameraDirection);
  17371. };
  17372. TargetCamera.prototype._checkInputs = function () {
  17373. var needToMove = this._decideIfNeedsToMove();
  17374. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17375. // Move
  17376. if (needToMove) {
  17377. this._updatePosition();
  17378. }
  17379. // Rotate
  17380. if (needToRotate) {
  17381. this.rotation.x += this.cameraRotation.x;
  17382. this.rotation.y += this.cameraRotation.y;
  17383. if (!this.noRotationConstraint) {
  17384. var limit = (Math.PI / 2) * 0.95;
  17385. if (this.rotation.x > limit)
  17386. this.rotation.x = limit;
  17387. if (this.rotation.x < -limit)
  17388. this.rotation.x = -limit;
  17389. }
  17390. }
  17391. // Inertia
  17392. if (needToMove) {
  17393. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17394. this.cameraDirection.x = 0;
  17395. }
  17396. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17397. this.cameraDirection.y = 0;
  17398. }
  17399. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17400. this.cameraDirection.z = 0;
  17401. }
  17402. this.cameraDirection.scaleInPlace(this.inertia);
  17403. }
  17404. if (needToRotate) {
  17405. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17406. this.cameraRotation.x = 0;
  17407. }
  17408. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17409. this.cameraRotation.y = 0;
  17410. }
  17411. this.cameraRotation.scaleInPlace(this.inertia);
  17412. }
  17413. _super.prototype._checkInputs.call(this);
  17414. };
  17415. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17416. if (this.rotationQuaternion) {
  17417. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17418. //update the up vector!
  17419. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17420. }
  17421. else {
  17422. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17423. }
  17424. };
  17425. TargetCamera.prototype._getViewMatrix = function () {
  17426. if (!this.lockedTarget) {
  17427. // Compute
  17428. this._updateCameraRotationMatrix();
  17429. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17430. // Computing target and final matrix
  17431. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17432. }
  17433. else {
  17434. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17435. }
  17436. if (this.getScene().useRightHandedSystem) {
  17437. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17438. }
  17439. else {
  17440. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17441. }
  17442. return this._viewMatrix;
  17443. };
  17444. /**
  17445. * @override
  17446. * Override Camera.createRigCamera
  17447. */
  17448. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17449. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17450. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17451. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17452. if (!this.rotationQuaternion) {
  17453. this.rotationQuaternion = new BABYLON.Quaternion();
  17454. }
  17455. rigCamera._cameraRigParams = {};
  17456. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17457. }
  17458. return rigCamera;
  17459. }
  17460. return null;
  17461. };
  17462. /**
  17463. * @override
  17464. * Override Camera._updateRigCameras
  17465. */
  17466. TargetCamera.prototype._updateRigCameras = function () {
  17467. var camLeft = this._rigCameras[0];
  17468. var camRight = this._rigCameras[1];
  17469. switch (this.cameraRigMode) {
  17470. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17474. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17475. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17476. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17477. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17478. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17479. camLeft.setTarget(this.getTarget());
  17480. camRight.setTarget(this.getTarget());
  17481. break;
  17482. case BABYLON.Camera.RIG_MODE_VR:
  17483. case BABYLON.Camera.RIG_MODE_WEBVR:
  17484. if (camLeft.rotationQuaternion) {
  17485. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17486. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17487. }
  17488. else {
  17489. camLeft.rotation.copyFrom(this.rotation);
  17490. camRight.rotation.copyFrom(this.rotation);
  17491. }
  17492. camLeft.position.copyFrom(this.position);
  17493. camRight.position.copyFrom(this.position);
  17494. break;
  17495. }
  17496. _super.prototype._updateRigCameras.call(this);
  17497. };
  17498. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17499. if (!this._rigCamTransformMatrix) {
  17500. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17501. }
  17502. var target = this.getTarget();
  17503. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17504. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17505. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17506. };
  17507. TargetCamera.prototype.getClassName = function () {
  17508. return "TargetCamera";
  17509. };
  17510. return TargetCamera;
  17511. }(BABYLON.Camera));
  17512. __decorate([
  17513. BABYLON.serializeAsVector3()
  17514. ], TargetCamera.prototype, "rotation", void 0);
  17515. __decorate([
  17516. BABYLON.serialize()
  17517. ], TargetCamera.prototype, "speed", void 0);
  17518. __decorate([
  17519. BABYLON.serializeAsMeshReference("lockedTargetId")
  17520. ], TargetCamera.prototype, "lockedTarget", void 0);
  17521. BABYLON.TargetCamera = TargetCamera;
  17522. })(BABYLON || (BABYLON = {}));
  17523. //# sourceMappingURL=babylon.targetCamera.js.map
  17524. var BABYLON;
  17525. (function (BABYLON) {
  17526. var FreeCamera = (function (_super) {
  17527. __extends(FreeCamera, _super);
  17528. function FreeCamera(name, position, scene) {
  17529. var _this = _super.call(this, name, position, scene) || this;
  17530. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17531. _this.checkCollisions = false;
  17532. _this.applyGravity = false;
  17533. _this._collider = new BABYLON.Collider();
  17534. _this._needMoveForGravity = false;
  17535. _this._oldPosition = BABYLON.Vector3.Zero();
  17536. _this._diffPosition = BABYLON.Vector3.Zero();
  17537. _this._newPosition = BABYLON.Vector3.Zero();
  17538. // Collisions
  17539. _this._collisionMask = -1;
  17540. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17541. if (collidedMesh === void 0) { collidedMesh = null; }
  17542. //TODO move this to the collision coordinator!
  17543. if (_this.getScene().workerCollisions)
  17544. newPosition.multiplyInPlace(_this._collider.radius);
  17545. var updatePosition = function (newPos) {
  17546. _this._newPosition.copyFrom(newPos);
  17547. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17548. var oldPosition = _this.position.clone();
  17549. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17550. _this.position.addInPlace(_this._diffPosition);
  17551. if (_this.onCollide && collidedMesh) {
  17552. _this.onCollide(collidedMesh);
  17553. }
  17554. }
  17555. };
  17556. updatePosition(newPosition);
  17557. };
  17558. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17559. _this.inputs.addKeyboard().addMouse();
  17560. return _this;
  17561. }
  17562. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17563. //-- begin properties for backward compatibility for inputs
  17564. get: function () {
  17565. var mouse = this.inputs.attached["mouse"];
  17566. if (mouse)
  17567. return mouse.angularSensibility;
  17568. },
  17569. set: function (value) {
  17570. var mouse = this.inputs.attached["mouse"];
  17571. if (mouse)
  17572. mouse.angularSensibility = value;
  17573. },
  17574. enumerable: true,
  17575. configurable: true
  17576. });
  17577. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17578. get: function () {
  17579. var keyboard = this.inputs.attached["keyboard"];
  17580. if (keyboard)
  17581. return keyboard.keysUp;
  17582. },
  17583. set: function (value) {
  17584. var keyboard = this.inputs.attached["keyboard"];
  17585. if (keyboard)
  17586. keyboard.keysUp = value;
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17592. get: function () {
  17593. var keyboard = this.inputs.attached["keyboard"];
  17594. if (keyboard)
  17595. return keyboard.keysDown;
  17596. },
  17597. set: function (value) {
  17598. var keyboard = this.inputs.attached["keyboard"];
  17599. if (keyboard)
  17600. keyboard.keysDown = value;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17606. get: function () {
  17607. var keyboard = this.inputs.attached["keyboard"];
  17608. if (keyboard)
  17609. return keyboard.keysLeft;
  17610. },
  17611. set: function (value) {
  17612. var keyboard = this.inputs.attached["keyboard"];
  17613. if (keyboard)
  17614. keyboard.keysLeft = value;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17620. get: function () {
  17621. var keyboard = this.inputs.attached["keyboard"];
  17622. if (keyboard)
  17623. return keyboard.keysRight;
  17624. },
  17625. set: function (value) {
  17626. var keyboard = this.inputs.attached["keyboard"];
  17627. if (keyboard)
  17628. keyboard.keysRight = value;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. // Controls
  17634. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17635. this.inputs.attachElement(element, noPreventDefault);
  17636. };
  17637. FreeCamera.prototype.detachControl = function (element) {
  17638. this.inputs.detachElement(element);
  17639. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17640. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17641. };
  17642. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17643. get: function () {
  17644. return this._collisionMask;
  17645. },
  17646. set: function (mask) {
  17647. this._collisionMask = !isNaN(mask) ? mask : -1;
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17653. var globalPosition;
  17654. if (this.parent) {
  17655. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17656. }
  17657. else {
  17658. globalPosition = this.position;
  17659. }
  17660. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17661. this._collider.radius = this.ellipsoid;
  17662. this._collider.collisionMask = this._collisionMask;
  17663. //no need for clone, as long as gravity is not on.
  17664. var actualVelocity = velocity;
  17665. //add gravity to the velocity to prevent the dual-collision checking
  17666. if (this.applyGravity) {
  17667. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17668. actualVelocity = velocity.add(this.getScene().gravity);
  17669. }
  17670. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17671. };
  17672. FreeCamera.prototype._checkInputs = function () {
  17673. if (!this._localDirection) {
  17674. this._localDirection = BABYLON.Vector3.Zero();
  17675. this._transformedDirection = BABYLON.Vector3.Zero();
  17676. }
  17677. this.inputs.checkInputs();
  17678. _super.prototype._checkInputs.call(this);
  17679. };
  17680. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17681. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17682. };
  17683. FreeCamera.prototype._updatePosition = function () {
  17684. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17685. this._collideWithWorld(this.cameraDirection);
  17686. }
  17687. else {
  17688. this.position.addInPlace(this.cameraDirection);
  17689. }
  17690. };
  17691. FreeCamera.prototype.dispose = function () {
  17692. this.inputs.clear();
  17693. _super.prototype.dispose.call(this);
  17694. };
  17695. FreeCamera.prototype.getClassName = function () {
  17696. return "FreeCamera";
  17697. };
  17698. return FreeCamera;
  17699. }(BABYLON.TargetCamera));
  17700. __decorate([
  17701. BABYLON.serializeAsVector3()
  17702. ], FreeCamera.prototype, "ellipsoid", void 0);
  17703. __decorate([
  17704. BABYLON.serialize()
  17705. ], FreeCamera.prototype, "checkCollisions", void 0);
  17706. __decorate([
  17707. BABYLON.serialize()
  17708. ], FreeCamera.prototype, "applyGravity", void 0);
  17709. BABYLON.FreeCamera = FreeCamera;
  17710. })(BABYLON || (BABYLON = {}));
  17711. //# sourceMappingURL=babylon.freeCamera.js.map
  17712. var BABYLON;
  17713. (function (BABYLON) {
  17714. var FreeCameraInputsManager = (function (_super) {
  17715. __extends(FreeCameraInputsManager, _super);
  17716. function FreeCameraInputsManager(camera) {
  17717. return _super.call(this, camera) || this;
  17718. }
  17719. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17720. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  17721. return this;
  17722. };
  17723. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  17724. if (touchEnabled === void 0) { touchEnabled = true; }
  17725. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  17726. return this;
  17727. };
  17728. FreeCameraInputsManager.prototype.addGamepad = function () {
  17729. this.add(new BABYLON.FreeCameraGamepadInput());
  17730. return this;
  17731. };
  17732. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  17733. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  17734. return this;
  17735. };
  17736. FreeCameraInputsManager.prototype.addTouch = function () {
  17737. this.add(new BABYLON.FreeCameraTouchInput());
  17738. return this;
  17739. };
  17740. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  17741. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  17742. return this;
  17743. };
  17744. return FreeCameraInputsManager;
  17745. }(BABYLON.CameraInputsManager));
  17746. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  17747. })(BABYLON || (BABYLON = {}));
  17748. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  17749. /// <reference path="babylon.targetCamera.ts" />
  17750. var BABYLON;
  17751. (function (BABYLON) {
  17752. var FollowCamera = (function (_super) {
  17753. __extends(FollowCamera, _super);
  17754. function FollowCamera(name, position, scene, lockedTarget) {
  17755. var _this = _super.call(this, name, position, scene) || this;
  17756. _this.radius = 12;
  17757. _this.rotationOffset = 0;
  17758. _this.heightOffset = 4;
  17759. _this.cameraAcceleration = 0.05;
  17760. _this.maxCameraSpeed = 20;
  17761. _this.lockedTarget = lockedTarget;
  17762. return _this;
  17763. }
  17764. FollowCamera.prototype.getRadians = function (degrees) {
  17765. return degrees * Math.PI / 180;
  17766. };
  17767. FollowCamera.prototype.follow = function (cameraTarget) {
  17768. if (!cameraTarget)
  17769. return;
  17770. var yRotation;
  17771. if (cameraTarget.rotationQuaternion) {
  17772. var rotMatrix = new BABYLON.Matrix();
  17773. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  17774. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  17775. }
  17776. else {
  17777. yRotation = cameraTarget.rotation.y;
  17778. }
  17779. var radians = this.getRadians(this.rotationOffset) + yRotation;
  17780. var targetPosition = cameraTarget.getAbsolutePosition();
  17781. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  17782. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  17783. var dx = targetX - this.position.x;
  17784. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  17785. var dz = (targetZ) - this.position.z;
  17786. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  17787. var vy = dy * this.cameraAcceleration;
  17788. var vz = dz * this.cameraAcceleration * 2;
  17789. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  17790. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17791. }
  17792. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  17793. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17794. }
  17795. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  17796. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17797. }
  17798. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  17799. this.setTarget(targetPosition);
  17800. };
  17801. FollowCamera.prototype._checkInputs = function () {
  17802. _super.prototype._checkInputs.call(this);
  17803. this.follow(this.lockedTarget);
  17804. };
  17805. FollowCamera.prototype.getClassName = function () {
  17806. return "FollowCamera";
  17807. };
  17808. return FollowCamera;
  17809. }(BABYLON.TargetCamera));
  17810. __decorate([
  17811. BABYLON.serialize()
  17812. ], FollowCamera.prototype, "radius", void 0);
  17813. __decorate([
  17814. BABYLON.serialize()
  17815. ], FollowCamera.prototype, "rotationOffset", void 0);
  17816. __decorate([
  17817. BABYLON.serialize()
  17818. ], FollowCamera.prototype, "heightOffset", void 0);
  17819. __decorate([
  17820. BABYLON.serialize()
  17821. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  17822. __decorate([
  17823. BABYLON.serialize()
  17824. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  17825. __decorate([
  17826. BABYLON.serializeAsMeshReference("lockedTargetId")
  17827. ], FollowCamera.prototype, "lockedTarget", void 0);
  17828. BABYLON.FollowCamera = FollowCamera;
  17829. var ArcFollowCamera = (function (_super) {
  17830. __extends(ArcFollowCamera, _super);
  17831. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  17832. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17833. _this.alpha = alpha;
  17834. _this.beta = beta;
  17835. _this.radius = radius;
  17836. _this.target = target;
  17837. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  17838. _this.follow();
  17839. return _this;
  17840. }
  17841. ArcFollowCamera.prototype.follow = function () {
  17842. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  17843. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  17844. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  17845. var targetPosition = this.target.getAbsolutePosition();
  17846. this.position = targetPosition.add(this._cartesianCoordinates);
  17847. this.setTarget(targetPosition);
  17848. };
  17849. ArcFollowCamera.prototype._checkInputs = function () {
  17850. _super.prototype._checkInputs.call(this);
  17851. this.follow();
  17852. };
  17853. ArcFollowCamera.prototype.getClassName = function () {
  17854. return "ArcFollowCamera";
  17855. };
  17856. return ArcFollowCamera;
  17857. }(BABYLON.TargetCamera));
  17858. BABYLON.ArcFollowCamera = ArcFollowCamera;
  17859. })(BABYLON || (BABYLON = {}));
  17860. //# sourceMappingURL=babylon.followCamera.js.map
  17861. /// <reference path="babylon.freeCamera.ts" />
  17862. var BABYLON;
  17863. (function (BABYLON) {
  17864. // We're mainly based on the logic defined into the FreeCamera code
  17865. var TouchCamera = (function (_super) {
  17866. __extends(TouchCamera, _super);
  17867. //-- end properties for backward compatibility for inputs
  17868. function TouchCamera(name, position, scene) {
  17869. var _this = _super.call(this, name, position, scene) || this;
  17870. _this.inputs.addTouch();
  17871. _this._setupInputs();
  17872. return _this;
  17873. }
  17874. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  17875. //-- Begin properties for backward compatibility for inputs
  17876. get: function () {
  17877. var touch = this.inputs.attached["touch"];
  17878. if (touch)
  17879. return touch.touchAngularSensibility;
  17880. },
  17881. set: function (value) {
  17882. var touch = this.inputs.attached["touch"];
  17883. if (touch)
  17884. touch.touchAngularSensibility = value;
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  17890. get: function () {
  17891. var touch = this.inputs.attached["touch"];
  17892. if (touch)
  17893. return touch.touchMoveSensibility;
  17894. },
  17895. set: function (value) {
  17896. var touch = this.inputs.attached["touch"];
  17897. if (touch)
  17898. touch.touchMoveSensibility = value;
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. TouchCamera.prototype.getClassName = function () {
  17904. return "TouchCamera";
  17905. };
  17906. TouchCamera.prototype._setupInputs = function () {
  17907. var mouse = this.inputs.attached["mouse"];
  17908. if (mouse) {
  17909. mouse.touchEnabled = false;
  17910. }
  17911. };
  17912. return TouchCamera;
  17913. }(BABYLON.FreeCamera));
  17914. BABYLON.TouchCamera = TouchCamera;
  17915. })(BABYLON || (BABYLON = {}));
  17916. //# sourceMappingURL=babylon.touchCamera.js.map
  17917. /// <reference path="babylon.targetCamera.ts" />
  17918. /// <reference path="..\Tools\babylon.tools.ts" />
  17919. var BABYLON;
  17920. (function (BABYLON) {
  17921. var ArcRotateCamera = (function (_super) {
  17922. __extends(ArcRotateCamera, _super);
  17923. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  17924. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17925. _this.inertialAlphaOffset = 0;
  17926. _this.inertialBetaOffset = 0;
  17927. _this.inertialRadiusOffset = 0;
  17928. _this.lowerAlphaLimit = null;
  17929. _this.upperAlphaLimit = null;
  17930. _this.lowerBetaLimit = 0.01;
  17931. _this.upperBetaLimit = Math.PI;
  17932. _this.lowerRadiusLimit = null;
  17933. _this.upperRadiusLimit = null;
  17934. _this.inertialPanningX = 0;
  17935. _this.inertialPanningY = 0;
  17936. //-- end properties for backward compatibility for inputs
  17937. _this.zoomOnFactor = 1;
  17938. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  17939. _this.allowUpsideDown = true;
  17940. _this._viewMatrix = new BABYLON.Matrix();
  17941. // Panning
  17942. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  17943. _this.checkCollisions = false;
  17944. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  17945. _this._collider = new BABYLON.Collider();
  17946. _this._previousPosition = BABYLON.Vector3.Zero();
  17947. _this._collisionVelocity = BABYLON.Vector3.Zero();
  17948. _this._newPosition = BABYLON.Vector3.Zero();
  17949. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17950. if (collidedMesh === void 0) { collidedMesh = null; }
  17951. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  17952. newPosition.multiplyInPlace(_this._collider.radius);
  17953. }
  17954. if (!collidedMesh) {
  17955. _this._previousPosition.copyFrom(_this.position);
  17956. }
  17957. else {
  17958. _this.setPosition(newPosition);
  17959. if (_this.onCollide) {
  17960. _this.onCollide(collidedMesh);
  17961. }
  17962. }
  17963. // Recompute because of constraints
  17964. var cosa = Math.cos(_this.alpha);
  17965. var sina = Math.sin(_this.alpha);
  17966. var cosb = Math.cos(_this.beta);
  17967. var sinb = Math.sin(_this.beta);
  17968. if (sinb === 0) {
  17969. sinb = 0.0001;
  17970. }
  17971. var target = _this._getTargetPosition();
  17972. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  17973. _this.position.copyFrom(_this._newPosition);
  17974. var up = _this.upVector;
  17975. if (_this.allowUpsideDown && _this.beta < 0) {
  17976. up = up.clone();
  17977. up = up.negate();
  17978. }
  17979. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  17980. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  17981. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  17982. _this._collisionTriggered = false;
  17983. };
  17984. if (!target) {
  17985. _this.target = BABYLON.Vector3.Zero();
  17986. }
  17987. else {
  17988. _this.target = target;
  17989. }
  17990. _this.alpha = alpha;
  17991. _this.beta = beta;
  17992. _this.radius = radius;
  17993. _this.getViewMatrix();
  17994. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  17995. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  17996. return _this;
  17997. }
  17998. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  17999. //-- begin properties for backward compatibility for inputs
  18000. get: function () {
  18001. var pointers = this.inputs.attached["pointers"];
  18002. if (pointers)
  18003. return pointers.angularSensibilityX;
  18004. },
  18005. set: function (value) {
  18006. var pointers = this.inputs.attached["pointers"];
  18007. if (pointers) {
  18008. pointers.angularSensibilityX = value;
  18009. }
  18010. },
  18011. enumerable: true,
  18012. configurable: true
  18013. });
  18014. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18015. get: function () {
  18016. var pointers = this.inputs.attached["pointers"];
  18017. if (pointers)
  18018. return pointers.angularSensibilityY;
  18019. },
  18020. set: function (value) {
  18021. var pointers = this.inputs.attached["pointers"];
  18022. if (pointers) {
  18023. pointers.angularSensibilityY = value;
  18024. }
  18025. },
  18026. enumerable: true,
  18027. configurable: true
  18028. });
  18029. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18030. get: function () {
  18031. var pointers = this.inputs.attached["pointers"];
  18032. if (pointers)
  18033. return pointers.pinchPrecision;
  18034. },
  18035. set: function (value) {
  18036. var pointers = this.inputs.attached["pointers"];
  18037. if (pointers) {
  18038. pointers.pinchPrecision = value;
  18039. }
  18040. },
  18041. enumerable: true,
  18042. configurable: true
  18043. });
  18044. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18045. get: function () {
  18046. var pointers = this.inputs.attached["pointers"];
  18047. if (pointers)
  18048. return pointers.panningSensibility;
  18049. },
  18050. set: function (value) {
  18051. var pointers = this.inputs.attached["pointers"];
  18052. if (pointers) {
  18053. pointers.panningSensibility = value;
  18054. }
  18055. },
  18056. enumerable: true,
  18057. configurable: true
  18058. });
  18059. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18060. get: function () {
  18061. var keyboard = this.inputs.attached["keyboard"];
  18062. if (keyboard)
  18063. return keyboard.keysUp;
  18064. },
  18065. set: function (value) {
  18066. var keyboard = this.inputs.attached["keyboard"];
  18067. if (keyboard)
  18068. keyboard.keysUp = value;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18074. get: function () {
  18075. var keyboard = this.inputs.attached["keyboard"];
  18076. if (keyboard)
  18077. return keyboard.keysDown;
  18078. },
  18079. set: function (value) {
  18080. var keyboard = this.inputs.attached["keyboard"];
  18081. if (keyboard)
  18082. keyboard.keysDown = value;
  18083. },
  18084. enumerable: true,
  18085. configurable: true
  18086. });
  18087. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18088. get: function () {
  18089. var keyboard = this.inputs.attached["keyboard"];
  18090. if (keyboard)
  18091. return keyboard.keysLeft;
  18092. },
  18093. set: function (value) {
  18094. var keyboard = this.inputs.attached["keyboard"];
  18095. if (keyboard)
  18096. keyboard.keysLeft = value;
  18097. },
  18098. enumerable: true,
  18099. configurable: true
  18100. });
  18101. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18102. get: function () {
  18103. var keyboard = this.inputs.attached["keyboard"];
  18104. if (keyboard)
  18105. return keyboard.keysRight;
  18106. },
  18107. set: function (value) {
  18108. var keyboard = this.inputs.attached["keyboard"];
  18109. if (keyboard)
  18110. keyboard.keysRight = value;
  18111. },
  18112. enumerable: true,
  18113. configurable: true
  18114. });
  18115. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18116. get: function () {
  18117. var mousewheel = this.inputs.attached["mousewheel"];
  18118. if (mousewheel)
  18119. return mousewheel.wheelPrecision;
  18120. },
  18121. set: function (value) {
  18122. var mousewheel = this.inputs.attached["mousewheel"];
  18123. if (mousewheel)
  18124. mousewheel.wheelPrecision = value;
  18125. },
  18126. enumerable: true,
  18127. configurable: true
  18128. });
  18129. // Cache
  18130. ArcRotateCamera.prototype._initCache = function () {
  18131. _super.prototype._initCache.call(this);
  18132. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18133. this._cache.alpha = undefined;
  18134. this._cache.beta = undefined;
  18135. this._cache.radius = undefined;
  18136. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18137. };
  18138. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18139. if (!ignoreParentClass) {
  18140. _super.prototype._updateCache.call(this);
  18141. }
  18142. this._cache.target.copyFrom(this._getTargetPosition());
  18143. this._cache.alpha = this.alpha;
  18144. this._cache.beta = this.beta;
  18145. this._cache.radius = this.radius;
  18146. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18147. };
  18148. ArcRotateCamera.prototype._getTargetPosition = function () {
  18149. if (this.target.getAbsolutePosition) {
  18150. var pos = this.target.getAbsolutePosition();
  18151. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18152. }
  18153. return this.target;
  18154. };
  18155. // Synchronized
  18156. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18157. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18158. return false;
  18159. return this._cache.target.equals(this.target)
  18160. && this._cache.alpha === this.alpha
  18161. && this._cache.beta === this.beta
  18162. && this._cache.radius === this.radius
  18163. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18164. };
  18165. // Methods
  18166. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18167. var _this = this;
  18168. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18169. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18170. this._useCtrlForPanning = useCtrlForPanning;
  18171. this._panningMouseButton = panningMouseButton;
  18172. this.inputs.attachElement(element, noPreventDefault);
  18173. this._reset = function () {
  18174. _this.inertialAlphaOffset = 0;
  18175. _this.inertialBetaOffset = 0;
  18176. _this.inertialRadiusOffset = 0;
  18177. };
  18178. };
  18179. ArcRotateCamera.prototype.detachControl = function (element) {
  18180. this.inputs.detachElement(element);
  18181. if (this._reset) {
  18182. this._reset();
  18183. }
  18184. };
  18185. ArcRotateCamera.prototype._checkInputs = function () {
  18186. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18187. if (this._collisionTriggered) {
  18188. return;
  18189. }
  18190. this.inputs.checkInputs();
  18191. // Inertia
  18192. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18193. if (this.getScene().useRightHandedSystem) {
  18194. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18195. }
  18196. else {
  18197. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18198. }
  18199. this.beta += this.inertialBetaOffset;
  18200. this.radius -= this.inertialRadiusOffset;
  18201. this.inertialAlphaOffset *= this.inertia;
  18202. this.inertialBetaOffset *= this.inertia;
  18203. this.inertialRadiusOffset *= this.inertia;
  18204. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18205. this.inertialAlphaOffset = 0;
  18206. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18207. this.inertialBetaOffset = 0;
  18208. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18209. this.inertialRadiusOffset = 0;
  18210. }
  18211. // Panning inertia
  18212. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18213. if (!this._localDirection) {
  18214. this._localDirection = BABYLON.Vector3.Zero();
  18215. this._transformedDirection = BABYLON.Vector3.Zero();
  18216. }
  18217. this.inertialPanningX *= this.inertia;
  18218. this.inertialPanningY *= this.inertia;
  18219. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18220. this.inertialPanningX = 0;
  18221. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18222. this.inertialPanningY = 0;
  18223. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18224. this._localDirection.multiplyInPlace(this.panningAxis);
  18225. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18226. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18227. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18228. if (!this.panningAxis.y) {
  18229. this._transformedDirection.y = 0;
  18230. }
  18231. if (!this.target.getAbsolutePosition) {
  18232. this.target.addInPlace(this._transformedDirection);
  18233. }
  18234. }
  18235. // Limits
  18236. this._checkLimits();
  18237. _super.prototype._checkInputs.call(this);
  18238. };
  18239. ArcRotateCamera.prototype._checkLimits = function () {
  18240. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18241. if (this.allowUpsideDown && this.beta > Math.PI) {
  18242. this.beta = this.beta - (2 * Math.PI);
  18243. }
  18244. }
  18245. else {
  18246. if (this.beta < this.lowerBetaLimit) {
  18247. this.beta = this.lowerBetaLimit;
  18248. }
  18249. }
  18250. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18251. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18252. this.beta = this.beta + (2 * Math.PI);
  18253. }
  18254. }
  18255. else {
  18256. if (this.beta > this.upperBetaLimit) {
  18257. this.beta = this.upperBetaLimit;
  18258. }
  18259. }
  18260. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18261. this.alpha = this.lowerAlphaLimit;
  18262. }
  18263. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18264. this.alpha = this.upperAlphaLimit;
  18265. }
  18266. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18267. this.radius = this.lowerRadiusLimit;
  18268. }
  18269. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18270. this.radius = this.upperRadiusLimit;
  18271. }
  18272. };
  18273. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18274. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18275. this.radius = radiusv3.length();
  18276. // Alpha
  18277. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18278. if (radiusv3.z < 0) {
  18279. this.alpha = 2 * Math.PI - this.alpha;
  18280. }
  18281. // Beta
  18282. this.beta = Math.acos(radiusv3.y / this.radius);
  18283. this._checkLimits();
  18284. };
  18285. ArcRotateCamera.prototype.setPosition = function (position) {
  18286. if (this.position.equals(position)) {
  18287. return;
  18288. }
  18289. this.position.copyFrom(position);
  18290. this.rebuildAnglesAndRadius();
  18291. };
  18292. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18293. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18294. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18295. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18296. return;
  18297. }
  18298. if (toBoundingCenter && target.getBoundingInfo) {
  18299. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  18300. }
  18301. else {
  18302. this._targetBoundingCenter = null;
  18303. }
  18304. this.target = target;
  18305. this.rebuildAnglesAndRadius();
  18306. };
  18307. ArcRotateCamera.prototype._getViewMatrix = function () {
  18308. // Compute
  18309. var cosa = Math.cos(this.alpha);
  18310. var sina = Math.sin(this.alpha);
  18311. var cosb = Math.cos(this.beta);
  18312. var sinb = Math.sin(this.beta);
  18313. if (sinb === 0) {
  18314. sinb = 0.0001;
  18315. }
  18316. var target = this._getTargetPosition();
  18317. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18318. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18319. this._collider.radius = this.collisionRadius;
  18320. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18321. this._collisionTriggered = true;
  18322. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18323. }
  18324. else {
  18325. this.position.copyFrom(this._newPosition);
  18326. var up = this.upVector;
  18327. if (this.allowUpsideDown && this.beta < 0) {
  18328. up = up.clone();
  18329. up = up.negate();
  18330. }
  18331. if (this.getScene().useRightHandedSystem) {
  18332. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18333. }
  18334. else {
  18335. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18336. }
  18337. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18338. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18339. }
  18340. this._currentTarget = target;
  18341. return this._viewMatrix;
  18342. };
  18343. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18344. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18345. meshes = meshes || this.getScene().meshes;
  18346. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18347. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18348. this.radius = distance * this.zoomOnFactor;
  18349. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18350. };
  18351. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18352. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18353. var meshesOrMinMaxVector;
  18354. var distance;
  18355. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18356. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18357. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18358. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18359. }
  18360. else {
  18361. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18362. distance = meshesOrMinMaxVectorAndDistance.distance;
  18363. }
  18364. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18365. if (!doNotUpdateMaxZ) {
  18366. this.maxZ = distance * 2;
  18367. }
  18368. };
  18369. /**
  18370. * @override
  18371. * Override Camera.createRigCamera
  18372. */
  18373. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18374. var alphaShift;
  18375. switch (this.cameraRigMode) {
  18376. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18379. case BABYLON.Camera.RIG_MODE_VR:
  18380. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18381. break;
  18382. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18383. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18384. break;
  18385. }
  18386. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18387. rigCam._cameraRigParams = {};
  18388. return rigCam;
  18389. };
  18390. /**
  18391. * @override
  18392. * Override Camera._updateRigCameras
  18393. */
  18394. ArcRotateCamera.prototype._updateRigCameras = function () {
  18395. var camLeft = this._rigCameras[0];
  18396. var camRight = this._rigCameras[1];
  18397. camLeft.beta = camRight.beta = this.beta;
  18398. camLeft.radius = camRight.radius = this.radius;
  18399. switch (this.cameraRigMode) {
  18400. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18401. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18402. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18403. case BABYLON.Camera.RIG_MODE_VR:
  18404. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18405. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18406. break;
  18407. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18408. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18409. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18410. break;
  18411. }
  18412. _super.prototype._updateRigCameras.call(this);
  18413. };
  18414. ArcRotateCamera.prototype.dispose = function () {
  18415. this.inputs.clear();
  18416. _super.prototype.dispose.call(this);
  18417. };
  18418. ArcRotateCamera.prototype.getClassName = function () {
  18419. return "ArcRotateCamera";
  18420. };
  18421. return ArcRotateCamera;
  18422. }(BABYLON.TargetCamera));
  18423. __decorate([
  18424. BABYLON.serialize()
  18425. ], ArcRotateCamera.prototype, "alpha", void 0);
  18426. __decorate([
  18427. BABYLON.serialize()
  18428. ], ArcRotateCamera.prototype, "beta", void 0);
  18429. __decorate([
  18430. BABYLON.serialize()
  18431. ], ArcRotateCamera.prototype, "radius", void 0);
  18432. __decorate([
  18433. BABYLON.serializeAsVector3()
  18434. ], ArcRotateCamera.prototype, "target", void 0);
  18435. __decorate([
  18436. BABYLON.serialize()
  18437. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18438. __decorate([
  18439. BABYLON.serialize()
  18440. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18441. __decorate([
  18442. BABYLON.serialize()
  18443. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18444. __decorate([
  18445. BABYLON.serialize()
  18446. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18447. __decorate([
  18448. BABYLON.serialize()
  18449. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18450. __decorate([
  18451. BABYLON.serialize()
  18452. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18453. __decorate([
  18454. BABYLON.serialize()
  18455. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18456. __decorate([
  18457. BABYLON.serialize()
  18458. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18459. __decorate([
  18460. BABYLON.serialize()
  18461. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18462. __decorate([
  18463. BABYLON.serialize()
  18464. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18465. __decorate([
  18466. BABYLON.serialize()
  18467. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18468. __decorate([
  18469. BABYLON.serialize()
  18470. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18471. __decorate([
  18472. BABYLON.serialize()
  18473. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18474. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18475. })(BABYLON || (BABYLON = {}));
  18476. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18477. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18478. var BABYLON;
  18479. (function (BABYLON) {
  18480. var ArcRotateCameraInputsManager = (function (_super) {
  18481. __extends(ArcRotateCameraInputsManager, _super);
  18482. function ArcRotateCameraInputsManager(camera) {
  18483. return _super.call(this, camera) || this;
  18484. }
  18485. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18486. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18487. return this;
  18488. };
  18489. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18490. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18491. return this;
  18492. };
  18493. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18494. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18495. return this;
  18496. };
  18497. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18498. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18499. return this;
  18500. };
  18501. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18502. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18503. return this;
  18504. };
  18505. return ArcRotateCameraInputsManager;
  18506. }(BABYLON.CameraInputsManager));
  18507. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18508. })(BABYLON || (BABYLON = {}));
  18509. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18510. var BABYLON;
  18511. (function (BABYLON) {
  18512. var RenderingManager = (function () {
  18513. function RenderingManager(scene) {
  18514. this._renderingGroups = new Array();
  18515. this._autoClearDepthStencil = {};
  18516. this._customOpaqueSortCompareFn = {};
  18517. this._customAlphaTestSortCompareFn = {};
  18518. this._customTransparentSortCompareFn = {};
  18519. this._renderinGroupInfo = null;
  18520. this._scene = scene;
  18521. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18522. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18523. }
  18524. }
  18525. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18526. if (depth === void 0) { depth = true; }
  18527. if (stencil === void 0) { stencil = true; }
  18528. if (this._depthStencilBufferAlreadyCleaned) {
  18529. return;
  18530. }
  18531. this._scene.getEngine().clear(null, false, depth, stencil);
  18532. this._depthStencilBufferAlreadyCleaned = true;
  18533. };
  18534. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18535. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18536. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18537. var info = null;
  18538. if (observable) {
  18539. if (!this._renderinGroupInfo) {
  18540. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18541. }
  18542. info = this._renderinGroupInfo;
  18543. info.scene = this._scene;
  18544. info.camera = this._scene.activeCamera;
  18545. }
  18546. // Dispatch sprites
  18547. if (renderSprites) {
  18548. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18549. var manager = this._scene.spriteManagers[index];
  18550. this.dispatchSprites(manager);
  18551. }
  18552. }
  18553. // Render
  18554. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18555. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18556. var renderingGroup = this._renderingGroups[index];
  18557. if (!renderingGroup && !observable)
  18558. continue;
  18559. this._currentIndex = index;
  18560. var renderingGroupMask = 0;
  18561. // Fire PRECLEAR stage
  18562. if (observable) {
  18563. renderingGroupMask = Math.pow(2, index);
  18564. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18565. info.renderingGroupId = index;
  18566. observable.notifyObservers(info, renderingGroupMask);
  18567. }
  18568. // Clear depth/stencil if needed
  18569. var autoClear = this._autoClearDepthStencil[index];
  18570. if (autoClear && autoClear.autoClear) {
  18571. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18572. }
  18573. if (observable) {
  18574. // Fire PREOPAQUE stage
  18575. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18576. observable.notifyObservers(info, renderingGroupMask);
  18577. // Fire PRETRANSPARENT stage
  18578. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18579. observable.notifyObservers(info, renderingGroupMask);
  18580. }
  18581. if (renderingGroup)
  18582. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18583. // Fire POSTTRANSPARENT stage
  18584. if (observable) {
  18585. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18586. observable.notifyObservers(info, renderingGroupMask);
  18587. }
  18588. }
  18589. };
  18590. RenderingManager.prototype.reset = function () {
  18591. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18592. var renderingGroup = this._renderingGroups[index];
  18593. if (renderingGroup) {
  18594. renderingGroup.prepare();
  18595. }
  18596. }
  18597. };
  18598. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18599. if (!this._renderingGroups[renderingGroupId]) {
  18600. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18601. }
  18602. };
  18603. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18604. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18605. this._prepareRenderingGroup(renderingGroupId);
  18606. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18607. };
  18608. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18609. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18610. this._prepareRenderingGroup(renderingGroupId);
  18611. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18612. };
  18613. RenderingManager.prototype.dispatch = function (subMesh) {
  18614. var mesh = subMesh.getMesh();
  18615. var renderingGroupId = mesh.renderingGroupId || 0;
  18616. this._prepareRenderingGroup(renderingGroupId);
  18617. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18618. };
  18619. /**
  18620. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18621. * This allowed control for front to back rendering or reversly depending of the special needs.
  18622. *
  18623. * @param renderingGroupId The rendering group id corresponding to its index
  18624. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18625. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18626. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18627. */
  18628. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18629. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18630. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18631. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18632. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18633. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18634. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18635. if (this._renderingGroups[renderingGroupId]) {
  18636. var group = this._renderingGroups[renderingGroupId];
  18637. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18638. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18639. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18640. }
  18641. };
  18642. /**
  18643. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18644. *
  18645. * @param renderingGroupId The rendering group id corresponding to its index
  18646. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18647. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18648. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18649. */
  18650. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18651. if (depth === void 0) { depth = true; }
  18652. if (stencil === void 0) { stencil = true; }
  18653. this._autoClearDepthStencil[renderingGroupId] = {
  18654. autoClear: autoClearDepthStencil,
  18655. depth: depth,
  18656. stencil: stencil
  18657. };
  18658. };
  18659. return RenderingManager;
  18660. }());
  18661. /**
  18662. * The max id used for rendering groups (not included)
  18663. */
  18664. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18665. /**
  18666. * The min id used for rendering groups (included)
  18667. */
  18668. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18669. BABYLON.RenderingManager = RenderingManager;
  18670. })(BABYLON || (BABYLON = {}));
  18671. //# sourceMappingURL=babylon.renderingManager.js.map
  18672. var BABYLON;
  18673. (function (BABYLON) {
  18674. var RenderingGroup = (function () {
  18675. /**
  18676. * Creates a new rendering group.
  18677. * @param index The rendering group index
  18678. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18679. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18680. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18681. */
  18682. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18683. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18684. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18685. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18686. this.index = index;
  18687. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18688. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18689. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18690. this._particleSystems = new BABYLON.SmartArray(256);
  18691. this._spriteManagers = new BABYLON.SmartArray(256);
  18692. this._scene = scene;
  18693. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18694. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18695. this.transparentSortCompareFn = transparentSortCompareFn;
  18696. }
  18697. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18698. /**
  18699. * Set the opaque sort comparison function.
  18700. * If null the sub meshes will be render in the order they were created
  18701. */
  18702. set: function (value) {
  18703. this._opaqueSortCompareFn = value;
  18704. if (value) {
  18705. this._renderOpaque = this.renderOpaqueSorted;
  18706. }
  18707. else {
  18708. this._renderOpaque = RenderingGroup.renderUnsorted;
  18709. }
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18715. /**
  18716. * Set the alpha test sort comparison function.
  18717. * If null the sub meshes will be render in the order they were created
  18718. */
  18719. set: function (value) {
  18720. this._alphaTestSortCompareFn = value;
  18721. if (value) {
  18722. this._renderAlphaTest = this.renderAlphaTestSorted;
  18723. }
  18724. else {
  18725. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18726. }
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18732. /**
  18733. * Set the transparent sort comparison function.
  18734. * If null the sub meshes will be render in the order they were created
  18735. */
  18736. set: function (value) {
  18737. if (value) {
  18738. this._transparentSortCompareFn = value;
  18739. }
  18740. else {
  18741. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18742. }
  18743. this._renderTransparent = this.renderTransparentSorted;
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. /**
  18749. * Render all the sub meshes contained in the group.
  18750. * @param customRenderFunction Used to override the default render behaviour of the group.
  18751. * @returns true if rendered some submeshes.
  18752. */
  18753. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18754. if (customRenderFunction) {
  18755. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  18756. return;
  18757. }
  18758. var engine = this._scene.getEngine();
  18759. // Opaque
  18760. if (this._opaqueSubMeshes.length !== 0) {
  18761. this._renderOpaque(this._opaqueSubMeshes);
  18762. }
  18763. // Alpha test
  18764. if (this._alphaTestSubMeshes.length !== 0) {
  18765. engine.setAlphaTesting(true);
  18766. this._renderAlphaTest(this._alphaTestSubMeshes);
  18767. engine.setAlphaTesting(false);
  18768. }
  18769. // Sprites
  18770. if (renderSprites) {
  18771. this._renderSprites();
  18772. }
  18773. // Particles
  18774. if (renderParticles) {
  18775. this._renderParticles(activeMeshes);
  18776. }
  18777. if (this.onBeforeTransparentRendering) {
  18778. this.onBeforeTransparentRendering();
  18779. }
  18780. // Transparent
  18781. if (this._transparentSubMeshes.length !== 0) {
  18782. this._renderTransparent(this._transparentSubMeshes);
  18783. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18784. }
  18785. };
  18786. /**
  18787. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18788. * @param subMeshes The submeshes to render
  18789. */
  18790. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18791. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18792. };
  18793. /**
  18794. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18795. * @param subMeshes The submeshes to render
  18796. */
  18797. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18798. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18799. };
  18800. /**
  18801. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18802. * @param subMeshes The submeshes to render
  18803. */
  18804. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18805. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  18806. };
  18807. /**
  18808. * Renders the submeshes in a specified order.
  18809. * @param subMeshes The submeshes to sort before render
  18810. * @param sortCompareFn The comparison function use to sort
  18811. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18812. * @param transparent Specifies to activate blending if true
  18813. */
  18814. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  18815. var subIndex = 0;
  18816. var subMesh;
  18817. for (; subIndex < subMeshes.length; subIndex++) {
  18818. subMesh = subMeshes.data[subIndex];
  18819. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18820. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18821. }
  18822. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18823. sortedArray.sort(sortCompareFn);
  18824. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18825. subMesh = sortedArray[subIndex];
  18826. subMesh.render(transparent);
  18827. }
  18828. };
  18829. /**
  18830. * Renders the submeshes in the order they were dispatched (no sort applied).
  18831. * @param subMeshes The submeshes to render
  18832. */
  18833. RenderingGroup.renderUnsorted = function (subMeshes) {
  18834. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18835. var submesh = subMeshes.data[subIndex];
  18836. submesh.render(false);
  18837. }
  18838. };
  18839. /**
  18840. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18841. * are rendered back to front if in the same alpha index.
  18842. *
  18843. * @param a The first submesh
  18844. * @param b The second submesh
  18845. * @returns The result of the comparison
  18846. */
  18847. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18848. // Alpha index first
  18849. if (a._alphaIndex > b._alphaIndex) {
  18850. return 1;
  18851. }
  18852. if (a._alphaIndex < b._alphaIndex) {
  18853. return -1;
  18854. }
  18855. // Then distance to camera
  18856. return RenderingGroup.backToFrontSortCompare(a, b);
  18857. };
  18858. /**
  18859. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18860. * are rendered back to front.
  18861. *
  18862. * @param a The first submesh
  18863. * @param b The second submesh
  18864. * @returns The result of the comparison
  18865. */
  18866. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18867. // Then distance to camera
  18868. if (a._distanceToCamera < b._distanceToCamera) {
  18869. return 1;
  18870. }
  18871. if (a._distanceToCamera > b._distanceToCamera) {
  18872. return -1;
  18873. }
  18874. return 0;
  18875. };
  18876. /**
  18877. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18878. * are rendered front to back (prevent overdraw).
  18879. *
  18880. * @param a The first submesh
  18881. * @param b The second submesh
  18882. * @returns The result of the comparison
  18883. */
  18884. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18885. // Then distance to camera
  18886. if (a._distanceToCamera < b._distanceToCamera) {
  18887. return -1;
  18888. }
  18889. if (a._distanceToCamera > b._distanceToCamera) {
  18890. return 1;
  18891. }
  18892. return 0;
  18893. };
  18894. /**
  18895. * Resets the different lists of submeshes to prepare a new frame.
  18896. */
  18897. RenderingGroup.prototype.prepare = function () {
  18898. this._opaqueSubMeshes.reset();
  18899. this._transparentSubMeshes.reset();
  18900. this._alphaTestSubMeshes.reset();
  18901. this._particleSystems.reset();
  18902. this._spriteManagers.reset();
  18903. };
  18904. /**
  18905. * Inserts the submesh in its correct queue depending on its material.
  18906. * @param subMesh The submesh to dispatch
  18907. */
  18908. RenderingGroup.prototype.dispatch = function (subMesh) {
  18909. var material = subMesh.getMaterial();
  18910. var mesh = subMesh.getMesh();
  18911. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  18912. this._transparentSubMeshes.push(subMesh);
  18913. }
  18914. else if (material.needAlphaTesting()) {
  18915. this._alphaTestSubMeshes.push(subMesh);
  18916. }
  18917. else {
  18918. this._opaqueSubMeshes.push(subMesh); // Opaque
  18919. }
  18920. };
  18921. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18922. this._spriteManagers.push(spriteManager);
  18923. };
  18924. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18925. this._particleSystems.push(particleSystem);
  18926. };
  18927. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18928. if (this._particleSystems.length === 0) {
  18929. return;
  18930. }
  18931. // Particles
  18932. var activeCamera = this._scene.activeCamera;
  18933. this._scene._particlesDuration.beginMonitoring();
  18934. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18935. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18936. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18937. continue;
  18938. }
  18939. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  18940. this._scene._activeParticles.addCount(particleSystem.render(), false);
  18941. }
  18942. }
  18943. this._scene._particlesDuration.endMonitoring(false);
  18944. };
  18945. RenderingGroup.prototype._renderSprites = function () {
  18946. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  18947. return;
  18948. }
  18949. // Sprites
  18950. var activeCamera = this._scene.activeCamera;
  18951. this._scene._spritesDuration.beginMonitoring();
  18952. for (var id = 0; id < this._spriteManagers.length; id++) {
  18953. var spriteManager = this._spriteManagers.data[id];
  18954. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  18955. spriteManager.render();
  18956. }
  18957. }
  18958. this._scene._spritesDuration.endMonitoring(false);
  18959. };
  18960. return RenderingGroup;
  18961. }());
  18962. BABYLON.RenderingGroup = RenderingGroup;
  18963. })(BABYLON || (BABYLON = {}));
  18964. //# sourceMappingURL=babylon.renderingGroup.js.map
  18965. var BABYLON;
  18966. (function (BABYLON) {
  18967. var PointerEventTypes = (function () {
  18968. function PointerEventTypes() {
  18969. }
  18970. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  18971. get: function () {
  18972. return PointerEventTypes._POINTERDOWN;
  18973. },
  18974. enumerable: true,
  18975. configurable: true
  18976. });
  18977. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  18978. get: function () {
  18979. return PointerEventTypes._POINTERUP;
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  18985. get: function () {
  18986. return PointerEventTypes._POINTERMOVE;
  18987. },
  18988. enumerable: true,
  18989. configurable: true
  18990. });
  18991. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  18992. get: function () {
  18993. return PointerEventTypes._POINTERWHEEL;
  18994. },
  18995. enumerable: true,
  18996. configurable: true
  18997. });
  18998. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  18999. get: function () {
  19000. return PointerEventTypes._POINTERPICK;
  19001. },
  19002. enumerable: true,
  19003. configurable: true
  19004. });
  19005. return PointerEventTypes;
  19006. }());
  19007. PointerEventTypes._POINTERDOWN = 0x01;
  19008. PointerEventTypes._POINTERUP = 0x02;
  19009. PointerEventTypes._POINTERMOVE = 0x04;
  19010. PointerEventTypes._POINTERWHEEL = 0x08;
  19011. PointerEventTypes._POINTERPICK = 0x10;
  19012. BABYLON.PointerEventTypes = PointerEventTypes;
  19013. var PointerInfoBase = (function () {
  19014. function PointerInfoBase(type, event) {
  19015. this.type = type;
  19016. this.event = event;
  19017. }
  19018. return PointerInfoBase;
  19019. }());
  19020. BABYLON.PointerInfoBase = PointerInfoBase;
  19021. /**
  19022. * This class is used to store pointer related info for the onPrePointerObservable event.
  19023. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19024. */
  19025. var PointerInfoPre = (function (_super) {
  19026. __extends(PointerInfoPre, _super);
  19027. function PointerInfoPre(type, event, localX, localY) {
  19028. var _this = _super.call(this, type, event) || this;
  19029. _this.skipOnPointerObservable = false;
  19030. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19031. return _this;
  19032. }
  19033. return PointerInfoPre;
  19034. }(PointerInfoBase));
  19035. BABYLON.PointerInfoPre = PointerInfoPre;
  19036. /**
  19037. * This type contains all the data related to a pointer event in Babylon.js.
  19038. * 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.
  19039. */
  19040. var PointerInfo = (function (_super) {
  19041. __extends(PointerInfo, _super);
  19042. function PointerInfo(type, event, pickInfo) {
  19043. var _this = _super.call(this, type, event) || this;
  19044. _this.pickInfo = pickInfo;
  19045. return _this;
  19046. }
  19047. return PointerInfo;
  19048. }(PointerInfoBase));
  19049. BABYLON.PointerInfo = PointerInfo;
  19050. /**
  19051. * This class is used by the onRenderingGroupObservable
  19052. */
  19053. var RenderingGroupInfo = (function () {
  19054. function RenderingGroupInfo() {
  19055. }
  19056. return RenderingGroupInfo;
  19057. }());
  19058. /**
  19059. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19060. * This stage will be fired no matter what
  19061. */
  19062. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19063. /**
  19064. * Called before opaque object are rendered.
  19065. * This stage will be fired only if there's 3D Opaque content to render
  19066. */
  19067. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19068. /**
  19069. * Called after the opaque objects are rendered and before the transparent ones
  19070. * This stage will be fired only if there's 3D transparent content to render
  19071. */
  19072. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19073. /**
  19074. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19075. * This stage will be fired no matter what
  19076. */
  19077. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19078. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19079. /**
  19080. * Represents a scene to be rendered by the engine.
  19081. * @see http://doc.babylonjs.com/page.php?p=21911
  19082. */
  19083. var Scene = (function () {
  19084. /**
  19085. * @constructor
  19086. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19087. */
  19088. function Scene(engine) {
  19089. // Members
  19090. this.autoClear = true;
  19091. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19092. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19093. this.forceWireframe = false;
  19094. this.forcePointsCloud = false;
  19095. this.forceShowBoundingBoxes = false;
  19096. this.animationsEnabled = true;
  19097. this.constantlyUpdateMeshUnderPointer = false;
  19098. this.useRightHandedSystem = false;
  19099. this.hoverCursor = "pointer";
  19100. // Metadata
  19101. this.metadata = null;
  19102. // Events
  19103. /**
  19104. * An event triggered when the scene is disposed.
  19105. * @type {BABYLON.Observable}
  19106. */
  19107. this.onDisposeObservable = new BABYLON.Observable();
  19108. /**
  19109. * An event triggered before rendering the scene
  19110. * @type {BABYLON.Observable}
  19111. */
  19112. this.onBeforeRenderObservable = new BABYLON.Observable();
  19113. /**
  19114. * An event triggered after rendering the scene
  19115. * @type {BABYLON.Observable}
  19116. */
  19117. this.onAfterRenderObservable = new BABYLON.Observable();
  19118. /**
  19119. * An event triggered when the scene is ready
  19120. * @type {BABYLON.Observable}
  19121. */
  19122. this.onReadyObservable = new BABYLON.Observable();
  19123. /**
  19124. * An event triggered before rendering a camera
  19125. * @type {BABYLON.Observable}
  19126. */
  19127. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19128. /**
  19129. * An event triggered after rendering a camera
  19130. * @type {BABYLON.Observable}
  19131. */
  19132. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19133. /**
  19134. * An event triggered when a camera is created
  19135. * @type {BABYLON.Observable}
  19136. */
  19137. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19138. /**
  19139. * An event triggered when a camera is removed
  19140. * @type {BABYLON.Observable}
  19141. */
  19142. this.onCameraRemovedObservable = new BABYLON.Observable();
  19143. /**
  19144. * An event triggered when a light is created
  19145. * @type {BABYLON.Observable}
  19146. */
  19147. this.onNewLightAddedObservable = new BABYLON.Observable();
  19148. /**
  19149. * An event triggered when a light is removed
  19150. * @type {BABYLON.Observable}
  19151. */
  19152. this.onLightRemovedObservable = new BABYLON.Observable();
  19153. /**
  19154. * An event triggered when a geometry is created
  19155. * @type {BABYLON.Observable}
  19156. */
  19157. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19158. /**
  19159. * An event triggered when a geometry is removed
  19160. * @type {BABYLON.Observable}
  19161. */
  19162. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19163. /**
  19164. * An event triggered when a mesh is created
  19165. * @type {BABYLON.Observable}
  19166. */
  19167. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19168. /**
  19169. * An event triggered when a mesh is removed
  19170. * @type {BABYLON.Observable}
  19171. */
  19172. this.onMeshRemovedObservable = new BABYLON.Observable();
  19173. /**
  19174. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19175. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19176. * 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)
  19177. */
  19178. this.onRenderingGroupObservable = new BABYLON.Observable();
  19179. // Animations
  19180. this.animations = [];
  19181. /**
  19182. * 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).
  19183. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19184. */
  19185. this.onPrePointerObservable = new BABYLON.Observable();
  19186. /**
  19187. * Observable event triggered each time an input event is received from the rendering canvas
  19188. */
  19189. this.onPointerObservable = new BABYLON.Observable();
  19190. 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
  19191. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19192. this._startingPointerTime = 0;
  19193. // Fog
  19194. /**
  19195. * is fog enabled on this scene.
  19196. * @type {boolean}
  19197. */
  19198. this.fogEnabled = true;
  19199. this.fogMode = Scene.FOGMODE_NONE;
  19200. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19201. this.fogDensity = 0.1;
  19202. this.fogStart = 0;
  19203. this.fogEnd = 1000.0;
  19204. // Lights
  19205. /**
  19206. * is shadow enabled on this scene.
  19207. * @type {boolean}
  19208. */
  19209. this.shadowsEnabled = true;
  19210. /**
  19211. * is light enabled on this scene.
  19212. * @type {boolean}
  19213. */
  19214. this.lightsEnabled = true;
  19215. /**
  19216. * All of the lights added to this scene.
  19217. * @see BABYLON.Light
  19218. * @type {BABYLON.Light[]}
  19219. */
  19220. this.lights = new Array();
  19221. // Cameras
  19222. /**
  19223. * All of the cameras added to this scene.
  19224. * @see BABYLON.Camera
  19225. * @type {BABYLON.Camera[]}
  19226. */
  19227. this.cameras = new Array();
  19228. this.activeCameras = new Array();
  19229. // Meshes
  19230. /**
  19231. * All of the (abstract) meshes added to this scene.
  19232. * @see BABYLON.AbstractMesh
  19233. * @type {BABYLON.AbstractMesh[]}
  19234. */
  19235. this.meshes = new Array();
  19236. // Geometries
  19237. this._geometries = new Array();
  19238. this.materials = new Array();
  19239. this.multiMaterials = new Array();
  19240. // Textures
  19241. this.texturesEnabled = true;
  19242. this.textures = new Array();
  19243. // Particles
  19244. this.particlesEnabled = true;
  19245. this.particleSystems = new Array();
  19246. // Sprites
  19247. this.spritesEnabled = true;
  19248. this.spriteManagers = new Array();
  19249. // Layers
  19250. this.layers = new Array();
  19251. this.highlightLayers = new Array();
  19252. // Skeletons
  19253. this.skeletonsEnabled = true;
  19254. this.skeletons = new Array();
  19255. // Lens flares
  19256. this.lensFlaresEnabled = true;
  19257. this.lensFlareSystems = new Array();
  19258. // Collisions
  19259. this.collisionsEnabled = true;
  19260. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19261. // Postprocesses
  19262. this.postProcessesEnabled = true;
  19263. // Customs render targets
  19264. this.renderTargetsEnabled = true;
  19265. this.dumpNextRenderTargets = false;
  19266. this.customRenderTargets = new Array();
  19267. // Imported meshes
  19268. this.importedMeshesFiles = new Array();
  19269. // Probes
  19270. this.probesEnabled = true;
  19271. this.reflectionProbes = new Array();
  19272. this._actionManagers = new Array();
  19273. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19274. // Procedural textures
  19275. this.proceduralTexturesEnabled = true;
  19276. this._proceduralTextures = new Array();
  19277. this.soundTracks = new Array();
  19278. this._audioEnabled = true;
  19279. this._headphone = false;
  19280. // Performance counters
  19281. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19282. this._totalLightsCounter = new BABYLON.PerfCounter();
  19283. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19284. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19285. this._totalVertices = new BABYLON.PerfCounter();
  19286. this._activeIndices = new BABYLON.PerfCounter();
  19287. this._activeParticles = new BABYLON.PerfCounter();
  19288. this._lastFrameDuration = new BABYLON.PerfCounter();
  19289. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19290. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19291. this._particlesDuration = new BABYLON.PerfCounter();
  19292. this._renderDuration = new BABYLON.PerfCounter();
  19293. this._spritesDuration = new BABYLON.PerfCounter();
  19294. this._activeBones = new BABYLON.PerfCounter();
  19295. this._animationTime = 0;
  19296. this.animationTimeScale = 1;
  19297. this._renderId = 0;
  19298. this._executeWhenReadyTimeoutId = -1;
  19299. this._intermediateRendering = false;
  19300. this._toBeDisposed = new BABYLON.SmartArray(256);
  19301. this._pendingData = []; //ANY
  19302. this._activeMeshes = new BABYLON.SmartArray(256);
  19303. this._processedMaterials = new BABYLON.SmartArray(256);
  19304. this._renderTargets = new BABYLON.SmartArray(256);
  19305. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19306. this._activeSkeletons = new BABYLON.SmartArray(32);
  19307. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19308. this._activeAnimatables = new Array();
  19309. this._transformMatrix = BABYLON.Matrix.Zero();
  19310. this._edgesRenderers = new BABYLON.SmartArray(16);
  19311. this._uniqueIdCounter = 0;
  19312. this._engine = engine;
  19313. engine.scenes.push(this);
  19314. this._externalData = new BABYLON.StringDictionary();
  19315. this._uid = null;
  19316. this._renderingManager = new BABYLON.RenderingManager(this);
  19317. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19318. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19319. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19320. if (BABYLON.OutlineRenderer) {
  19321. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19322. }
  19323. this.attachControl();
  19324. if (BABYLON.SoundTrack) {
  19325. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19326. }
  19327. //simplification queue
  19328. if (BABYLON.SimplificationQueue) {
  19329. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19330. }
  19331. //collision coordinator initialization. For now legacy per default.
  19332. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19333. }
  19334. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19335. get: function () {
  19336. return Scene._FOGMODE_NONE;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19342. get: function () {
  19343. return Scene._FOGMODE_EXP;
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19349. get: function () {
  19350. return Scene._FOGMODE_EXP2;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19356. get: function () {
  19357. return Scene._FOGMODE_LINEAR;
  19358. },
  19359. enumerable: true,
  19360. configurable: true
  19361. });
  19362. Object.defineProperty(Scene.prototype, "onDispose", {
  19363. set: function (callback) {
  19364. if (this._onDisposeObserver) {
  19365. this.onDisposeObservable.remove(this._onDisposeObserver);
  19366. }
  19367. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19368. },
  19369. enumerable: true,
  19370. configurable: true
  19371. });
  19372. Object.defineProperty(Scene.prototype, "beforeRender", {
  19373. set: function (callback) {
  19374. if (this._onBeforeRenderObserver) {
  19375. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19376. }
  19377. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19378. },
  19379. enumerable: true,
  19380. configurable: true
  19381. });
  19382. Object.defineProperty(Scene.prototype, "afterRender", {
  19383. set: function (callback) {
  19384. if (this._onAfterRenderObserver) {
  19385. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19386. }
  19387. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19393. set: function (callback) {
  19394. if (this._onBeforeCameraRenderObserver) {
  19395. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19396. }
  19397. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19398. },
  19399. enumerable: true,
  19400. configurable: true
  19401. });
  19402. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19403. set: function (callback) {
  19404. if (this._onAfterCameraRenderObserver) {
  19405. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19406. }
  19407. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19413. get: function () {
  19414. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19420. get: function () {
  19421. if (!this._defaultMaterial) {
  19422. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19423. }
  19424. return this._defaultMaterial;
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19430. get: function () {
  19431. return this._frustumPlanes;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Object.defineProperty(Scene.prototype, "debugLayer", {
  19437. // Properties
  19438. get: function () {
  19439. if (!this._debugLayer) {
  19440. this._debugLayer = new BABYLON.DebugLayer(this);
  19441. }
  19442. return this._debugLayer;
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19448. get: function () {
  19449. return this._workerCollisions;
  19450. },
  19451. set: function (enabled) {
  19452. enabled = (enabled && !!Worker);
  19453. this._workerCollisions = enabled;
  19454. if (this.collisionCoordinator) {
  19455. this.collisionCoordinator.destroy();
  19456. }
  19457. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19458. this.collisionCoordinator.init(this);
  19459. },
  19460. enumerable: true,
  19461. configurable: true
  19462. });
  19463. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19464. get: function () {
  19465. return this._selectionOctree;
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19471. /**
  19472. * The mesh that is currently under the pointer.
  19473. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19474. */
  19475. get: function () {
  19476. return this._pointerOverMesh;
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(Scene.prototype, "pointerX", {
  19482. /**
  19483. * Current on-screen X position of the pointer
  19484. * @return {number} X position of the pointer
  19485. */
  19486. get: function () {
  19487. return this._pointerX;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. Object.defineProperty(Scene.prototype, "pointerY", {
  19493. /**
  19494. * Current on-screen Y position of the pointer
  19495. * @return {number} Y position of the pointer
  19496. */
  19497. get: function () {
  19498. return this._pointerY;
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Scene.prototype.getCachedMaterial = function () {
  19504. return this._cachedMaterial;
  19505. };
  19506. Scene.prototype.getBoundingBoxRenderer = function () {
  19507. return this._boundingBoxRenderer;
  19508. };
  19509. Scene.prototype.getOutlineRenderer = function () {
  19510. return this._outlineRenderer;
  19511. };
  19512. Scene.prototype.getEngine = function () {
  19513. return this._engine;
  19514. };
  19515. Scene.prototype.getTotalVertices = function () {
  19516. return this._totalVertices.current;
  19517. };
  19518. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19519. get: function () {
  19520. return this._totalVertices;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Scene.prototype.getActiveIndices = function () {
  19526. return this._activeIndices.current;
  19527. };
  19528. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19529. get: function () {
  19530. return this._activeIndices;
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Scene.prototype.getActiveParticles = function () {
  19536. return this._activeParticles.current;
  19537. };
  19538. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19539. get: function () {
  19540. return this._activeParticles;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Scene.prototype.getActiveBones = function () {
  19546. return this._activeBones.current;
  19547. };
  19548. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19549. get: function () {
  19550. return this._activeBones;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. // Stats
  19556. Scene.prototype.getLastFrameDuration = function () {
  19557. return this._lastFrameDuration.current;
  19558. };
  19559. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19560. get: function () {
  19561. return this._lastFrameDuration;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19567. return this._evaluateActiveMeshesDuration.current;
  19568. };
  19569. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19570. get: function () {
  19571. return this._evaluateActiveMeshesDuration;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Scene.prototype.getActiveMeshes = function () {
  19577. return this._activeMeshes;
  19578. };
  19579. Scene.prototype.getRenderTargetsDuration = function () {
  19580. return this._renderTargetsDuration.current;
  19581. };
  19582. Scene.prototype.getRenderDuration = function () {
  19583. return this._renderDuration.current;
  19584. };
  19585. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19586. get: function () {
  19587. return this._renderDuration;
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. Scene.prototype.getParticlesDuration = function () {
  19593. return this._particlesDuration.current;
  19594. };
  19595. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19596. get: function () {
  19597. return this._particlesDuration;
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Scene.prototype.getSpritesDuration = function () {
  19603. return this._spritesDuration.current;
  19604. };
  19605. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19606. get: function () {
  19607. return this._spritesDuration;
  19608. },
  19609. enumerable: true,
  19610. configurable: true
  19611. });
  19612. Scene.prototype.getAnimationRatio = function () {
  19613. return this._animationRatio;
  19614. };
  19615. Scene.prototype.getRenderId = function () {
  19616. return this._renderId;
  19617. };
  19618. Scene.prototype.incrementRenderId = function () {
  19619. this._renderId++;
  19620. };
  19621. Scene.prototype._updatePointerPosition = function (evt) {
  19622. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19623. this._pointerX = evt.clientX - canvasRect.left;
  19624. this._pointerY = evt.clientY - canvasRect.top;
  19625. this._unTranslatedPointerX = this._pointerX;
  19626. this._unTranslatedPointerY = this._pointerY;
  19627. if (this.cameraToUseForPointers) {
  19628. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19629. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19630. }
  19631. };
  19632. // Pointers handling
  19633. /**
  19634. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19635. * @param attachUp defines if you want to attach events to pointerup
  19636. * @param attachDown defines if you want to attach events to pointerdown
  19637. * @param attachMove defines if you want to attach events to pointermove
  19638. */
  19639. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19640. var _this = this;
  19641. if (attachUp === void 0) { attachUp = true; }
  19642. if (attachDown === void 0) { attachDown = true; }
  19643. if (attachMove === void 0) { attachMove = true; }
  19644. var spritePredicate = function (sprite) {
  19645. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19646. };
  19647. this._onPointerMove = function (evt) {
  19648. _this._updatePointerPosition(evt);
  19649. // PreObservable support
  19650. if (_this.onPrePointerObservable.hasObservers()) {
  19651. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19652. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19653. _this.onPrePointerObservable.notifyObservers(pi, type);
  19654. if (pi.skipOnPointerObservable) {
  19655. return;
  19656. }
  19657. }
  19658. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19659. return;
  19660. }
  19661. var canvas = _this._engine.getRenderingCanvas();
  19662. if (!_this.pointerMovePredicate) {
  19663. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19664. }
  19665. // Meshes
  19666. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19667. if (pickResult.hit && pickResult.pickedMesh) {
  19668. _this.setPointerOverSprite(null);
  19669. _this.setPointerOverMesh(pickResult.pickedMesh);
  19670. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19671. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  19672. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  19673. }
  19674. else {
  19675. canvas.style.cursor = _this.hoverCursor;
  19676. }
  19677. }
  19678. else {
  19679. canvas.style.cursor = "";
  19680. }
  19681. }
  19682. else {
  19683. _this.setPointerOverMesh(null);
  19684. // Sprites
  19685. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19686. if (pickResult.hit && pickResult.pickedSprite) {
  19687. _this.setPointerOverSprite(pickResult.pickedSprite);
  19688. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  19689. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  19690. }
  19691. else {
  19692. canvas.style.cursor = _this.hoverCursor;
  19693. }
  19694. }
  19695. else {
  19696. _this.setPointerOverSprite(null);
  19697. // Restore pointer
  19698. canvas.style.cursor = "";
  19699. }
  19700. }
  19701. if (_this.onPointerMove) {
  19702. _this.onPointerMove(evt, pickResult);
  19703. }
  19704. if (_this.onPointerObservable.hasObservers()) {
  19705. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19706. var pi = new PointerInfo(type, evt, pickResult);
  19707. _this.onPointerObservable.notifyObservers(pi, type);
  19708. }
  19709. };
  19710. this._onPointerDown = function (evt) {
  19711. _this._updatePointerPosition(evt);
  19712. // PreObservable support
  19713. if (_this.onPrePointerObservable.hasObservers()) {
  19714. var type = PointerEventTypes.POINTERDOWN;
  19715. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19716. _this.onPrePointerObservable.notifyObservers(pi, type);
  19717. if (pi.skipOnPointerObservable) {
  19718. return;
  19719. }
  19720. }
  19721. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19722. return;
  19723. }
  19724. _this._startingPointerPosition.x = _this._pointerX;
  19725. _this._startingPointerPosition.y = _this._pointerY;
  19726. _this._startingPointerTime = new Date().getTime();
  19727. if (!_this.pointerDownPredicate) {
  19728. _this.pointerDownPredicate = function (mesh) {
  19729. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19730. };
  19731. }
  19732. // Meshes
  19733. _this._pickedDownMesh = null;
  19734. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19735. if (pickResult.hit && pickResult.pickedMesh) {
  19736. _this._pickedDownMesh = pickResult.pickedMesh;
  19737. if (pickResult.pickedMesh.actionManager) {
  19738. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  19739. switch (evt.button) {
  19740. case 0:
  19741. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19742. break;
  19743. case 1:
  19744. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19745. break;
  19746. case 2:
  19747. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19748. break;
  19749. }
  19750. if (pickResult.pickedMesh.actionManager) {
  19751. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19752. }
  19753. }
  19754. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19755. var that = _this;
  19756. window.setTimeout(function () {
  19757. 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);
  19758. if (pickResult.hit && pickResult.pickedMesh) {
  19759. if (pickResult.pickedMesh.actionManager) {
  19760. 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)) {
  19761. that._startingPointerTime = 0;
  19762. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19763. }
  19764. }
  19765. }
  19766. }, BABYLON.ActionManager.LongPressDelay);
  19767. }
  19768. }
  19769. }
  19770. if (_this.onPointerDown) {
  19771. _this.onPointerDown(evt, pickResult);
  19772. }
  19773. if (_this.onPointerObservable.hasObservers()) {
  19774. var type = PointerEventTypes.POINTERDOWN;
  19775. var pi = new PointerInfo(type, evt, pickResult);
  19776. _this.onPointerObservable.notifyObservers(pi, type);
  19777. }
  19778. // Sprites
  19779. _this._pickedDownSprite = null;
  19780. if (_this.spriteManagers.length > 0) {
  19781. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19782. if (pickResult.hit && pickResult.pickedSprite) {
  19783. if (pickResult.pickedSprite.actionManager) {
  19784. _this._pickedDownSprite = pickResult.pickedSprite;
  19785. switch (evt.button) {
  19786. case 0:
  19787. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19788. break;
  19789. case 1:
  19790. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19791. break;
  19792. case 2:
  19793. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19794. break;
  19795. }
  19796. if (pickResult.pickedSprite.actionManager) {
  19797. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19798. }
  19799. }
  19800. }
  19801. }
  19802. };
  19803. this._onPointerUp = function (evt) {
  19804. _this._updatePointerPosition(evt);
  19805. // PreObservable support
  19806. if (_this.onPrePointerObservable.hasObservers()) {
  19807. var type = PointerEventTypes.POINTERUP;
  19808. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19809. _this.onPrePointerObservable.notifyObservers(pi, type);
  19810. if (pi.skipOnPointerObservable) {
  19811. return;
  19812. }
  19813. }
  19814. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19815. return;
  19816. }
  19817. if (!_this.pointerUpPredicate) {
  19818. _this.pointerUpPredicate = function (mesh) {
  19819. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19820. };
  19821. }
  19822. // Meshes
  19823. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  19824. if (pickResult.hit && pickResult.pickedMesh) {
  19825. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  19826. if (_this.onPointerPick) {
  19827. _this.onPointerPick(evt, pickResult);
  19828. }
  19829. if (_this.onPointerObservable.hasObservers()) {
  19830. var type = PointerEventTypes.POINTERPICK;
  19831. var pi = new PointerInfo(type, evt, pickResult);
  19832. _this.onPointerObservable.notifyObservers(pi, type);
  19833. }
  19834. }
  19835. if (pickResult.pickedMesh.actionManager) {
  19836. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19837. if (pickResult.pickedMesh.actionManager) {
  19838. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19839. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19840. }
  19841. }
  19842. }
  19843. }
  19844. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  19845. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  19846. }
  19847. if (_this.onPointerUp) {
  19848. _this.onPointerUp(evt, pickResult);
  19849. }
  19850. if (_this.onPointerObservable.hasObservers()) {
  19851. var type = PointerEventTypes.POINTERUP;
  19852. var pi = new PointerInfo(type, evt, pickResult);
  19853. _this.onPointerObservable.notifyObservers(pi, type);
  19854. }
  19855. _this._startingPointerTime = 0;
  19856. // Sprites
  19857. if (_this.spriteManagers.length > 0) {
  19858. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19859. if (pickResult.hit && pickResult.pickedSprite) {
  19860. if (pickResult.pickedSprite.actionManager) {
  19861. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19862. if (pickResult.pickedSprite.actionManager) {
  19863. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19864. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19865. }
  19866. }
  19867. }
  19868. }
  19869. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  19870. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19871. }
  19872. }
  19873. };
  19874. this._onKeyDown = function (evt) {
  19875. if (_this.actionManager) {
  19876. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19877. }
  19878. };
  19879. this._onKeyUp = function (evt) {
  19880. if (_this.actionManager) {
  19881. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19882. }
  19883. };
  19884. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19885. var canvas = this._engine.getRenderingCanvas();
  19886. if (attachMove) {
  19887. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19888. // Wheel
  19889. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19890. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19891. }
  19892. if (attachDown) {
  19893. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19894. }
  19895. if (attachUp) {
  19896. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19897. }
  19898. canvas.tabIndex = 1;
  19899. canvas.addEventListener("keydown", this._onKeyDown, false);
  19900. canvas.addEventListener("keyup", this._onKeyUp, false);
  19901. };
  19902. Scene.prototype.detachControl = function () {
  19903. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19904. var canvas = this._engine.getRenderingCanvas();
  19905. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19906. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19907. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19908. // Wheel
  19909. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19910. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19911. canvas.removeEventListener("keydown", this._onKeyDown);
  19912. canvas.removeEventListener("keyup", this._onKeyUp);
  19913. };
  19914. // Ready
  19915. Scene.prototype.isReady = function () {
  19916. if (this._pendingData.length > 0) {
  19917. return false;
  19918. }
  19919. var index;
  19920. for (index = 0; index < this._geometries.length; index++) {
  19921. var geometry = this._geometries[index];
  19922. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19923. return false;
  19924. }
  19925. }
  19926. for (index = 0; index < this.meshes.length; index++) {
  19927. var mesh = this.meshes[index];
  19928. if (!mesh.isReady()) {
  19929. return false;
  19930. }
  19931. var mat = mesh.material;
  19932. if (mat) {
  19933. if (!mat.isReady(mesh)) {
  19934. return false;
  19935. }
  19936. }
  19937. }
  19938. return true;
  19939. };
  19940. Scene.prototype.resetCachedMaterial = function () {
  19941. this._cachedMaterial = null;
  19942. };
  19943. Scene.prototype.registerBeforeRender = function (func) {
  19944. this.onBeforeRenderObservable.add(func);
  19945. };
  19946. Scene.prototype.unregisterBeforeRender = function (func) {
  19947. this.onBeforeRenderObservable.removeCallback(func);
  19948. };
  19949. Scene.prototype.registerAfterRender = function (func) {
  19950. this.onAfterRenderObservable.add(func);
  19951. };
  19952. Scene.prototype.unregisterAfterRender = function (func) {
  19953. this.onAfterRenderObservable.removeCallback(func);
  19954. };
  19955. Scene.prototype._addPendingData = function (data) {
  19956. this._pendingData.push(data);
  19957. };
  19958. Scene.prototype._removePendingData = function (data) {
  19959. var index = this._pendingData.indexOf(data);
  19960. if (index !== -1) {
  19961. this._pendingData.splice(index, 1);
  19962. }
  19963. };
  19964. Scene.prototype.getWaitingItemsCount = function () {
  19965. return this._pendingData.length;
  19966. };
  19967. /**
  19968. * Registers a function to be executed when the scene is ready.
  19969. * @param {Function} func - the function to be executed.
  19970. */
  19971. Scene.prototype.executeWhenReady = function (func) {
  19972. var _this = this;
  19973. this.onReadyObservable.add(func);
  19974. if (this._executeWhenReadyTimeoutId !== -1) {
  19975. return;
  19976. }
  19977. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19978. _this._checkIsReady();
  19979. }, 150);
  19980. };
  19981. Scene.prototype._checkIsReady = function () {
  19982. var _this = this;
  19983. if (this.isReady()) {
  19984. this.onReadyObservable.notifyObservers(this);
  19985. this.onReadyObservable.clear();
  19986. this._executeWhenReadyTimeoutId = -1;
  19987. return;
  19988. }
  19989. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19990. _this._checkIsReady();
  19991. }, 150);
  19992. };
  19993. // Animations
  19994. /**
  19995. * Will start the animation sequence of a given target
  19996. * @param target - the target
  19997. * @param {number} from - from which frame should animation start
  19998. * @param {number} to - till which frame should animation run.
  19999. * @param {boolean} [loop] - should the animation loop
  20000. * @param {number} [speedRatio] - the speed in which to run the animation
  20001. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20002. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20003. * @return {BABYLON.Animatable} the animatable object created for this animation
  20004. * @see BABYLON.Animatable
  20005. * @see http://doc.babylonjs.com/page.php?p=22081
  20006. */
  20007. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20008. if (speedRatio === void 0) { speedRatio = 1.0; }
  20009. this.stopAnimation(target);
  20010. if (!animatable) {
  20011. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20012. }
  20013. // Local animations
  20014. if (target.animations) {
  20015. animatable.appendAnimations(target, target.animations);
  20016. }
  20017. // Children animations
  20018. if (target.getAnimatables) {
  20019. var animatables = target.getAnimatables();
  20020. for (var index = 0; index < animatables.length; index++) {
  20021. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20022. }
  20023. }
  20024. animatable.reset();
  20025. return animatable;
  20026. };
  20027. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20028. if (speedRatio === undefined) {
  20029. speedRatio = 1.0;
  20030. }
  20031. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20032. return animatable;
  20033. };
  20034. Scene.prototype.getAnimatableByTarget = function (target) {
  20035. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20036. if (this._activeAnimatables[index].target === target) {
  20037. return this._activeAnimatables[index];
  20038. }
  20039. }
  20040. return null;
  20041. };
  20042. Object.defineProperty(Scene.prototype, "Animatables", {
  20043. get: function () {
  20044. return this._activeAnimatables;
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. /**
  20050. * Will stop the animation of the given target
  20051. * @param target - the target
  20052. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20053. * @see beginAnimation
  20054. */
  20055. Scene.prototype.stopAnimation = function (target, animationName) {
  20056. var animatable = this.getAnimatableByTarget(target);
  20057. if (animatable) {
  20058. animatable.stop(animationName);
  20059. }
  20060. };
  20061. Scene.prototype._animate = function () {
  20062. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20063. return;
  20064. }
  20065. // Getting time
  20066. var now = BABYLON.Tools.Now;
  20067. if (!this._animationTimeLast) {
  20068. if (this._pendingData.length > 0) {
  20069. return;
  20070. }
  20071. this._animationTimeLast = now;
  20072. }
  20073. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20074. this._animationTime += deltaTime;
  20075. this._animationTimeLast = now;
  20076. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20077. this._activeAnimatables[index]._animate(this._animationTime);
  20078. }
  20079. };
  20080. // Matrix
  20081. Scene.prototype.getViewMatrix = function () {
  20082. return this._viewMatrix;
  20083. };
  20084. Scene.prototype.getProjectionMatrix = function () {
  20085. return this._projectionMatrix;
  20086. };
  20087. Scene.prototype.getTransformMatrix = function () {
  20088. return this._transformMatrix;
  20089. };
  20090. Scene.prototype.setTransformMatrix = function (view, projection) {
  20091. this._viewMatrix = view;
  20092. this._projectionMatrix = projection;
  20093. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20094. // Update frustum
  20095. if (!this._frustumPlanes) {
  20096. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20097. }
  20098. else {
  20099. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20100. }
  20101. };
  20102. // Methods
  20103. Scene.prototype.addMesh = function (newMesh) {
  20104. newMesh.uniqueId = this._uniqueIdCounter++;
  20105. var position = this.meshes.push(newMesh);
  20106. //notify the collision coordinator
  20107. this.collisionCoordinator.onMeshAdded(newMesh);
  20108. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20109. };
  20110. Scene.prototype.removeMesh = function (toRemove) {
  20111. var index = this.meshes.indexOf(toRemove);
  20112. if (index !== -1) {
  20113. // Remove from the scene if mesh found
  20114. this.meshes.splice(index, 1);
  20115. }
  20116. //notify the collision coordinator
  20117. this.collisionCoordinator.onMeshRemoved(toRemove);
  20118. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20119. return index;
  20120. };
  20121. Scene.prototype.removeSkeleton = function (toRemove) {
  20122. var index = this.skeletons.indexOf(toRemove);
  20123. if (index !== -1) {
  20124. // Remove from the scene if mesh found
  20125. this.skeletons.splice(index, 1);
  20126. }
  20127. return index;
  20128. };
  20129. Scene.prototype.removeLight = function (toRemove) {
  20130. var index = this.lights.indexOf(toRemove);
  20131. if (index !== -1) {
  20132. // Remove from the scene if mesh found
  20133. this.lights.splice(index, 1);
  20134. }
  20135. this.onLightRemovedObservable.notifyObservers(toRemove);
  20136. return index;
  20137. };
  20138. Scene.prototype.removeCamera = function (toRemove) {
  20139. var index = this.cameras.indexOf(toRemove);
  20140. if (index !== -1) {
  20141. // Remove from the scene if mesh found
  20142. this.cameras.splice(index, 1);
  20143. }
  20144. // Remove from activeCameras
  20145. var index2 = this.activeCameras.indexOf(toRemove);
  20146. if (index2 !== -1) {
  20147. // Remove from the scene if mesh found
  20148. this.activeCameras.splice(index2, 1);
  20149. }
  20150. // Reset the activeCamera
  20151. if (this.activeCamera === toRemove) {
  20152. if (this.cameras.length > 0) {
  20153. this.activeCamera = this.cameras[0];
  20154. }
  20155. else {
  20156. this.activeCamera = null;
  20157. }
  20158. }
  20159. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20160. return index;
  20161. };
  20162. Scene.prototype.addLight = function (newLight) {
  20163. newLight.uniqueId = this._uniqueIdCounter++;
  20164. var position = this.lights.push(newLight);
  20165. this.onNewLightAddedObservable.notifyObservers(newLight);
  20166. };
  20167. Scene.prototype.addCamera = function (newCamera) {
  20168. newCamera.uniqueId = this._uniqueIdCounter++;
  20169. var position = this.cameras.push(newCamera);
  20170. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20171. };
  20172. /**
  20173. * Switch active camera
  20174. * @param {Camera} newCamera - new active camera
  20175. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20176. */
  20177. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20178. if (attachControl === void 0) { attachControl = true; }
  20179. var canvas = this._engine.getRenderingCanvas();
  20180. this.activeCamera.detachControl(canvas);
  20181. this.activeCamera = newCamera;
  20182. if (attachControl) {
  20183. newCamera.attachControl(canvas);
  20184. }
  20185. };
  20186. /**
  20187. * sets the active camera of the scene using its ID
  20188. * @param {string} id - the camera's ID
  20189. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20190. * @see activeCamera
  20191. */
  20192. Scene.prototype.setActiveCameraByID = function (id) {
  20193. var camera = this.getCameraByID(id);
  20194. if (camera) {
  20195. this.activeCamera = camera;
  20196. return camera;
  20197. }
  20198. return null;
  20199. };
  20200. /**
  20201. * sets the active camera of the scene using its name
  20202. * @param {string} name - the camera's name
  20203. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20204. * @see activeCamera
  20205. */
  20206. Scene.prototype.setActiveCameraByName = function (name) {
  20207. var camera = this.getCameraByName(name);
  20208. if (camera) {
  20209. this.activeCamera = camera;
  20210. return camera;
  20211. }
  20212. return null;
  20213. };
  20214. /**
  20215. * get a material using its id
  20216. * @param {string} the material's ID
  20217. * @return {BABYLON.Material|null} the material or null if none found.
  20218. */
  20219. Scene.prototype.getMaterialByID = function (id) {
  20220. for (var index = 0; index < this.materials.length; index++) {
  20221. if (this.materials[index].id === id) {
  20222. return this.materials[index];
  20223. }
  20224. }
  20225. return null;
  20226. };
  20227. /**
  20228. * get a material using its name
  20229. * @param {string} the material's name
  20230. * @return {BABYLON.Material|null} the material or null if none found.
  20231. */
  20232. Scene.prototype.getMaterialByName = function (name) {
  20233. for (var index = 0; index < this.materials.length; index++) {
  20234. if (this.materials[index].name === name) {
  20235. return this.materials[index];
  20236. }
  20237. }
  20238. return null;
  20239. };
  20240. Scene.prototype.getLensFlareSystemByName = function (name) {
  20241. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20242. if (this.lensFlareSystems[index].name === name) {
  20243. return this.lensFlareSystems[index];
  20244. }
  20245. }
  20246. return null;
  20247. };
  20248. Scene.prototype.getLensFlareSystemByID = function (id) {
  20249. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20250. if (this.lensFlareSystems[index].id === id) {
  20251. return this.lensFlareSystems[index];
  20252. }
  20253. }
  20254. return null;
  20255. };
  20256. Scene.prototype.getCameraByID = function (id) {
  20257. for (var index = 0; index < this.cameras.length; index++) {
  20258. if (this.cameras[index].id === id) {
  20259. return this.cameras[index];
  20260. }
  20261. }
  20262. return null;
  20263. };
  20264. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20265. for (var index = 0; index < this.cameras.length; index++) {
  20266. if (this.cameras[index].uniqueId === uniqueId) {
  20267. return this.cameras[index];
  20268. }
  20269. }
  20270. return null;
  20271. };
  20272. /**
  20273. * get a camera using its name
  20274. * @param {string} the camera's name
  20275. * @return {BABYLON.Camera|null} the camera or null if none found.
  20276. */
  20277. Scene.prototype.getCameraByName = function (name) {
  20278. for (var index = 0; index < this.cameras.length; index++) {
  20279. if (this.cameras[index].name === name) {
  20280. return this.cameras[index];
  20281. }
  20282. }
  20283. return null;
  20284. };
  20285. /**
  20286. * get a bone using its id
  20287. * @param {string} the bone's id
  20288. * @return {BABYLON.Bone|null} the bone or null if not found
  20289. */
  20290. Scene.prototype.getBoneByID = function (id) {
  20291. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20292. var skeleton = this.skeletons[skeletonIndex];
  20293. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20294. if (skeleton.bones[boneIndex].id === id) {
  20295. return skeleton.bones[boneIndex];
  20296. }
  20297. }
  20298. }
  20299. return null;
  20300. };
  20301. /**
  20302. * get a bone using its id
  20303. * @param {string} the bone's name
  20304. * @return {BABYLON.Bone|null} the bone or null if not found
  20305. */
  20306. Scene.prototype.getBoneByName = function (name) {
  20307. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20308. var skeleton = this.skeletons[skeletonIndex];
  20309. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20310. if (skeleton.bones[boneIndex].name === name) {
  20311. return skeleton.bones[boneIndex];
  20312. }
  20313. }
  20314. }
  20315. return null;
  20316. };
  20317. /**
  20318. * get a light node using its name
  20319. * @param {string} the light's name
  20320. * @return {BABYLON.Light|null} the light or null if none found.
  20321. */
  20322. Scene.prototype.getLightByName = function (name) {
  20323. for (var index = 0; index < this.lights.length; index++) {
  20324. if (this.lights[index].name === name) {
  20325. return this.lights[index];
  20326. }
  20327. }
  20328. return null;
  20329. };
  20330. /**
  20331. * get a light node using its ID
  20332. * @param {string} the light's id
  20333. * @return {BABYLON.Light|null} the light or null if none found.
  20334. */
  20335. Scene.prototype.getLightByID = function (id) {
  20336. for (var index = 0; index < this.lights.length; index++) {
  20337. if (this.lights[index].id === id) {
  20338. return this.lights[index];
  20339. }
  20340. }
  20341. return null;
  20342. };
  20343. /**
  20344. * get a light node using its scene-generated unique ID
  20345. * @param {number} the light's unique id
  20346. * @return {BABYLON.Light|null} the light or null if none found.
  20347. */
  20348. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20349. for (var index = 0; index < this.lights.length; index++) {
  20350. if (this.lights[index].uniqueId === uniqueId) {
  20351. return this.lights[index];
  20352. }
  20353. }
  20354. return null;
  20355. };
  20356. /**
  20357. * get a particle system by id
  20358. * @param id {number} the particle system id
  20359. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20360. */
  20361. Scene.prototype.getParticleSystemByID = function (id) {
  20362. for (var index = 0; index < this.particleSystems.length; index++) {
  20363. if (this.particleSystems[index].id === id) {
  20364. return this.particleSystems[index];
  20365. }
  20366. }
  20367. return null;
  20368. };
  20369. /**
  20370. * get a geometry using its ID
  20371. * @param {string} the geometry's id
  20372. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20373. */
  20374. Scene.prototype.getGeometryByID = function (id) {
  20375. for (var index = 0; index < this._geometries.length; index++) {
  20376. if (this._geometries[index].id === id) {
  20377. return this._geometries[index];
  20378. }
  20379. }
  20380. return null;
  20381. };
  20382. /**
  20383. * add a new geometry to this scene.
  20384. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20385. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20386. * @return {boolean} was the geometry added or not
  20387. */
  20388. Scene.prototype.pushGeometry = function (geometry, force) {
  20389. if (!force && this.getGeometryByID(geometry.id)) {
  20390. return false;
  20391. }
  20392. this._geometries.push(geometry);
  20393. //notify the collision coordinator
  20394. this.collisionCoordinator.onGeometryAdded(geometry);
  20395. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20396. return true;
  20397. };
  20398. /**
  20399. * Removes an existing geometry
  20400. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20401. * @return {boolean} was the geometry removed or not
  20402. */
  20403. Scene.prototype.removeGeometry = function (geometry) {
  20404. var index = this._geometries.indexOf(geometry);
  20405. if (index > -1) {
  20406. this._geometries.splice(index, 1);
  20407. //notify the collision coordinator
  20408. this.collisionCoordinator.onGeometryDeleted(geometry);
  20409. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20410. return true;
  20411. }
  20412. return false;
  20413. };
  20414. Scene.prototype.getGeometries = function () {
  20415. return this._geometries;
  20416. };
  20417. /**
  20418. * Get the first added mesh found of a given ID
  20419. * @param {string} id - the id to search for
  20420. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20421. */
  20422. Scene.prototype.getMeshByID = function (id) {
  20423. for (var index = 0; index < this.meshes.length; index++) {
  20424. if (this.meshes[index].id === id) {
  20425. return this.meshes[index];
  20426. }
  20427. }
  20428. return null;
  20429. };
  20430. Scene.prototype.getMeshesByID = function (id) {
  20431. return this.meshes.filter(function (m) {
  20432. return m.id === id;
  20433. });
  20434. };
  20435. /**
  20436. * Get a mesh with its auto-generated unique id
  20437. * @param {number} uniqueId - the unique id to search for
  20438. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20439. */
  20440. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20441. for (var index = 0; index < this.meshes.length; index++) {
  20442. if (this.meshes[index].uniqueId === uniqueId) {
  20443. return this.meshes[index];
  20444. }
  20445. }
  20446. return null;
  20447. };
  20448. /**
  20449. * Get a the last added mesh found of a given ID
  20450. * @param {string} id - the id to search for
  20451. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20452. */
  20453. Scene.prototype.getLastMeshByID = function (id) {
  20454. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20455. if (this.meshes[index].id === id) {
  20456. return this.meshes[index];
  20457. }
  20458. }
  20459. return null;
  20460. };
  20461. /**
  20462. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20463. * @param {string} id - the id to search for
  20464. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20465. */
  20466. Scene.prototype.getLastEntryByID = function (id) {
  20467. var index;
  20468. for (index = this.meshes.length - 1; index >= 0; index--) {
  20469. if (this.meshes[index].id === id) {
  20470. return this.meshes[index];
  20471. }
  20472. }
  20473. for (index = this.cameras.length - 1; index >= 0; index--) {
  20474. if (this.cameras[index].id === id) {
  20475. return this.cameras[index];
  20476. }
  20477. }
  20478. for (index = this.lights.length - 1; index >= 0; index--) {
  20479. if (this.lights[index].id === id) {
  20480. return this.lights[index];
  20481. }
  20482. }
  20483. return null;
  20484. };
  20485. Scene.prototype.getNodeByID = function (id) {
  20486. var mesh = this.getMeshByID(id);
  20487. if (mesh) {
  20488. return mesh;
  20489. }
  20490. var light = this.getLightByID(id);
  20491. if (light) {
  20492. return light;
  20493. }
  20494. var camera = this.getCameraByID(id);
  20495. if (camera) {
  20496. return camera;
  20497. }
  20498. var bone = this.getBoneByID(id);
  20499. return bone;
  20500. };
  20501. Scene.prototype.getNodeByName = function (name) {
  20502. var mesh = this.getMeshByName(name);
  20503. if (mesh) {
  20504. return mesh;
  20505. }
  20506. var light = this.getLightByName(name);
  20507. if (light) {
  20508. return light;
  20509. }
  20510. var camera = this.getCameraByName(name);
  20511. if (camera) {
  20512. return camera;
  20513. }
  20514. var bone = this.getBoneByName(name);
  20515. return bone;
  20516. };
  20517. Scene.prototype.getMeshByName = function (name) {
  20518. for (var index = 0; index < this.meshes.length; index++) {
  20519. if (this.meshes[index].name === name) {
  20520. return this.meshes[index];
  20521. }
  20522. }
  20523. return null;
  20524. };
  20525. Scene.prototype.getSoundByName = function (name) {
  20526. var index;
  20527. if (BABYLON.AudioEngine) {
  20528. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20529. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20530. return this.mainSoundTrack.soundCollection[index];
  20531. }
  20532. }
  20533. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20534. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20535. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20536. return this.soundTracks[sdIndex].soundCollection[index];
  20537. }
  20538. }
  20539. }
  20540. }
  20541. return null;
  20542. };
  20543. Scene.prototype.getLastSkeletonByID = function (id) {
  20544. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20545. if (this.skeletons[index].id === id) {
  20546. return this.skeletons[index];
  20547. }
  20548. }
  20549. return null;
  20550. };
  20551. Scene.prototype.getSkeletonById = function (id) {
  20552. for (var index = 0; index < this.skeletons.length; index++) {
  20553. if (this.skeletons[index].id === id) {
  20554. return this.skeletons[index];
  20555. }
  20556. }
  20557. return null;
  20558. };
  20559. Scene.prototype.getSkeletonByName = function (name) {
  20560. for (var index = 0; index < this.skeletons.length; index++) {
  20561. if (this.skeletons[index].name === name) {
  20562. return this.skeletons[index];
  20563. }
  20564. }
  20565. return null;
  20566. };
  20567. Scene.prototype.isActiveMesh = function (mesh) {
  20568. return (this._activeMeshes.indexOf(mesh) !== -1);
  20569. };
  20570. Object.defineProperty(Scene.prototype, "uid", {
  20571. /**
  20572. * Return a unique id as a string which can serve as an identifier for the scene
  20573. */
  20574. get: function () {
  20575. if (!this._uid) {
  20576. this._uid = BABYLON.Tools.RandomId();
  20577. }
  20578. return this._uid;
  20579. },
  20580. enumerable: true,
  20581. configurable: true
  20582. });
  20583. /**
  20584. * Add an externaly attached data from its key.
  20585. * This method call will fail and return false, if such key already exists.
  20586. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20587. * @param key the unique key that identifies the data
  20588. * @param data the data object to associate to the key for this Engine instance
  20589. * @return true if no such key were already present and the data was added successfully, false otherwise
  20590. */
  20591. Scene.prototype.addExternalData = function (key, data) {
  20592. return this._externalData.add(key, data);
  20593. };
  20594. /**
  20595. * Get an externaly attached data from its key
  20596. * @param key the unique key that identifies the data
  20597. * @return the associated data, if present (can be null), or undefined if not present
  20598. */
  20599. Scene.prototype.getExternalData = function (key) {
  20600. return this._externalData.get(key);
  20601. };
  20602. /**
  20603. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20604. * @param key the unique key that identifies the data
  20605. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20606. * @return the associated data, can be null if the factory returned null.
  20607. */
  20608. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20609. return this._externalData.getOrAddWithFactory(key, factory);
  20610. };
  20611. /**
  20612. * Remove an externaly attached data from the Engine instance
  20613. * @param key the unique key that identifies the data
  20614. * @return true if the data was successfully removed, false if it doesn't exist
  20615. */
  20616. Scene.prototype.removeExternalData = function (key) {
  20617. return this._externalData.remove(key);
  20618. };
  20619. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20620. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20621. var material = subMesh.getMaterial();
  20622. if (mesh.showSubMeshesBoundingBox) {
  20623. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  20624. }
  20625. if (material) {
  20626. // Render targets
  20627. if (material.getRenderTargetTextures) {
  20628. if (this._processedMaterials.indexOf(material) === -1) {
  20629. this._processedMaterials.push(material);
  20630. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20631. }
  20632. }
  20633. // Dispatch
  20634. this._activeIndices.addCount(subMesh.indexCount, false);
  20635. this._renderingManager.dispatch(subMesh);
  20636. }
  20637. }
  20638. };
  20639. Scene.prototype._isInIntermediateRendering = function () {
  20640. return this._intermediateRendering;
  20641. };
  20642. Scene.prototype._evaluateActiveMeshes = function () {
  20643. this.activeCamera._activeMeshes.reset();
  20644. this._activeMeshes.reset();
  20645. this._renderingManager.reset();
  20646. this._processedMaterials.reset();
  20647. this._activeParticleSystems.reset();
  20648. this._activeSkeletons.reset();
  20649. this._softwareSkinnedMeshes.reset();
  20650. this._boundingBoxRenderer.reset();
  20651. this._edgesRenderers.reset();
  20652. // Meshes
  20653. var meshes;
  20654. var len;
  20655. if (this._selectionOctree) {
  20656. var selection = this._selectionOctree.select(this._frustumPlanes);
  20657. meshes = selection.data;
  20658. len = selection.length;
  20659. }
  20660. else {
  20661. len = this.meshes.length;
  20662. meshes = this.meshes;
  20663. }
  20664. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20665. var mesh = meshes[meshIndex];
  20666. if (mesh.isBlocked) {
  20667. continue;
  20668. }
  20669. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20670. if (!mesh.isReady() || !mesh.isEnabled()) {
  20671. continue;
  20672. }
  20673. mesh.computeWorldMatrix();
  20674. // Intersections
  20675. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20676. this._meshesForIntersections.pushNoDuplicate(mesh);
  20677. }
  20678. // Switch to current LOD
  20679. var meshLOD = mesh.getLOD(this.activeCamera);
  20680. if (!meshLOD) {
  20681. continue;
  20682. }
  20683. mesh._preActivate();
  20684. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20685. this._activeMeshes.push(mesh);
  20686. this.activeCamera._activeMeshes.push(mesh);
  20687. mesh._activate(this._renderId);
  20688. this._activeMesh(mesh, meshLOD);
  20689. }
  20690. }
  20691. // Particle systems
  20692. this._particlesDuration.beginMonitoring();
  20693. var beforeParticlesDate = BABYLON.Tools.Now;
  20694. if (this.particlesEnabled) {
  20695. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  20696. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20697. var particleSystem = this.particleSystems[particleIndex];
  20698. if (!particleSystem.isStarted()) {
  20699. continue;
  20700. }
  20701. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  20702. this._activeParticleSystems.push(particleSystem);
  20703. particleSystem.animate();
  20704. this._renderingManager.dispatchParticles(particleSystem);
  20705. }
  20706. }
  20707. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  20708. }
  20709. this._particlesDuration.endMonitoring(false);
  20710. };
  20711. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20712. if (mesh.skeleton && this.skeletonsEnabled) {
  20713. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20714. mesh.skeleton.prepare();
  20715. }
  20716. if (!mesh.computeBonesUsingShaders) {
  20717. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20718. }
  20719. }
  20720. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20721. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  20722. }
  20723. if (sourceMesh._edgesRenderer) {
  20724. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  20725. }
  20726. if (mesh && mesh.subMeshes) {
  20727. // Submeshes Octrees
  20728. var len;
  20729. var subMeshes;
  20730. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20731. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20732. len = intersections.length;
  20733. subMeshes = intersections.data;
  20734. }
  20735. else {
  20736. subMeshes = mesh.subMeshes;
  20737. len = subMeshes.length;
  20738. }
  20739. for (var subIndex = 0; subIndex < len; subIndex++) {
  20740. var subMesh = subMeshes[subIndex];
  20741. this._evaluateSubMesh(subMesh, mesh);
  20742. }
  20743. }
  20744. };
  20745. Scene.prototype.updateTransformMatrix = function (force) {
  20746. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20747. };
  20748. Scene.prototype._renderForCamera = function (camera) {
  20749. var engine = this._engine;
  20750. var startTime = BABYLON.Tools.Now;
  20751. this.activeCamera = camera;
  20752. if (!this.activeCamera)
  20753. throw new Error("Active camera not set");
  20754. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20755. // Viewport
  20756. engine.setViewport(this.activeCamera.viewport);
  20757. // Camera
  20758. this.resetCachedMaterial();
  20759. this._renderId++;
  20760. this.updateTransformMatrix();
  20761. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20762. // Meshes
  20763. this._evaluateActiveMeshesDuration.beginMonitoring();
  20764. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  20765. this._evaluateActiveMeshes();
  20766. this._evaluateActiveMeshesDuration.endMonitoring(false);
  20767. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  20768. // Software skinning
  20769. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20770. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20771. mesh.applySkeleton(mesh.skeleton);
  20772. }
  20773. // Render targets
  20774. this._renderTargetsDuration.beginMonitoring();
  20775. var needsRestoreFrameBuffer = false;
  20776. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20777. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20778. this._intermediateRendering = true;
  20779. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20780. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20781. var renderTarget = this._renderTargets.data[renderIndex];
  20782. if (renderTarget._shouldRender()) {
  20783. this._renderId++;
  20784. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20785. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20786. }
  20787. }
  20788. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20789. this._intermediateRendering = false;
  20790. this._renderId++;
  20791. needsRestoreFrameBuffer = true; // Restore back buffer
  20792. }
  20793. // Render HighlightLayer Texture
  20794. var stencilState = this._engine.getStencilBuffer();
  20795. var renderhighlights = false;
  20796. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20797. this._intermediateRendering = true;
  20798. for (var i = 0; i < this.highlightLayers.length; i++) {
  20799. var highlightLayer = this.highlightLayers[i];
  20800. if (highlightLayer.shouldRender() &&
  20801. (!highlightLayer.camera ||
  20802. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20803. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20804. renderhighlights = true;
  20805. var renderTarget = highlightLayer._mainTexture;
  20806. if (renderTarget._shouldRender()) {
  20807. this._renderId++;
  20808. renderTarget.render(false, false);
  20809. needsRestoreFrameBuffer = true;
  20810. }
  20811. }
  20812. }
  20813. this._intermediateRendering = false;
  20814. this._renderId++;
  20815. }
  20816. if (needsRestoreFrameBuffer) {
  20817. engine.restoreDefaultFramebuffer();
  20818. }
  20819. this._renderTargetsDuration.endMonitoring(false);
  20820. // Prepare Frame
  20821. this.postProcessManager._prepareFrame();
  20822. this._renderDuration.beginMonitoring();
  20823. // Backgrounds
  20824. var layerIndex;
  20825. var layer;
  20826. if (this.layers.length) {
  20827. engine.setDepthBuffer(false);
  20828. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20829. layer = this.layers[layerIndex];
  20830. if (layer.isBackground) {
  20831. layer.render();
  20832. }
  20833. }
  20834. engine.setDepthBuffer(true);
  20835. }
  20836. // Render
  20837. BABYLON.Tools.StartPerformanceCounter("Main render");
  20838. // Activate HighlightLayer stencil
  20839. if (renderhighlights) {
  20840. this._engine.setStencilBuffer(true);
  20841. }
  20842. this._renderingManager.render(null, null, true, true);
  20843. // Restore HighlightLayer stencil
  20844. if (renderhighlights) {
  20845. this._engine.setStencilBuffer(stencilState);
  20846. }
  20847. BABYLON.Tools.EndPerformanceCounter("Main render");
  20848. // Bounding boxes
  20849. this._boundingBoxRenderer.render();
  20850. // Edges
  20851. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20852. this._edgesRenderers.data[edgesRendererIndex].render();
  20853. }
  20854. // Lens flares
  20855. if (this.lensFlaresEnabled) {
  20856. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20857. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20858. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20859. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20860. lensFlareSystem.render();
  20861. }
  20862. }
  20863. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20864. }
  20865. // Foregrounds
  20866. if (this.layers.length) {
  20867. engine.setDepthBuffer(false);
  20868. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20869. layer = this.layers[layerIndex];
  20870. if (!layer.isBackground) {
  20871. layer.render();
  20872. }
  20873. }
  20874. engine.setDepthBuffer(true);
  20875. }
  20876. // Highlight Layer
  20877. if (renderhighlights) {
  20878. engine.setDepthBuffer(false);
  20879. for (var i = 0; i < this.highlightLayers.length; i++) {
  20880. if (this.highlightLayers[i].shouldRender()) {
  20881. this.highlightLayers[i].render();
  20882. }
  20883. }
  20884. engine.setDepthBuffer(true);
  20885. }
  20886. this._renderDuration.endMonitoring(false);
  20887. // Finalize frame
  20888. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20889. // Update camera
  20890. this.activeCamera._updateFromScene();
  20891. // Reset some special arrays
  20892. this._renderTargets.reset();
  20893. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20894. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20895. };
  20896. Scene.prototype._processSubCameras = function (camera) {
  20897. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20898. this._renderForCamera(camera);
  20899. return;
  20900. }
  20901. // rig cameras
  20902. for (var index = 0; index < camera._rigCameras.length; index++) {
  20903. this._renderForCamera(camera._rigCameras[index]);
  20904. }
  20905. this.activeCamera = camera;
  20906. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20907. // Update camera
  20908. this.activeCamera._updateFromScene();
  20909. };
  20910. Scene.prototype._checkIntersections = function () {
  20911. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20912. var sourceMesh = this._meshesForIntersections.data[index];
  20913. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20914. var action = sourceMesh.actionManager.actions[actionIndex];
  20915. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20916. var parameters = action.getTriggerParameter();
  20917. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20918. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20919. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20920. if (areIntersecting && currentIntersectionInProgress === -1) {
  20921. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20922. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20923. sourceMesh._intersectionsInProgress.push(otherMesh);
  20924. }
  20925. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20926. sourceMesh._intersectionsInProgress.push(otherMesh);
  20927. }
  20928. }
  20929. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20930. //They intersected, and now they don't.
  20931. //is this trigger an exit trigger? execute an event.
  20932. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20933. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20934. }
  20935. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20936. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20937. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20938. }
  20939. }
  20940. }
  20941. }
  20942. }
  20943. };
  20944. Scene.prototype.render = function () {
  20945. this._lastFrameDuration.beginMonitoring();
  20946. this._particlesDuration.fetchNewFrame();
  20947. this._spritesDuration.fetchNewFrame();
  20948. this._activeParticles.fetchNewFrame();
  20949. this._renderDuration.fetchNewFrame();
  20950. this._renderTargetsDuration.fetchNewFrame();
  20951. this._evaluateActiveMeshesDuration.fetchNewFrame();
  20952. this._totalVertices.fetchNewFrame();
  20953. this._activeIndices.fetchNewFrame();
  20954. this._activeBones.fetchNewFrame();
  20955. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  20956. this._meshesForIntersections.reset();
  20957. this.resetCachedMaterial();
  20958. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  20959. // Actions
  20960. if (this.actionManager) {
  20961. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  20962. }
  20963. //Simplification Queue
  20964. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20965. this.simplificationQueue.executeNext();
  20966. }
  20967. // Animations
  20968. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20969. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20970. this._animate();
  20971. // Physics
  20972. if (this._physicsEngine) {
  20973. BABYLON.Tools.StartPerformanceCounter("Physics");
  20974. this._physicsEngine._step(deltaTime / 1000.0);
  20975. BABYLON.Tools.EndPerformanceCounter("Physics");
  20976. }
  20977. // Before render
  20978. this.onBeforeRenderObservable.notifyObservers(this);
  20979. // Customs render targets
  20980. this._renderTargetsDuration.beginMonitoring();
  20981. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20982. var engine = this.getEngine();
  20983. var currentActiveCamera = this.activeCamera;
  20984. if (this.renderTargetsEnabled) {
  20985. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20986. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20987. var renderTarget = this.customRenderTargets[customIndex];
  20988. if (renderTarget._shouldRender()) {
  20989. this._renderId++;
  20990. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20991. if (!this.activeCamera)
  20992. throw new Error("Active camera not set");
  20993. // Viewport
  20994. engine.setViewport(this.activeCamera.viewport);
  20995. // Camera
  20996. this.updateTransformMatrix();
  20997. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20998. }
  20999. }
  21000. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21001. this._renderId++;
  21002. }
  21003. if (this.customRenderTargets.length > 0) {
  21004. engine.restoreDefaultFramebuffer();
  21005. }
  21006. this._renderTargetsDuration.endMonitoring();
  21007. this.activeCamera = currentActiveCamera;
  21008. // Procedural textures
  21009. if (this.proceduralTexturesEnabled) {
  21010. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21011. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21012. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21013. if (proceduralTexture._shouldRender()) {
  21014. proceduralTexture.render();
  21015. }
  21016. }
  21017. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21018. }
  21019. // Clear
  21020. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21021. // Shadows
  21022. if (this.shadowsEnabled) {
  21023. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21024. var light = this.lights[lightIndex];
  21025. var shadowGenerator = light.getShadowGenerator();
  21026. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21027. this._renderTargets.push(shadowGenerator.getShadowMap());
  21028. }
  21029. }
  21030. }
  21031. // Depth renderer
  21032. if (this._depthRenderer) {
  21033. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21034. }
  21035. // RenderPipeline
  21036. this.postProcessRenderPipelineManager.update();
  21037. // Multi-cameras?
  21038. if (this.activeCameras.length > 0) {
  21039. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21040. if (cameraIndex > 0) {
  21041. this._engine.clear(null, false, true, true);
  21042. }
  21043. this._processSubCameras(this.activeCameras[cameraIndex]);
  21044. }
  21045. }
  21046. else {
  21047. if (!this.activeCamera) {
  21048. throw new Error("No camera defined");
  21049. }
  21050. this._processSubCameras(this.activeCamera);
  21051. }
  21052. // Intersection checks
  21053. this._checkIntersections();
  21054. // Update the audio listener attached to the camera
  21055. if (BABYLON.AudioEngine) {
  21056. this._updateAudioParameters();
  21057. }
  21058. // After render
  21059. if (this.afterRender) {
  21060. this.afterRender();
  21061. }
  21062. this.onAfterRenderObservable.notifyObservers(this);
  21063. // Cleaning
  21064. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21065. this._toBeDisposed.data[index].dispose();
  21066. this._toBeDisposed[index] = null;
  21067. }
  21068. this._toBeDisposed.reset();
  21069. if (this.dumpNextRenderTargets) {
  21070. this.dumpNextRenderTargets = false;
  21071. }
  21072. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21073. this._lastFrameDuration.endMonitoring();
  21074. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21075. this._totalLightsCounter.addCount(this.lights.length, true);
  21076. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21077. this._totalTexturesCounter.addCount(this.textures.length, true);
  21078. this._activeBones.addCount(0, true);
  21079. this._activeIndices.addCount(0, true);
  21080. this._activeParticles.addCount(0, true);
  21081. };
  21082. Scene.prototype._updateAudioParameters = function () {
  21083. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21084. return;
  21085. }
  21086. var listeningCamera;
  21087. var audioEngine = BABYLON.Engine.audioEngine;
  21088. if (this.activeCameras.length > 0) {
  21089. listeningCamera = this.activeCameras[0];
  21090. }
  21091. else {
  21092. listeningCamera = this.activeCamera;
  21093. }
  21094. if (listeningCamera && audioEngine.canUseWebAudio) {
  21095. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21096. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21097. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21098. cameraDirection.normalize();
  21099. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21100. var i;
  21101. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21102. var sound = this.mainSoundTrack.soundCollection[i];
  21103. if (sound.useCustomAttenuation) {
  21104. sound.updateDistanceFromListener();
  21105. }
  21106. }
  21107. for (i = 0; i < this.soundTracks.length; i++) {
  21108. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21109. sound = this.soundTracks[i].soundCollection[j];
  21110. if (sound.useCustomAttenuation) {
  21111. sound.updateDistanceFromListener();
  21112. }
  21113. }
  21114. }
  21115. }
  21116. };
  21117. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21118. // Audio
  21119. get: function () {
  21120. return this._audioEnabled;
  21121. },
  21122. set: function (value) {
  21123. this._audioEnabled = value;
  21124. if (BABYLON.AudioEngine) {
  21125. if (this._audioEnabled) {
  21126. this._enableAudio();
  21127. }
  21128. else {
  21129. this._disableAudio();
  21130. }
  21131. }
  21132. },
  21133. enumerable: true,
  21134. configurable: true
  21135. });
  21136. Scene.prototype._disableAudio = function () {
  21137. var i;
  21138. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21139. this.mainSoundTrack.soundCollection[i].pause();
  21140. }
  21141. for (i = 0; i < this.soundTracks.length; i++) {
  21142. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21143. this.soundTracks[i].soundCollection[j].pause();
  21144. }
  21145. }
  21146. };
  21147. Scene.prototype._enableAudio = function () {
  21148. var i;
  21149. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21150. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21151. this.mainSoundTrack.soundCollection[i].play();
  21152. }
  21153. }
  21154. for (i = 0; i < this.soundTracks.length; i++) {
  21155. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21156. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21157. this.soundTracks[i].soundCollection[j].play();
  21158. }
  21159. }
  21160. }
  21161. };
  21162. Object.defineProperty(Scene.prototype, "headphone", {
  21163. get: function () {
  21164. return this._headphone;
  21165. },
  21166. set: function (value) {
  21167. this._headphone = value;
  21168. if (BABYLON.AudioEngine) {
  21169. if (this._headphone) {
  21170. this._switchAudioModeForHeadphones();
  21171. }
  21172. else {
  21173. this._switchAudioModeForNormalSpeakers();
  21174. }
  21175. }
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. Scene.prototype._switchAudioModeForHeadphones = function () {
  21181. this.mainSoundTrack.switchPanningModelToHRTF();
  21182. for (var i = 0; i < this.soundTracks.length; i++) {
  21183. this.soundTracks[i].switchPanningModelToHRTF();
  21184. }
  21185. };
  21186. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21187. this.mainSoundTrack.switchPanningModelToEqualPower();
  21188. for (var i = 0; i < this.soundTracks.length; i++) {
  21189. this.soundTracks[i].switchPanningModelToEqualPower();
  21190. }
  21191. };
  21192. Scene.prototype.enableDepthRenderer = function () {
  21193. if (this._depthRenderer) {
  21194. return this._depthRenderer;
  21195. }
  21196. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21197. return this._depthRenderer;
  21198. };
  21199. Scene.prototype.disableDepthRenderer = function () {
  21200. if (!this._depthRenderer) {
  21201. return;
  21202. }
  21203. this._depthRenderer.dispose();
  21204. this._depthRenderer = null;
  21205. };
  21206. Scene.prototype.freezeMaterials = function () {
  21207. for (var i = 0; i < this.materials.length; i++) {
  21208. this.materials[i].freeze();
  21209. }
  21210. };
  21211. Scene.prototype.unfreezeMaterials = function () {
  21212. for (var i = 0; i < this.materials.length; i++) {
  21213. this.materials[i].unfreeze();
  21214. }
  21215. };
  21216. Scene.prototype.dispose = function () {
  21217. this.beforeRender = null;
  21218. this.afterRender = null;
  21219. this.skeletons = [];
  21220. this._boundingBoxRenderer.dispose();
  21221. if (this._depthRenderer) {
  21222. this._depthRenderer.dispose();
  21223. }
  21224. // Debug layer
  21225. if (this._debugLayer) {
  21226. this._debugLayer.hide();
  21227. }
  21228. // Events
  21229. this.onDisposeObservable.notifyObservers(this);
  21230. this.onDisposeObservable.clear();
  21231. this.onBeforeRenderObservable.clear();
  21232. this.onAfterRenderObservable.clear();
  21233. this.detachControl();
  21234. // Release sounds & sounds tracks
  21235. if (BABYLON.AudioEngine) {
  21236. this.disposeSounds();
  21237. }
  21238. // Detach cameras
  21239. var canvas = this._engine.getRenderingCanvas();
  21240. var index;
  21241. for (index = 0; index < this.cameras.length; index++) {
  21242. this.cameras[index].detachControl(canvas);
  21243. }
  21244. // Release lights
  21245. while (this.lights.length) {
  21246. this.lights[0].dispose();
  21247. }
  21248. // Release meshes
  21249. while (this.meshes.length) {
  21250. this.meshes[0].dispose(true);
  21251. }
  21252. // Release cameras
  21253. while (this.cameras.length) {
  21254. this.cameras[0].dispose();
  21255. }
  21256. // Release materials
  21257. while (this.materials.length) {
  21258. this.materials[0].dispose();
  21259. }
  21260. // Release particles
  21261. while (this.particleSystems.length) {
  21262. this.particleSystems[0].dispose();
  21263. }
  21264. // Release sprites
  21265. while (this.spriteManagers.length) {
  21266. this.spriteManagers[0].dispose();
  21267. }
  21268. // Release layers
  21269. while (this.layers.length) {
  21270. this.layers[0].dispose();
  21271. }
  21272. while (this.highlightLayers.length) {
  21273. this.highlightLayers[0].dispose();
  21274. }
  21275. // Release textures
  21276. while (this.textures.length) {
  21277. this.textures[0].dispose();
  21278. }
  21279. // Post-processes
  21280. this.postProcessManager.dispose();
  21281. // Physics
  21282. if (this._physicsEngine) {
  21283. this.disablePhysicsEngine();
  21284. }
  21285. // Remove from engine
  21286. index = this._engine.scenes.indexOf(this);
  21287. if (index > -1) {
  21288. this._engine.scenes.splice(index, 1);
  21289. }
  21290. this._engine.wipeCaches();
  21291. };
  21292. // Release sounds & sounds tracks
  21293. Scene.prototype.disposeSounds = function () {
  21294. this.mainSoundTrack.dispose();
  21295. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21296. this.soundTracks[scIndex].dispose();
  21297. }
  21298. };
  21299. // Octrees
  21300. Scene.prototype.getWorldExtends = function () {
  21301. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21302. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21303. for (var index = 0; index < this.meshes.length; index++) {
  21304. var mesh = this.meshes[index];
  21305. mesh.computeWorldMatrix(true);
  21306. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21307. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21308. BABYLON.Tools.CheckExtends(minBox, min, max);
  21309. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21310. }
  21311. return {
  21312. min: min,
  21313. max: max
  21314. };
  21315. };
  21316. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21317. if (maxCapacity === void 0) { maxCapacity = 64; }
  21318. if (maxDepth === void 0) { maxDepth = 2; }
  21319. if (!this._selectionOctree) {
  21320. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21321. }
  21322. var worldExtends = this.getWorldExtends();
  21323. // Update octree
  21324. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21325. return this._selectionOctree;
  21326. };
  21327. // Picking
  21328. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21329. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21330. var engine = this._engine;
  21331. if (!camera) {
  21332. if (!this.activeCamera)
  21333. throw new Error("Active camera not set");
  21334. camera = this.activeCamera;
  21335. }
  21336. var cameraViewport = camera.viewport;
  21337. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21338. // Moving coordinates to local viewport world
  21339. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21340. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21341. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21342. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21343. };
  21344. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21345. var engine = this._engine;
  21346. if (!camera) {
  21347. if (!this.activeCamera)
  21348. throw new Error("Active camera not set");
  21349. camera = this.activeCamera;
  21350. }
  21351. var cameraViewport = camera.viewport;
  21352. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21353. var identity = BABYLON.Matrix.Identity();
  21354. // Moving coordinates to local viewport world
  21355. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21356. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21357. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21358. };
  21359. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21360. var pickingInfo = null;
  21361. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21362. var mesh = this.meshes[meshIndex];
  21363. if (predicate) {
  21364. if (!predicate(mesh)) {
  21365. continue;
  21366. }
  21367. }
  21368. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21369. continue;
  21370. }
  21371. var world = mesh.getWorldMatrix();
  21372. var ray = rayFunction(world);
  21373. var result = mesh.intersects(ray, fastCheck);
  21374. if (!result || !result.hit)
  21375. continue;
  21376. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21377. continue;
  21378. pickingInfo = result;
  21379. if (fastCheck) {
  21380. break;
  21381. }
  21382. }
  21383. return pickingInfo || new BABYLON.PickingInfo();
  21384. };
  21385. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21386. var pickingInfos = new Array();
  21387. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21388. var mesh = this.meshes[meshIndex];
  21389. if (predicate) {
  21390. if (!predicate(mesh)) {
  21391. continue;
  21392. }
  21393. }
  21394. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21395. continue;
  21396. }
  21397. var world = mesh.getWorldMatrix();
  21398. var ray = rayFunction(world);
  21399. var result = mesh.intersects(ray, false);
  21400. if (!result || !result.hit)
  21401. continue;
  21402. pickingInfos.push(result);
  21403. }
  21404. return pickingInfos;
  21405. };
  21406. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21407. var pickingInfo = null;
  21408. camera = camera || this.activeCamera;
  21409. if (this.spriteManagers.length > 0) {
  21410. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21411. var spriteManager = this.spriteManagers[spriteIndex];
  21412. if (!spriteManager.isPickable) {
  21413. continue;
  21414. }
  21415. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21416. if (!result || !result.hit)
  21417. continue;
  21418. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21419. continue;
  21420. pickingInfo = result;
  21421. if (fastCheck) {
  21422. break;
  21423. }
  21424. }
  21425. }
  21426. return pickingInfo || new BABYLON.PickingInfo();
  21427. };
  21428. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21429. /// <param name="x">X position on screen</param>
  21430. /// <param name="y">Y position on screen</param>
  21431. /// <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>
  21432. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21433. /// <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>
  21434. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21435. var _this = this;
  21436. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  21437. };
  21438. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21439. /// <param name="x">X position on screen</param>
  21440. /// <param name="y">Y position on screen</param>
  21441. /// <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>
  21442. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21443. /// <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>
  21444. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21445. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  21446. };
  21447. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21448. var _this = this;
  21449. return this._internalPick(function (world) {
  21450. if (!_this._pickWithRayInverseMatrix) {
  21451. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21452. }
  21453. world.invertToRef(_this._pickWithRayInverseMatrix);
  21454. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21455. }, predicate, fastCheck);
  21456. };
  21457. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21458. /// <param name="x">X position on screen</param>
  21459. /// <param name="y">Y position on screen</param>
  21460. /// <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>
  21461. /// <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>
  21462. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21463. var _this = this;
  21464. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  21465. };
  21466. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21467. /// <param name="ray">Ray to use</param>
  21468. /// <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>
  21469. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21470. var _this = this;
  21471. return this._internalMultiPick(function (world) {
  21472. if (!_this._pickWithRayInverseMatrix) {
  21473. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21474. }
  21475. world.invertToRef(_this._pickWithRayInverseMatrix);
  21476. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21477. }, predicate);
  21478. };
  21479. Scene.prototype.setPointerOverMesh = function (mesh) {
  21480. if (this._pointerOverMesh === mesh) {
  21481. return;
  21482. }
  21483. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21484. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21485. }
  21486. this._pointerOverMesh = mesh;
  21487. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21488. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21489. }
  21490. };
  21491. Scene.prototype.getPointerOverMesh = function () {
  21492. return this._pointerOverMesh;
  21493. };
  21494. Scene.prototype.setPointerOverSprite = function (sprite) {
  21495. if (this._pointerOverSprite === sprite) {
  21496. return;
  21497. }
  21498. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21499. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21500. }
  21501. this._pointerOverSprite = sprite;
  21502. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21503. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21504. }
  21505. };
  21506. Scene.prototype.getPointerOverSprite = function () {
  21507. return this._pointerOverSprite;
  21508. };
  21509. // Physics
  21510. Scene.prototype.getPhysicsEngine = function () {
  21511. return this._physicsEngine;
  21512. };
  21513. /**
  21514. * Enables physics to the current scene
  21515. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21516. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21517. * @return {boolean} was the physics engine initialized
  21518. */
  21519. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21520. if (this._physicsEngine) {
  21521. return true;
  21522. }
  21523. try {
  21524. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21525. return true;
  21526. }
  21527. catch (e) {
  21528. BABYLON.Tools.Error(e.message);
  21529. return false;
  21530. }
  21531. };
  21532. Scene.prototype.disablePhysicsEngine = function () {
  21533. if (!this._physicsEngine) {
  21534. return;
  21535. }
  21536. this._physicsEngine.dispose();
  21537. this._physicsEngine = undefined;
  21538. };
  21539. Scene.prototype.isPhysicsEnabled = function () {
  21540. return this._physicsEngine !== undefined;
  21541. };
  21542. /**
  21543. *
  21544. * Sets the gravity of the physics engine (and NOT of the scene)
  21545. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  21546. */
  21547. Scene.prototype.setGravity = function (gravity) {
  21548. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  21549. if (!this._physicsEngine) {
  21550. return;
  21551. }
  21552. this._physicsEngine.setGravity(gravity);
  21553. };
  21554. /**
  21555. * Legacy support, using the new API
  21556. * @Deprecated
  21557. */
  21558. Scene.prototype.createCompoundImpostor = function (parts, options) {
  21559. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  21560. if (parts.parts) {
  21561. options = parts;
  21562. parts = parts.parts;
  21563. }
  21564. var mainMesh = parts[0].mesh;
  21565. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  21566. for (var index = 1; index < parts.length; index++) {
  21567. var mesh = parts[index].mesh;
  21568. if (mesh.parent !== mainMesh) {
  21569. mesh.position = mesh.position.subtract(mainMesh.position);
  21570. mesh.parent = mainMesh;
  21571. }
  21572. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  21573. }
  21574. mainMesh.physicsImpostor.forceUpdate();
  21575. };
  21576. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21577. var mesh = compound.parts[0].mesh;
  21578. mesh.physicsImpostor.dispose();
  21579. mesh.physicsImpostor = null;
  21580. };
  21581. // Misc.
  21582. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  21583. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21584. // Light
  21585. if (this.lights.length === 0) {
  21586. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21587. }
  21588. // Camera
  21589. if (!this.activeCamera) {
  21590. // Compute position
  21591. var worldExtends = this.getWorldExtends();
  21592. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  21593. var camera;
  21594. if (createArcRotateCamera) {
  21595. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  21596. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  21597. camera.setTarget(worldCenter);
  21598. }
  21599. else {
  21600. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  21601. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  21602. camera.setTarget(worldCenter);
  21603. }
  21604. this.activeCamera = camera;
  21605. }
  21606. };
  21607. // Tags
  21608. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21609. if (tagsQuery === undefined) {
  21610. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21611. return list;
  21612. }
  21613. var listByTags = [];
  21614. forEach = forEach || (function (item) { return; });
  21615. for (var i in list) {
  21616. var item = list[i];
  21617. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21618. listByTags.push(item);
  21619. forEach(item);
  21620. }
  21621. }
  21622. return listByTags;
  21623. };
  21624. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21625. return this._getByTags(this.meshes, tagsQuery, forEach);
  21626. };
  21627. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21628. return this._getByTags(this.cameras, tagsQuery, forEach);
  21629. };
  21630. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21631. return this._getByTags(this.lights, tagsQuery, forEach);
  21632. };
  21633. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21634. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21635. };
  21636. /**
  21637. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21638. * This allowed control for front to back rendering or reversly depending of the special needs.
  21639. *
  21640. * @param renderingGroupId The rendering group id corresponding to its index
  21641. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21642. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21643. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21644. */
  21645. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21646. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21647. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21648. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21649. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21650. };
  21651. /**
  21652. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21653. *
  21654. * @param renderingGroupId The rendering group id corresponding to its index
  21655. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21656. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21657. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21658. */
  21659. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21660. if (depth === void 0) { depth = true; }
  21661. if (stencil === void 0) { stencil = true; }
  21662. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21663. };
  21664. return Scene;
  21665. }());
  21666. // Statics
  21667. Scene._FOGMODE_NONE = 0;
  21668. Scene._FOGMODE_EXP = 1;
  21669. Scene._FOGMODE_EXP2 = 2;
  21670. Scene._FOGMODE_LINEAR = 3;
  21671. Scene.MinDeltaTime = 1.0;
  21672. Scene.MaxDeltaTime = 1000.0;
  21673. BABYLON.Scene = Scene;
  21674. })(BABYLON || (BABYLON = {}));
  21675. //# sourceMappingURL=babylon.scene.js.map
  21676. var BABYLON;
  21677. (function (BABYLON) {
  21678. var Buffer = (function () {
  21679. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21680. if (engine instanceof BABYLON.Mesh) {
  21681. this._engine = engine.getScene().getEngine();
  21682. }
  21683. else {
  21684. this._engine = engine;
  21685. }
  21686. this._updatable = updatable;
  21687. this._data = data;
  21688. this._strideSize = stride;
  21689. if (!postponeInternalCreation) {
  21690. this.create();
  21691. }
  21692. this._instanced = instanced;
  21693. }
  21694. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21695. // a lot of these parameters are ignored as they are overriden by the buffer
  21696. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21697. };
  21698. // Properties
  21699. Buffer.prototype.isUpdatable = function () {
  21700. return this._updatable;
  21701. };
  21702. Buffer.prototype.getData = function () {
  21703. return this._data;
  21704. };
  21705. Buffer.prototype.getBuffer = function () {
  21706. return this._buffer;
  21707. };
  21708. Buffer.prototype.getStrideSize = function () {
  21709. return this._strideSize;
  21710. };
  21711. Buffer.prototype.getIsInstanced = function () {
  21712. return this._instanced;
  21713. };
  21714. // Methods
  21715. Buffer.prototype.create = function (data) {
  21716. if (!data && this._buffer) {
  21717. return; // nothing to do
  21718. }
  21719. data = data || this._data;
  21720. if (!this._buffer) {
  21721. if (this._updatable) {
  21722. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21723. this._data = data;
  21724. }
  21725. else {
  21726. this._buffer = this._engine.createVertexBuffer(data);
  21727. }
  21728. }
  21729. else if (this._updatable) {
  21730. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21731. this._data = data;
  21732. }
  21733. };
  21734. Buffer.prototype.update = function (data) {
  21735. this.create(data);
  21736. };
  21737. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21738. if (!this._buffer) {
  21739. return;
  21740. }
  21741. if (this._updatable) {
  21742. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21743. this._data = null;
  21744. }
  21745. };
  21746. Buffer.prototype.dispose = function () {
  21747. if (!this._buffer) {
  21748. return;
  21749. }
  21750. if (this._engine._releaseBuffer(this._buffer)) {
  21751. this._buffer = null;
  21752. }
  21753. };
  21754. return Buffer;
  21755. }());
  21756. BABYLON.Buffer = Buffer;
  21757. })(BABYLON || (BABYLON = {}));
  21758. //# sourceMappingURL=babylon.buffer.js.map
  21759. var BABYLON;
  21760. (function (BABYLON) {
  21761. var VertexBuffer = (function () {
  21762. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21763. if (!stride) {
  21764. // Deduce stride from kind
  21765. switch (kind) {
  21766. case VertexBuffer.PositionKind:
  21767. stride = 3;
  21768. break;
  21769. case VertexBuffer.NormalKind:
  21770. stride = 3;
  21771. break;
  21772. case VertexBuffer.UVKind:
  21773. case VertexBuffer.UV2Kind:
  21774. case VertexBuffer.UV3Kind:
  21775. case VertexBuffer.UV4Kind:
  21776. case VertexBuffer.UV5Kind:
  21777. case VertexBuffer.UV6Kind:
  21778. stride = 2;
  21779. break;
  21780. case VertexBuffer.ColorKind:
  21781. stride = 4;
  21782. break;
  21783. case VertexBuffer.MatricesIndicesKind:
  21784. case VertexBuffer.MatricesIndicesExtraKind:
  21785. stride = 4;
  21786. break;
  21787. case VertexBuffer.MatricesWeightsKind:
  21788. case VertexBuffer.MatricesWeightsExtraKind:
  21789. stride = 4;
  21790. break;
  21791. }
  21792. }
  21793. if (data instanceof BABYLON.Buffer) {
  21794. if (!stride) {
  21795. stride = data.getStrideSize();
  21796. }
  21797. this._buffer = data;
  21798. this._ownsBuffer = false;
  21799. }
  21800. else {
  21801. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21802. this._ownsBuffer = true;
  21803. }
  21804. this._stride = stride;
  21805. this._offset = offset ? offset : 0;
  21806. this._size = size ? size : stride;
  21807. this._kind = kind;
  21808. }
  21809. /**
  21810. * Returns the kind of the VertexBuffer (string).
  21811. */
  21812. VertexBuffer.prototype.getKind = function () {
  21813. return this._kind;
  21814. };
  21815. // Properties
  21816. /**
  21817. * Boolean : is the VertexBuffer updatable ?
  21818. */
  21819. VertexBuffer.prototype.isUpdatable = function () {
  21820. return this._buffer.isUpdatable();
  21821. };
  21822. /**
  21823. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21824. */
  21825. VertexBuffer.prototype.getData = function () {
  21826. return this._buffer.getData();
  21827. };
  21828. /**
  21829. * Returns the WebGLBuffer associated to the VertexBuffer.
  21830. */
  21831. VertexBuffer.prototype.getBuffer = function () {
  21832. return this._buffer.getBuffer();
  21833. };
  21834. /**
  21835. * Returns the stride of the VertexBuffer (integer).
  21836. */
  21837. VertexBuffer.prototype.getStrideSize = function () {
  21838. return this._stride;
  21839. };
  21840. /**
  21841. * Returns the offset (integer).
  21842. */
  21843. VertexBuffer.prototype.getOffset = function () {
  21844. return this._offset;
  21845. };
  21846. /**
  21847. * Returns the VertexBuffer total size (integer).
  21848. */
  21849. VertexBuffer.prototype.getSize = function () {
  21850. return this._size;
  21851. };
  21852. /**
  21853. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21854. */
  21855. VertexBuffer.prototype.getIsInstanced = function () {
  21856. return this._buffer.getIsInstanced();
  21857. };
  21858. // Methods
  21859. /**
  21860. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21861. * Returns the created WebGLBuffer.
  21862. */
  21863. VertexBuffer.prototype.create = function (data) {
  21864. return this._buffer.create(data);
  21865. };
  21866. /**
  21867. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21868. * Returns the updated WebGLBuffer.
  21869. */
  21870. VertexBuffer.prototype.update = function (data) {
  21871. return this._buffer.update(data);
  21872. };
  21873. /**
  21874. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21875. * Returns the directly updated WebGLBuffer.
  21876. */
  21877. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21878. return this._buffer.updateDirectly(data, offset);
  21879. };
  21880. /**
  21881. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21882. */
  21883. VertexBuffer.prototype.dispose = function () {
  21884. if (this._ownsBuffer) {
  21885. this._buffer.dispose();
  21886. }
  21887. };
  21888. Object.defineProperty(VertexBuffer, "PositionKind", {
  21889. get: function () {
  21890. return VertexBuffer._PositionKind;
  21891. },
  21892. enumerable: true,
  21893. configurable: true
  21894. });
  21895. Object.defineProperty(VertexBuffer, "NormalKind", {
  21896. get: function () {
  21897. return VertexBuffer._NormalKind;
  21898. },
  21899. enumerable: true,
  21900. configurable: true
  21901. });
  21902. Object.defineProperty(VertexBuffer, "UVKind", {
  21903. get: function () {
  21904. return VertexBuffer._UVKind;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21910. get: function () {
  21911. return VertexBuffer._UV2Kind;
  21912. },
  21913. enumerable: true,
  21914. configurable: true
  21915. });
  21916. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21917. get: function () {
  21918. return VertexBuffer._UV3Kind;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21924. get: function () {
  21925. return VertexBuffer._UV4Kind;
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21931. get: function () {
  21932. return VertexBuffer._UV5Kind;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21938. get: function () {
  21939. return VertexBuffer._UV6Kind;
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Object.defineProperty(VertexBuffer, "ColorKind", {
  21945. get: function () {
  21946. return VertexBuffer._ColorKind;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21952. get: function () {
  21953. return VertexBuffer._MatricesIndicesKind;
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21959. get: function () {
  21960. return VertexBuffer._MatricesWeightsKind;
  21961. },
  21962. enumerable: true,
  21963. configurable: true
  21964. });
  21965. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21966. get: function () {
  21967. return VertexBuffer._MatricesIndicesExtraKind;
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21973. get: function () {
  21974. return VertexBuffer._MatricesWeightsExtraKind;
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. return VertexBuffer;
  21980. }());
  21981. // Enums
  21982. VertexBuffer._PositionKind = "position";
  21983. VertexBuffer._NormalKind = "normal";
  21984. VertexBuffer._UVKind = "uv";
  21985. VertexBuffer._UV2Kind = "uv2";
  21986. VertexBuffer._UV3Kind = "uv3";
  21987. VertexBuffer._UV4Kind = "uv4";
  21988. VertexBuffer._UV5Kind = "uv5";
  21989. VertexBuffer._UV6Kind = "uv6";
  21990. VertexBuffer._ColorKind = "color";
  21991. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21992. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21993. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21994. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21995. BABYLON.VertexBuffer = VertexBuffer;
  21996. })(BABYLON || (BABYLON = {}));
  21997. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21998. var BABYLON;
  21999. (function (BABYLON) {
  22000. /**
  22001. * Creates an instance based on a source mesh.
  22002. */
  22003. var InstancedMesh = (function (_super) {
  22004. __extends(InstancedMesh, _super);
  22005. function InstancedMesh(name, source) {
  22006. var _this = _super.call(this, name, source.getScene()) || this;
  22007. source.instances.push(_this);
  22008. _this._sourceMesh = source;
  22009. _this.position.copyFrom(source.position);
  22010. _this.rotation.copyFrom(source.rotation);
  22011. _this.scaling.copyFrom(source.scaling);
  22012. if (source.rotationQuaternion) {
  22013. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22014. }
  22015. _this.infiniteDistance = source.infiniteDistance;
  22016. _this.setPivotMatrix(source.getPivotMatrix());
  22017. _this.refreshBoundingInfo();
  22018. _this._syncSubMeshes();
  22019. return _this;
  22020. }
  22021. /**
  22022. * Returns the string "InstancedMesh".
  22023. */
  22024. InstancedMesh.prototype.getClassName = function () {
  22025. return "InstancedMesh";
  22026. };
  22027. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22028. // Methods
  22029. get: function () {
  22030. return this._sourceMesh.receiveShadows;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Object.defineProperty(InstancedMesh.prototype, "material", {
  22036. get: function () {
  22037. return this._sourceMesh.material;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22043. get: function () {
  22044. return this._sourceMesh.visibility;
  22045. },
  22046. enumerable: true,
  22047. configurable: true
  22048. });
  22049. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22050. get: function () {
  22051. return this._sourceMesh.skeleton;
  22052. },
  22053. enumerable: true,
  22054. configurable: true
  22055. });
  22056. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22057. get: function () {
  22058. return this._sourceMesh.renderingGroupId;
  22059. },
  22060. enumerable: true,
  22061. configurable: true
  22062. });
  22063. /**
  22064. * Returns the total number of vertices (integer).
  22065. */
  22066. InstancedMesh.prototype.getTotalVertices = function () {
  22067. return this._sourceMesh.getTotalVertices();
  22068. };
  22069. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22070. get: function () {
  22071. return this._sourceMesh;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. /**
  22077. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22078. */
  22079. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22080. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22081. };
  22082. /**
  22083. * Boolean : True if the mesh owns the requested kind of data.
  22084. */
  22085. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22086. return this._sourceMesh.isVerticesDataPresent(kind);
  22087. };
  22088. /**
  22089. * Returns an array of indices (IndicesArray).
  22090. */
  22091. InstancedMesh.prototype.getIndices = function () {
  22092. return this._sourceMesh.getIndices();
  22093. };
  22094. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22095. get: function () {
  22096. return this._sourceMesh._positions;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. /**
  22102. * Sets a new updated BoundingInfo to the mesh.
  22103. * Returns the mesh.
  22104. */
  22105. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22106. var meshBB = this._sourceMesh.getBoundingInfo();
  22107. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22108. this._updateBoundingInfo();
  22109. return this;
  22110. };
  22111. InstancedMesh.prototype._preActivate = function () {
  22112. if (this._currentLOD) {
  22113. this._currentLOD._preActivate();
  22114. }
  22115. return this;
  22116. };
  22117. InstancedMesh.prototype._activate = function (renderId) {
  22118. if (this._currentLOD) {
  22119. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22120. }
  22121. return this;
  22122. };
  22123. /**
  22124. * Returns the current associated LOD AbstractMesh.
  22125. */
  22126. InstancedMesh.prototype.getLOD = function (camera) {
  22127. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22128. if (this._currentLOD === this.sourceMesh) {
  22129. return this;
  22130. }
  22131. return this._currentLOD;
  22132. };
  22133. InstancedMesh.prototype._syncSubMeshes = function () {
  22134. this.releaseSubMeshes();
  22135. if (this._sourceMesh.subMeshes) {
  22136. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22137. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22138. }
  22139. }
  22140. return this;
  22141. };
  22142. InstancedMesh.prototype._generatePointsArray = function () {
  22143. return this._sourceMesh._generatePointsArray();
  22144. };
  22145. /**
  22146. * Creates a new InstancedMesh from the current mesh.
  22147. * - name (string) : the cloned mesh name
  22148. * - newParent (optional Node) : the optional Node to parent the clone to.
  22149. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22150. *
  22151. * Returns the clone.
  22152. */
  22153. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22154. var result = this._sourceMesh.createInstance(name);
  22155. // Deep copy
  22156. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  22157. // Bounding info
  22158. this.refreshBoundingInfo();
  22159. // Parent
  22160. if (newParent) {
  22161. result.parent = newParent;
  22162. }
  22163. if (!doNotCloneChildren) {
  22164. // Children
  22165. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22166. var mesh = this.getScene().meshes[index];
  22167. if (mesh.parent === this) {
  22168. mesh.clone(mesh.name, result);
  22169. }
  22170. }
  22171. }
  22172. result.computeWorldMatrix(true);
  22173. return result;
  22174. };
  22175. /**
  22176. * Disposes the InstancedMesh.
  22177. * Returns nothing.
  22178. */
  22179. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22180. // Remove from mesh
  22181. var index = this._sourceMesh.instances.indexOf(this);
  22182. this._sourceMesh.instances.splice(index, 1);
  22183. _super.prototype.dispose.call(this, doNotRecurse);
  22184. };
  22185. return InstancedMesh;
  22186. }(BABYLON.AbstractMesh));
  22187. BABYLON.InstancedMesh = InstancedMesh;
  22188. })(BABYLON || (BABYLON = {}));
  22189. //# sourceMappingURL=babylon.instancedMesh.js.map
  22190. var BABYLON;
  22191. (function (BABYLON) {
  22192. var _InstancesBatch = (function () {
  22193. function _InstancesBatch() {
  22194. this.mustReturn = false;
  22195. this.visibleInstances = new Array();
  22196. this.renderSelf = new Array();
  22197. }
  22198. return _InstancesBatch;
  22199. }());
  22200. BABYLON._InstancesBatch = _InstancesBatch;
  22201. var Mesh = (function (_super) {
  22202. __extends(Mesh, _super);
  22203. /**
  22204. * @constructor
  22205. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22206. * @param {Scene} scene The scene to add this mesh to.
  22207. * @param {Node} parent The parent of this mesh, if it has one
  22208. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22209. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22210. * When false, achieved by calling a clone(), also passing False.
  22211. * This will make creation of children, recursive.
  22212. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22213. */
  22214. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22215. if (parent === void 0) { parent = null; }
  22216. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22217. var _this = _super.call(this, name, scene) || this;
  22218. // Events
  22219. /**
  22220. * An event triggered before rendering the mesh
  22221. * @type {BABYLON.Observable}
  22222. */
  22223. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22224. /**
  22225. * An event triggered after rendering the mesh
  22226. * @type {BABYLON.Observable}
  22227. */
  22228. _this.onAfterRenderObservable = new BABYLON.Observable();
  22229. /**
  22230. * An event triggered before drawing the mesh
  22231. * @type {BABYLON.Observable}
  22232. */
  22233. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22234. // Members
  22235. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22236. _this.instances = new Array();
  22237. _this._LODLevels = new Array();
  22238. _this._visibleInstances = {};
  22239. _this._renderIdForInstances = new Array();
  22240. _this._batchCache = new _InstancesBatch();
  22241. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22242. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22243. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22244. // Will be used to save a source mesh reference, If any
  22245. _this._source = null;
  22246. if (source) {
  22247. // Source mesh
  22248. _this._source = source;
  22249. // Geometry
  22250. if (source._geometry) {
  22251. source._geometry.applyToMesh(_this);
  22252. }
  22253. // Deep copy
  22254. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  22255. // Parent
  22256. _this.parent = source.parent;
  22257. // Pivot
  22258. _this.setPivotMatrix(source.getPivotMatrix());
  22259. _this.id = name + "." + source.id;
  22260. // Material
  22261. _this.material = source.material;
  22262. var index;
  22263. if (!doNotCloneChildren) {
  22264. // Children
  22265. for (index = 0; index < scene.meshes.length; index++) {
  22266. var mesh = scene.meshes[index];
  22267. if (mesh.parent === source) {
  22268. // doNotCloneChildren is always going to be False
  22269. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22270. }
  22271. }
  22272. }
  22273. // Physics clone
  22274. var physicsEngine = _this.getScene().getPhysicsEngine();
  22275. if (clonePhysicsImpostor && physicsEngine) {
  22276. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22277. if (impostor) {
  22278. _this.physicsImpostor = impostor.clone(_this);
  22279. }
  22280. }
  22281. // Particles
  22282. for (index = 0; index < scene.particleSystems.length; index++) {
  22283. var system = scene.particleSystems[index];
  22284. if (system.emitter === source) {
  22285. system.clone(system.name, _this);
  22286. }
  22287. }
  22288. _this.computeWorldMatrix(true);
  22289. }
  22290. // Parent
  22291. if (parent !== null) {
  22292. _this.parent = parent;
  22293. }
  22294. return _this;
  22295. }
  22296. Object.defineProperty(Mesh, "FRONTSIDE", {
  22297. /**
  22298. * Mesh side orientation : usually the external or front surface
  22299. */
  22300. get: function () {
  22301. return Mesh._FRONTSIDE;
  22302. },
  22303. enumerable: true,
  22304. configurable: true
  22305. });
  22306. Object.defineProperty(Mesh, "BACKSIDE", {
  22307. /**
  22308. * Mesh side orientation : usually the internal or back surface
  22309. */
  22310. get: function () {
  22311. return Mesh._BACKSIDE;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22317. /**
  22318. * Mesh side orientation : both internal and external or front and back surfaces
  22319. */
  22320. get: function () {
  22321. return Mesh._DOUBLESIDE;
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22327. /**
  22328. * Mesh side orientation : by default, `FRONTSIDE`
  22329. */
  22330. get: function () {
  22331. return Mesh._DEFAULTSIDE;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Object.defineProperty(Mesh, "NO_CAP", {
  22337. /**
  22338. * Mesh cap setting : no cap
  22339. */
  22340. get: function () {
  22341. return Mesh._NO_CAP;
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. Object.defineProperty(Mesh, "CAP_START", {
  22347. /**
  22348. * Mesh cap setting : one cap at the beginning of the mesh
  22349. */
  22350. get: function () {
  22351. return Mesh._CAP_START;
  22352. },
  22353. enumerable: true,
  22354. configurable: true
  22355. });
  22356. Object.defineProperty(Mesh, "CAP_END", {
  22357. /**
  22358. * Mesh cap setting : one cap at the end of the mesh
  22359. */
  22360. get: function () {
  22361. return Mesh._CAP_END;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Object.defineProperty(Mesh, "CAP_ALL", {
  22367. /**
  22368. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22369. */
  22370. get: function () {
  22371. return Mesh._CAP_ALL;
  22372. },
  22373. enumerable: true,
  22374. configurable: true
  22375. });
  22376. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22377. set: function (callback) {
  22378. if (this._onBeforeDrawObserver) {
  22379. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22380. }
  22381. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(Mesh.prototype, "source", {
  22387. get: function () {
  22388. return this._source;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. // Methods
  22394. /**
  22395. * Returns the string "Mesh".
  22396. */
  22397. Mesh.prototype.getClassName = function () {
  22398. return "Mesh";
  22399. };
  22400. /**
  22401. * Returns a string.
  22402. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22403. */
  22404. Mesh.prototype.toString = function (fullDetails) {
  22405. var ret = _super.prototype.toString.call(this, fullDetails);
  22406. ret += ", n vertices: " + this.getTotalVertices();
  22407. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22408. if (this.animations) {
  22409. for (var i = 0; i < this.animations.length; i++) {
  22410. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22411. }
  22412. }
  22413. if (fullDetails) {
  22414. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22415. }
  22416. return ret;
  22417. };
  22418. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22419. /**
  22420. * True if the mesh has some Levels Of Details (LOD).
  22421. * Returns a boolean.
  22422. */
  22423. get: function () {
  22424. return this._LODLevels.length > 0;
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Mesh.prototype._sortLODLevels = function () {
  22430. this._LODLevels.sort(function (a, b) {
  22431. if (a.distance < b.distance) {
  22432. return 1;
  22433. }
  22434. if (a.distance > b.distance) {
  22435. return -1;
  22436. }
  22437. return 0;
  22438. });
  22439. };
  22440. /**
  22441. * Add a mesh as LOD level triggered at the given distance.
  22442. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22443. * @param {number} distance The distance from the center of the object to show this level
  22444. * @param {Mesh} mesh The mesh to be added as LOD level
  22445. * @return {Mesh} This mesh (for chaining)
  22446. */
  22447. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22448. if (mesh && mesh._masterMesh) {
  22449. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22450. return this;
  22451. }
  22452. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22453. this._LODLevels.push(level);
  22454. if (mesh) {
  22455. mesh._masterMesh = this;
  22456. }
  22457. this._sortLODLevels();
  22458. return this;
  22459. };
  22460. /**
  22461. * Returns the LOD level mesh at the passed distance or null if not found.
  22462. * It is related to the method `addLODLevel(distance, mesh)`.
  22463. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22464. * Returns an object Mesh or `null`.
  22465. */
  22466. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22467. for (var index = 0; index < this._LODLevels.length; index++) {
  22468. var level = this._LODLevels[index];
  22469. if (level.distance === distance) {
  22470. return level.mesh;
  22471. }
  22472. }
  22473. return null;
  22474. };
  22475. /**
  22476. * Remove a mesh from the LOD array
  22477. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22478. * @param {Mesh} mesh The mesh to be removed.
  22479. * @return {Mesh} This mesh (for chaining)
  22480. */
  22481. Mesh.prototype.removeLODLevel = function (mesh) {
  22482. for (var index = 0; index < this._LODLevels.length; index++) {
  22483. if (this._LODLevels[index].mesh === mesh) {
  22484. this._LODLevels.splice(index, 1);
  22485. if (mesh) {
  22486. mesh._masterMesh = null;
  22487. }
  22488. }
  22489. }
  22490. this._sortLODLevels();
  22491. return this;
  22492. };
  22493. /**
  22494. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22495. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22496. */
  22497. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22498. if (!this._LODLevels || this._LODLevels.length === 0) {
  22499. return this;
  22500. }
  22501. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  22502. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22503. if (this.onLODLevelSelection) {
  22504. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22505. }
  22506. return this;
  22507. }
  22508. for (var index = 0; index < this._LODLevels.length; index++) {
  22509. var level = this._LODLevels[index];
  22510. if (level.distance < distanceToCamera) {
  22511. if (level.mesh) {
  22512. level.mesh._preActivate();
  22513. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22514. }
  22515. if (this.onLODLevelSelection) {
  22516. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22517. }
  22518. return level.mesh;
  22519. }
  22520. }
  22521. if (this.onLODLevelSelection) {
  22522. this.onLODLevelSelection(distanceToCamera, this, this);
  22523. }
  22524. return this;
  22525. };
  22526. Object.defineProperty(Mesh.prototype, "geometry", {
  22527. /**
  22528. * Returns the mesh internal Geometry object.
  22529. */
  22530. get: function () {
  22531. return this._geometry;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. /**
  22537. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22538. */
  22539. Mesh.prototype.getTotalVertices = function () {
  22540. if (!this._geometry) {
  22541. return 0;
  22542. }
  22543. return this._geometry.getTotalVertices();
  22544. };
  22545. /**
  22546. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22547. * 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.
  22548. * Returns null if the mesh has no geometry or no vertex buffer.
  22549. * Possible `kind` values :
  22550. * - BABYLON.VertexBuffer.PositionKind
  22551. * - BABYLON.VertexBuffer.UVKind
  22552. * - BABYLON.VertexBuffer.UV2Kind
  22553. * - BABYLON.VertexBuffer.UV3Kind
  22554. * - BABYLON.VertexBuffer.UV4Kind
  22555. * - BABYLON.VertexBuffer.UV5Kind
  22556. * - BABYLON.VertexBuffer.UV6Kind
  22557. * - BABYLON.VertexBuffer.ColorKind
  22558. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22559. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22560. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22561. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22562. */
  22563. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22564. if (!this._geometry) {
  22565. return null;
  22566. }
  22567. return this._geometry.getVerticesData(kind, copyWhenShared);
  22568. };
  22569. /**
  22570. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22571. * Returns `undefined` if the mesh has no geometry.
  22572. * Possible `kind` values :
  22573. * - BABYLON.VertexBuffer.PositionKind
  22574. * - BABYLON.VertexBuffer.UVKind
  22575. * - BABYLON.VertexBuffer.UV2Kind
  22576. * - BABYLON.VertexBuffer.UV3Kind
  22577. * - BABYLON.VertexBuffer.UV4Kind
  22578. * - BABYLON.VertexBuffer.UV5Kind
  22579. * - BABYLON.VertexBuffer.UV6Kind
  22580. * - BABYLON.VertexBuffer.ColorKind
  22581. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22582. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22583. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22584. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22585. */
  22586. Mesh.prototype.getVertexBuffer = function (kind) {
  22587. if (!this._geometry) {
  22588. return undefined;
  22589. }
  22590. return this._geometry.getVertexBuffer(kind);
  22591. };
  22592. /**
  22593. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22594. * Possible `kind` values :
  22595. * - BABYLON.VertexBuffer.PositionKind
  22596. * - BABYLON.VertexBuffer.UVKind
  22597. * - BABYLON.VertexBuffer.UV2Kind
  22598. * - BABYLON.VertexBuffer.UV3Kind
  22599. * - BABYLON.VertexBuffer.UV4Kind
  22600. * - BABYLON.VertexBuffer.UV5Kind
  22601. * - BABYLON.VertexBuffer.UV6Kind
  22602. * - BABYLON.VertexBuffer.ColorKind
  22603. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22604. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22605. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22606. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22607. */
  22608. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22609. if (!this._geometry) {
  22610. if (this._delayInfo) {
  22611. return this._delayInfo.indexOf(kind) !== -1;
  22612. }
  22613. return false;
  22614. }
  22615. return this._geometry.isVerticesDataPresent(kind);
  22616. };
  22617. /**
  22618. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22619. * Possible `kind` values :
  22620. * - BABYLON.VertexBuffer.PositionKind
  22621. * - BABYLON.VertexBuffer.UVKind
  22622. * - BABYLON.VertexBuffer.UV2Kind
  22623. * - BABYLON.VertexBuffer.UV3Kind
  22624. * - BABYLON.VertexBuffer.UV4Kind
  22625. * - BABYLON.VertexBuffer.UV5Kind
  22626. * - BABYLON.VertexBuffer.UV6Kind
  22627. * - BABYLON.VertexBuffer.ColorKind
  22628. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22629. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22630. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22631. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22632. */
  22633. Mesh.prototype.getVerticesDataKinds = function () {
  22634. if (!this._geometry) {
  22635. var result = [];
  22636. if (this._delayInfo) {
  22637. this._delayInfo.forEach(function (kind, index, array) {
  22638. result.push(kind);
  22639. });
  22640. }
  22641. return result;
  22642. }
  22643. return this._geometry.getVerticesDataKinds();
  22644. };
  22645. /**
  22646. * Returns a positive integer : the total number of indices in this mesh geometry.
  22647. * Returns zero if the mesh has no geometry.
  22648. */
  22649. Mesh.prototype.getTotalIndices = function () {
  22650. if (!this._geometry) {
  22651. return 0;
  22652. }
  22653. return this._geometry.getTotalIndices();
  22654. };
  22655. /**
  22656. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22657. * 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.
  22658. * Returns an empty array if the mesh has no geometry.
  22659. */
  22660. Mesh.prototype.getIndices = function (copyWhenShared) {
  22661. if (!this._geometry) {
  22662. return [];
  22663. }
  22664. return this._geometry.getIndices(copyWhenShared);
  22665. };
  22666. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22667. get: function () {
  22668. return this._masterMesh !== null && this._masterMesh !== undefined;
  22669. },
  22670. enumerable: true,
  22671. configurable: true
  22672. });
  22673. /**
  22674. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22675. */
  22676. Mesh.prototype.isReady = function () {
  22677. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22678. return false;
  22679. }
  22680. return _super.prototype.isReady.call(this);
  22681. };
  22682. /**
  22683. * Boolean : true if the mesh has been disposed.
  22684. */
  22685. Mesh.prototype.isDisposed = function () {
  22686. return this._isDisposed;
  22687. };
  22688. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  22689. get: function () {
  22690. return this._sideOrientation;
  22691. },
  22692. /**
  22693. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  22694. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  22695. */
  22696. set: function (sideO) {
  22697. this._sideOrientation = sideO;
  22698. },
  22699. enumerable: true,
  22700. configurable: true
  22701. });
  22702. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22703. /**
  22704. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22705. * This property is pertinent only for updatable parametric shapes.
  22706. */
  22707. get: function () {
  22708. return this._areNormalsFrozen;
  22709. },
  22710. enumerable: true,
  22711. configurable: true
  22712. });
  22713. /**
  22714. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22715. * It has no effect at all on other shapes.
  22716. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22717. * Returns the Mesh.
  22718. */
  22719. Mesh.prototype.freezeNormals = function () {
  22720. this._areNormalsFrozen = true;
  22721. return this;
  22722. };
  22723. /**
  22724. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22725. * It has no effect at all on other shapes.
  22726. * It reactivates the mesh normals computation if it was previously frozen.
  22727. * Returns the Mesh.
  22728. */
  22729. Mesh.prototype.unfreezeNormals = function () {
  22730. this._areNormalsFrozen = false;
  22731. return this;
  22732. };
  22733. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22734. /**
  22735. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22736. */
  22737. set: function (count) {
  22738. this._overridenInstanceCount = count;
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. // Methods
  22744. Mesh.prototype._preActivate = function () {
  22745. var sceneRenderId = this.getScene().getRenderId();
  22746. if (this._preActivateId === sceneRenderId) {
  22747. return this;
  22748. }
  22749. this._preActivateId = sceneRenderId;
  22750. this._visibleInstances = null;
  22751. return this;
  22752. };
  22753. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22754. if (this._visibleInstances) {
  22755. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22756. }
  22757. return this;
  22758. };
  22759. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22760. if (!this._visibleInstances) {
  22761. this._visibleInstances = {};
  22762. this._visibleInstances.defaultRenderId = renderId;
  22763. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22764. }
  22765. if (!this._visibleInstances[renderId]) {
  22766. this._visibleInstances[renderId] = new Array();
  22767. }
  22768. this._visibleInstances[renderId].push(instance);
  22769. return this;
  22770. };
  22771. /**
  22772. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22773. * This means the mesh underlying bounding box and sphere are recomputed.
  22774. * Returns the Mesh.
  22775. */
  22776. Mesh.prototype.refreshBoundingInfo = function () {
  22777. if (this._boundingInfo.isLocked) {
  22778. return;
  22779. }
  22780. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22781. if (data) {
  22782. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22783. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22784. }
  22785. if (this.subMeshes) {
  22786. for (var index = 0; index < this.subMeshes.length; index++) {
  22787. this.subMeshes[index].refreshBoundingInfo();
  22788. }
  22789. }
  22790. this._updateBoundingInfo();
  22791. return this;
  22792. };
  22793. Mesh.prototype._createGlobalSubMesh = function () {
  22794. var totalVertices = this.getTotalVertices();
  22795. if (!totalVertices || !this.getIndices()) {
  22796. return null;
  22797. }
  22798. this.releaseSubMeshes();
  22799. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22800. };
  22801. Mesh.prototype.subdivide = function (count) {
  22802. if (count < 1) {
  22803. return;
  22804. }
  22805. var totalIndices = this.getTotalIndices();
  22806. var subdivisionSize = (totalIndices / count) | 0;
  22807. var offset = 0;
  22808. // Ensure that subdivisionSize is a multiple of 3
  22809. while (subdivisionSize % 3 !== 0) {
  22810. subdivisionSize++;
  22811. }
  22812. this.releaseSubMeshes();
  22813. for (var index = 0; index < count; index++) {
  22814. if (offset >= totalIndices) {
  22815. break;
  22816. }
  22817. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22818. offset += subdivisionSize;
  22819. }
  22820. this.synchronizeInstances();
  22821. };
  22822. /**
  22823. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22824. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22825. * The `data` are either a numeric array either a Float32Array.
  22826. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22827. * 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).
  22828. * Note that a new underlying VertexBuffer object is created each call.
  22829. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22830. *
  22831. * Possible `kind` values :
  22832. * - BABYLON.VertexBuffer.PositionKind
  22833. * - BABYLON.VertexBuffer.UVKind
  22834. * - BABYLON.VertexBuffer.UV2Kind
  22835. * - BABYLON.VertexBuffer.UV3Kind
  22836. * - BABYLON.VertexBuffer.UV4Kind
  22837. * - BABYLON.VertexBuffer.UV5Kind
  22838. * - BABYLON.VertexBuffer.UV6Kind
  22839. * - BABYLON.VertexBuffer.ColorKind
  22840. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22841. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22842. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22843. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22844. *
  22845. * Returns the Mesh.
  22846. */
  22847. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22848. if (!this._geometry) {
  22849. var vertexData = new BABYLON.VertexData();
  22850. vertexData.set(data, kind);
  22851. var scene = this.getScene();
  22852. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22853. }
  22854. else {
  22855. this._geometry.setVerticesData(kind, data, updatable, stride);
  22856. }
  22857. return this;
  22858. };
  22859. /**
  22860. * Sets the mesh VertexBuffer.
  22861. * Returns the Mesh.
  22862. */
  22863. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22864. if (!this._geometry) {
  22865. var scene = this.getScene();
  22866. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22867. }
  22868. this._geometry.setVerticesBuffer(buffer);
  22869. return this;
  22870. };
  22871. /**
  22872. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22873. * If the mesh has no geometry, it is simply returned as it is.
  22874. * The `data` are either a numeric array either a Float32Array.
  22875. * No new underlying VertexBuffer object is created.
  22876. * 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.
  22877. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22878. *
  22879. * Possible `kind` values :
  22880. * - BABYLON.VertexBuffer.PositionKind
  22881. * - BABYLON.VertexBuffer.UVKind
  22882. * - BABYLON.VertexBuffer.UV2Kind
  22883. * - BABYLON.VertexBuffer.UV3Kind
  22884. * - BABYLON.VertexBuffer.UV4Kind
  22885. * - BABYLON.VertexBuffer.UV5Kind
  22886. * - BABYLON.VertexBuffer.UV6Kind
  22887. * - BABYLON.VertexBuffer.ColorKind
  22888. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22889. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22890. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22891. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22892. *
  22893. * Returns the Mesh.
  22894. */
  22895. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22896. if (!this._geometry) {
  22897. return;
  22898. }
  22899. if (!makeItUnique) {
  22900. this._geometry.updateVerticesData(kind, data, updateExtends);
  22901. }
  22902. else {
  22903. this.makeGeometryUnique();
  22904. this.updateVerticesData(kind, data, updateExtends, false);
  22905. }
  22906. return this;
  22907. };
  22908. /**
  22909. * Deprecated since BabylonJS v2.3
  22910. */
  22911. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  22912. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  22913. if (!this._geometry) {
  22914. return;
  22915. }
  22916. if (!makeItUnique) {
  22917. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  22918. }
  22919. else {
  22920. this.makeGeometryUnique();
  22921. this.updateVerticesDataDirectly(kind, data, offset, false);
  22922. }
  22923. };
  22924. /**
  22925. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22926. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22927. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22928. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22929. * Returns the Mesh.
  22930. */
  22931. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22932. if (computeNormals === void 0) { computeNormals = true; }
  22933. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22934. positionFunction(positions);
  22935. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22936. if (computeNormals) {
  22937. var indices = this.getIndices();
  22938. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22939. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22940. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22941. }
  22942. return this;
  22943. };
  22944. /**
  22945. * Creates a un-shared specific occurence of the geometry for the mesh.
  22946. * Returns the Mesh.
  22947. */
  22948. Mesh.prototype.makeGeometryUnique = function () {
  22949. if (!this._geometry) {
  22950. return;
  22951. }
  22952. var oldGeometry = this._geometry;
  22953. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22954. oldGeometry.releaseForMesh(this, true);
  22955. geometry.applyToMesh(this);
  22956. return this;
  22957. };
  22958. /**
  22959. * Sets the mesh indices.
  22960. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22961. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22962. * This method creates a new index buffer each call.
  22963. * Returns the Mesh.
  22964. */
  22965. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22966. if (!this._geometry) {
  22967. var vertexData = new BABYLON.VertexData();
  22968. vertexData.indices = indices;
  22969. var scene = this.getScene();
  22970. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22971. }
  22972. else {
  22973. this._geometry.setIndices(indices, totalVertices);
  22974. }
  22975. return this;
  22976. };
  22977. /**
  22978. * Invert the geometry to move from a right handed system to a left handed one.
  22979. * Returns the Mesh.
  22980. */
  22981. Mesh.prototype.toLeftHanded = function () {
  22982. if (!this._geometry) {
  22983. return;
  22984. }
  22985. this._geometry.toLeftHanded();
  22986. return this;
  22987. };
  22988. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22989. var engine = this.getScene().getEngine();
  22990. // Wireframe
  22991. var indexToBind;
  22992. if (this._unIndexed) {
  22993. indexToBind = null;
  22994. }
  22995. else {
  22996. switch (fillMode) {
  22997. case BABYLON.Material.PointFillMode:
  22998. indexToBind = null;
  22999. break;
  23000. case BABYLON.Material.WireFrameFillMode:
  23001. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23002. break;
  23003. default:
  23004. case BABYLON.Material.TriangleFillMode:
  23005. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23006. break;
  23007. }
  23008. }
  23009. // VBOs
  23010. this._geometry._bind(effect, indexToBind);
  23011. return this;
  23012. };
  23013. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23014. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23015. return this;
  23016. }
  23017. this.onBeforeDrawObservable.notifyObservers(this);
  23018. var engine = this.getScene().getEngine();
  23019. // Draw order
  23020. switch (fillMode) {
  23021. case BABYLON.Material.PointFillMode:
  23022. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23023. break;
  23024. case BABYLON.Material.WireFrameFillMode:
  23025. if (this._unIndexed) {
  23026. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23027. }
  23028. else {
  23029. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23030. }
  23031. break;
  23032. default:
  23033. if (this._unIndexed) {
  23034. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23035. }
  23036. else {
  23037. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23038. }
  23039. }
  23040. return this;
  23041. };
  23042. /**
  23043. * Registers for this mesh a javascript function called just before the rendering process.
  23044. * This function is passed the current mesh.
  23045. * Return the Mesh.
  23046. */
  23047. Mesh.prototype.registerBeforeRender = function (func) {
  23048. this.onBeforeRenderObservable.add(func);
  23049. return this;
  23050. };
  23051. /**
  23052. * Disposes a previously registered javascript function called before the rendering.
  23053. * This function is passed the current mesh.
  23054. * Returns the Mesh.
  23055. */
  23056. Mesh.prototype.unregisterBeforeRender = function (func) {
  23057. this.onBeforeRenderObservable.removeCallback(func);
  23058. return this;
  23059. };
  23060. /**
  23061. * Registers for this mesh a javascript function called just after the rendering is complete.
  23062. * This function is passed the current mesh.
  23063. * Returns the Mesh.
  23064. */
  23065. Mesh.prototype.registerAfterRender = function (func) {
  23066. this.onAfterRenderObservable.add(func);
  23067. return this;
  23068. };
  23069. /**
  23070. * Disposes a previously registered javascript function called after the rendering.
  23071. * This function is passed the current mesh.
  23072. * Return the Mesh.
  23073. */
  23074. Mesh.prototype.unregisterAfterRender = function (func) {
  23075. this.onAfterRenderObservable.removeCallback(func);
  23076. return this;
  23077. };
  23078. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23079. var scene = this.getScene();
  23080. this._batchCache.mustReturn = false;
  23081. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23082. this._batchCache.visibleInstances[subMeshId] = null;
  23083. if (this._visibleInstances) {
  23084. var currentRenderId = scene.getRenderId();
  23085. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23086. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23087. var selfRenderId = this._renderId;
  23088. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23089. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23090. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23091. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23092. }
  23093. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23094. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23095. this._batchCache.mustReturn = true;
  23096. return this._batchCache;
  23097. }
  23098. if (currentRenderId !== selfRenderId) {
  23099. this._batchCache.renderSelf[subMeshId] = false;
  23100. }
  23101. }
  23102. this._renderIdForInstances[subMeshId] = currentRenderId;
  23103. }
  23104. return this._batchCache;
  23105. };
  23106. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23107. var visibleInstances = batch.visibleInstances[subMesh._id];
  23108. var matricesCount = visibleInstances.length + 1;
  23109. var bufferSize = matricesCount * 16 * 4;
  23110. var currentInstancesBufferSize = this._instancesBufferSize;
  23111. var instancesBuffer = this._instancesBuffer;
  23112. while (this._instancesBufferSize < bufferSize) {
  23113. this._instancesBufferSize *= 2;
  23114. }
  23115. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23116. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23117. }
  23118. var offset = 0;
  23119. var instancesCount = 0;
  23120. var world = this.getWorldMatrix();
  23121. if (batch.renderSelf[subMesh._id]) {
  23122. world.copyToArray(this._instancesData, offset);
  23123. offset += 16;
  23124. instancesCount++;
  23125. }
  23126. if (visibleInstances) {
  23127. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23128. var instance = visibleInstances[instanceIndex];
  23129. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23130. offset += 16;
  23131. instancesCount++;
  23132. }
  23133. }
  23134. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23135. if (instancesBuffer) {
  23136. instancesBuffer.dispose();
  23137. }
  23138. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23139. this._instancesBuffer = instancesBuffer;
  23140. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23141. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23142. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23143. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23144. }
  23145. else {
  23146. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23147. }
  23148. this.geometry._bind(effect);
  23149. this._draw(subMesh, fillMode, instancesCount);
  23150. engine.unbindInstanceAttributes();
  23151. return this;
  23152. };
  23153. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23154. var scene = this.getScene();
  23155. var engine = scene.getEngine();
  23156. if (hardwareInstancedRendering) {
  23157. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23158. }
  23159. else {
  23160. if (batch.renderSelf[subMesh._id]) {
  23161. // Draw
  23162. if (onBeforeDraw) {
  23163. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23164. }
  23165. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23166. }
  23167. if (batch.visibleInstances[subMesh._id]) {
  23168. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23169. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23170. // World
  23171. var world = instance.getWorldMatrix();
  23172. if (onBeforeDraw) {
  23173. onBeforeDraw(true, world, effectiveMaterial);
  23174. }
  23175. // Draw
  23176. this._draw(subMesh, fillMode);
  23177. }
  23178. }
  23179. }
  23180. return this;
  23181. };
  23182. /**
  23183. * Triggers the draw call for the mesh.
  23184. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23185. * Returns the Mesh.
  23186. */
  23187. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23188. var scene = this.getScene();
  23189. // Managing instances
  23190. var batch = this._getInstancesRenderList(subMesh._id);
  23191. if (batch.mustReturn) {
  23192. return this;
  23193. }
  23194. // Checking geometry state
  23195. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23196. return this;
  23197. }
  23198. var callbackIndex;
  23199. this.onBeforeRenderObservable.notifyObservers(this);
  23200. var engine = scene.getEngine();
  23201. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23202. // Material
  23203. var effectiveMaterial = subMesh.getMaterial();
  23204. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23205. return this;
  23206. }
  23207. // Outline - step 1
  23208. var savedDepthWrite = engine.getDepthWrite();
  23209. if (this.renderOutline) {
  23210. engine.setDepthWrite(false);
  23211. scene.getOutlineRenderer().render(subMesh, batch);
  23212. engine.setDepthWrite(savedDepthWrite);
  23213. }
  23214. effectiveMaterial._preBind();
  23215. var effect = effectiveMaterial.getEffect();
  23216. // Bind
  23217. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23218. this._bind(subMesh, effect, fillMode);
  23219. var world = this.getWorldMatrix();
  23220. effectiveMaterial.bind(world, this);
  23221. // Alpha mode
  23222. if (enableAlphaMode) {
  23223. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23224. }
  23225. // Draw
  23226. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23227. // Unbind
  23228. effectiveMaterial.unbind();
  23229. // Outline - step 2
  23230. if (this.renderOutline && savedDepthWrite) {
  23231. engine.setDepthWrite(true);
  23232. engine.setColorWrite(false);
  23233. scene.getOutlineRenderer().render(subMesh, batch);
  23234. engine.setColorWrite(true);
  23235. }
  23236. // Overlay
  23237. if (this.renderOverlay) {
  23238. var currentMode = engine.getAlphaMode();
  23239. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23240. scene.getOutlineRenderer().render(subMesh, batch, true);
  23241. engine.setAlphaMode(currentMode);
  23242. }
  23243. this.onAfterRenderObservable.notifyObservers(this);
  23244. return this;
  23245. };
  23246. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23247. if (isInstance) {
  23248. effectiveMaterial.bindOnlyWorldMatrix(world);
  23249. }
  23250. return this;
  23251. };
  23252. /**
  23253. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23254. */
  23255. Mesh.prototype.getEmittedParticleSystems = function () {
  23256. var results = new Array();
  23257. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23258. var particleSystem = this.getScene().particleSystems[index];
  23259. if (particleSystem.emitter === this) {
  23260. results.push(particleSystem);
  23261. }
  23262. }
  23263. return results;
  23264. };
  23265. /**
  23266. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23267. */
  23268. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23269. var results = new Array();
  23270. var descendants = this.getDescendants();
  23271. descendants.push(this);
  23272. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23273. var particleSystem = this.getScene().particleSystems[index];
  23274. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23275. results.push(particleSystem);
  23276. }
  23277. }
  23278. return results;
  23279. };
  23280. Mesh.prototype._checkDelayState = function () {
  23281. var scene = this.getScene();
  23282. if (this._geometry) {
  23283. this._geometry.load(scene);
  23284. }
  23285. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23287. this._queueLoad(this, scene);
  23288. }
  23289. return this;
  23290. };
  23291. Mesh.prototype._queueLoad = function (mesh, scene) {
  23292. var _this = this;
  23293. scene._addPendingData(mesh);
  23294. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23295. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23296. if (data instanceof ArrayBuffer) {
  23297. _this._delayLoadingFunction(data, _this);
  23298. }
  23299. else {
  23300. _this._delayLoadingFunction(JSON.parse(data), _this);
  23301. }
  23302. _this.instances.forEach(function (instance) {
  23303. instance._syncSubMeshes();
  23304. });
  23305. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23306. scene._removePendingData(_this);
  23307. }, function () { }, scene.database, getBinaryData);
  23308. return this;
  23309. };
  23310. /**
  23311. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23312. */
  23313. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23314. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23315. return false;
  23316. }
  23317. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23318. return false;
  23319. }
  23320. this._checkDelayState();
  23321. return true;
  23322. };
  23323. /**
  23324. * Sets the mesh material by the material or multiMaterial `id` property.
  23325. * The material `id` is a string identifying the material or the multiMaterial.
  23326. * This method returns the Mesh.
  23327. */
  23328. Mesh.prototype.setMaterialByID = function (id) {
  23329. var materials = this.getScene().materials;
  23330. var index;
  23331. for (index = 0; index < materials.length; index++) {
  23332. if (materials[index].id === id) {
  23333. this.material = materials[index];
  23334. return this;
  23335. }
  23336. }
  23337. // Multi
  23338. var multiMaterials = this.getScene().multiMaterials;
  23339. for (index = 0; index < multiMaterials.length; index++) {
  23340. if (multiMaterials[index].id === id) {
  23341. this.material = multiMaterials[index];
  23342. return this;
  23343. }
  23344. }
  23345. return this;
  23346. };
  23347. /**
  23348. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23349. */
  23350. Mesh.prototype.getAnimatables = function () {
  23351. var results = [];
  23352. if (this.material) {
  23353. results.push(this.material);
  23354. }
  23355. if (this.skeleton) {
  23356. results.push(this.skeleton);
  23357. }
  23358. return results;
  23359. };
  23360. /**
  23361. * Modifies the mesh geometry according to the passed transformation matrix.
  23362. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23363. * The mesh normals are modified accordingly the same transformation.
  23364. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23365. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23366. * Returns the Mesh.
  23367. */
  23368. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23369. // Position
  23370. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23371. return this;
  23372. }
  23373. var submeshes = this.subMeshes.splice(0);
  23374. this._resetPointsArrayCache();
  23375. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23376. var temp = [];
  23377. var index;
  23378. for (index = 0; index < data.length; index += 3) {
  23379. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23380. }
  23381. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23382. // Normals
  23383. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23384. return this;
  23385. }
  23386. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23387. temp = [];
  23388. for (index = 0; index < data.length; index += 3) {
  23389. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23390. }
  23391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23392. // flip faces?
  23393. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23394. this.flipFaces();
  23395. }
  23396. // Restore submeshes
  23397. this.releaseSubMeshes();
  23398. this.subMeshes = submeshes;
  23399. return this;
  23400. };
  23401. /**
  23402. * Modifies the mesh geometry according to its own current World Matrix.
  23403. * The mesh World Matrix is then reset.
  23404. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23405. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23406. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23407. * Returns the Mesh.
  23408. */
  23409. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23410. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23411. this.scaling.copyFromFloats(1, 1, 1);
  23412. this.position.copyFromFloats(0, 0, 0);
  23413. this.rotation.copyFromFloats(0, 0, 0);
  23414. //only if quaternion is already set
  23415. if (this.rotationQuaternion) {
  23416. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23417. }
  23418. this._worldMatrix = BABYLON.Matrix.Identity();
  23419. return this;
  23420. };
  23421. // Cache
  23422. Mesh.prototype._resetPointsArrayCache = function () {
  23423. this._positions = null;
  23424. return this;
  23425. };
  23426. Mesh.prototype._generatePointsArray = function () {
  23427. if (this._positions)
  23428. return true;
  23429. this._positions = [];
  23430. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23431. if (!data) {
  23432. return false;
  23433. }
  23434. for (var index = 0; index < data.length; index += 3) {
  23435. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23436. }
  23437. return true;
  23438. };
  23439. /**
  23440. * Returns a new Mesh object generated from the current mesh properties.
  23441. * This method must not get confused with createInstance().
  23442. * The parameter `name` is a string, the name given to the new mesh.
  23443. * The optional parameter `newParent` can be any Node object (default `null`).
  23444. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23445. * 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.
  23446. */
  23447. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23448. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23449. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23450. };
  23451. /**
  23452. * Disposes the mesh.
  23453. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23454. */
  23455. Mesh.prototype.dispose = function (doNotRecurse) {
  23456. var _this = this;
  23457. if (this._geometry) {
  23458. this._geometry.releaseForMesh(this, true);
  23459. }
  23460. // Sources
  23461. var meshes = this.getScene().meshes;
  23462. meshes.forEach(function (mesh) {
  23463. if (mesh._source && mesh._source === _this) {
  23464. mesh._source = null;
  23465. }
  23466. });
  23467. this._source = null;
  23468. // Instances
  23469. if (this._instancesBuffer) {
  23470. this._instancesBuffer.dispose();
  23471. this._instancesBuffer = null;
  23472. }
  23473. while (this.instances.length) {
  23474. this.instances[0].dispose();
  23475. }
  23476. // Highlight layers.
  23477. var highlightLayers = this.getScene().highlightLayers;
  23478. for (var i = 0; i < highlightLayers.length; i++) {
  23479. var highlightLayer = highlightLayers[i];
  23480. if (highlightLayer) {
  23481. highlightLayer.removeMesh(this);
  23482. highlightLayer.removeExcludedMesh(this);
  23483. }
  23484. }
  23485. _super.prototype.dispose.call(this, doNotRecurse);
  23486. };
  23487. /**
  23488. * Modifies the mesh geometry according to a displacement map.
  23489. * 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.
  23490. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23491. * This method returns nothing.
  23492. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23493. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23494. * 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.
  23495. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23496. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23497. *
  23498. * Returns the Mesh.
  23499. */
  23500. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23501. var _this = this;
  23502. var scene = this.getScene();
  23503. var onload = function (img) {
  23504. // Getting height map data
  23505. var canvas = document.createElement("canvas");
  23506. var context = canvas.getContext("2d");
  23507. var heightMapWidth = img.width;
  23508. var heightMapHeight = img.height;
  23509. canvas.width = heightMapWidth;
  23510. canvas.height = heightMapHeight;
  23511. context.drawImage(img, 0, 0);
  23512. // Create VertexData from map data
  23513. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23514. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23515. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23516. //execute success callback, if set
  23517. if (onSuccess) {
  23518. onSuccess(_this);
  23519. }
  23520. };
  23521. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23522. return this;
  23523. };
  23524. /**
  23525. * Modifies the mesh geometry according to a displacementMap buffer.
  23526. * 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.
  23527. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23528. * This method returns nothing.
  23529. * 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.
  23530. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23531. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23532. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23533. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23534. *
  23535. * Returns the Mesh.
  23536. */
  23537. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23539. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23540. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23541. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23542. return this;
  23543. }
  23544. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23545. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23546. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23547. var position = BABYLON.Vector3.Zero();
  23548. var normal = BABYLON.Vector3.Zero();
  23549. var uv = BABYLON.Vector2.Zero();
  23550. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23551. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23552. for (var index = 0; index < positions.length; index += 3) {
  23553. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23554. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23555. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23556. // Compute height
  23557. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23558. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23559. var pos = (u + v * heightMapWidth) * 4;
  23560. var r = buffer[pos] / 255.0;
  23561. var g = buffer[pos + 1] / 255.0;
  23562. var b = buffer[pos + 2] / 255.0;
  23563. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23564. normal.normalize();
  23565. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23566. position = position.add(normal);
  23567. position.toArray(positions, index);
  23568. }
  23569. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23570. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23571. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23572. return this;
  23573. };
  23574. /**
  23575. * Modify the mesh to get a flat shading rendering.
  23576. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23577. * This method returns the Mesh.
  23578. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23579. */
  23580. Mesh.prototype.convertToFlatShadedMesh = function () {
  23581. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23582. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23583. var kinds = this.getVerticesDataKinds();
  23584. var vbs = [];
  23585. var data = [];
  23586. var newdata = [];
  23587. var updatableNormals = false;
  23588. var kindIndex;
  23589. var kind;
  23590. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23591. kind = kinds[kindIndex];
  23592. var vertexBuffer = this.getVertexBuffer(kind);
  23593. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23594. updatableNormals = vertexBuffer.isUpdatable();
  23595. kinds.splice(kindIndex, 1);
  23596. kindIndex--;
  23597. continue;
  23598. }
  23599. vbs[kind] = vertexBuffer;
  23600. data[kind] = vbs[kind].getData();
  23601. newdata[kind] = [];
  23602. }
  23603. // Save previous submeshes
  23604. var previousSubmeshes = this.subMeshes.slice(0);
  23605. var indices = this.getIndices();
  23606. var totalIndices = this.getTotalIndices();
  23607. // Generating unique vertices per face
  23608. var index;
  23609. for (index = 0; index < totalIndices; index++) {
  23610. var vertexIndex = indices[index];
  23611. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23612. kind = kinds[kindIndex];
  23613. var stride = vbs[kind].getStrideSize();
  23614. for (var offset = 0; offset < stride; offset++) {
  23615. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23616. }
  23617. }
  23618. }
  23619. // Updating faces & normal
  23620. var normals = [];
  23621. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23622. for (index = 0; index < totalIndices; index += 3) {
  23623. indices[index] = index;
  23624. indices[index + 1] = index + 1;
  23625. indices[index + 2] = index + 2;
  23626. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23627. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23628. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23629. var p1p2 = p1.subtract(p2);
  23630. var p3p2 = p3.subtract(p2);
  23631. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23632. // Store same normals for every vertex
  23633. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23634. normals.push(normal.x);
  23635. normals.push(normal.y);
  23636. normals.push(normal.z);
  23637. }
  23638. }
  23639. this.setIndices(indices);
  23640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23641. // Updating vertex buffers
  23642. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23643. kind = kinds[kindIndex];
  23644. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23645. }
  23646. // Updating submeshes
  23647. this.releaseSubMeshes();
  23648. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23649. var previousOne = previousSubmeshes[submeshIndex];
  23650. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23651. }
  23652. this.synchronizeInstances();
  23653. return this;
  23654. };
  23655. /**
  23656. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23657. * In other words, more vertices, no more indices and a single bigger VBO.
  23658. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23659. * Returns the Mesh.
  23660. */
  23661. Mesh.prototype.convertToUnIndexedMesh = function () {
  23662. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23663. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23664. var kinds = this.getVerticesDataKinds();
  23665. var vbs = [];
  23666. var data = [];
  23667. var newdata = [];
  23668. var updatableNormals = false;
  23669. var kindIndex;
  23670. var kind;
  23671. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23672. kind = kinds[kindIndex];
  23673. var vertexBuffer = this.getVertexBuffer(kind);
  23674. vbs[kind] = vertexBuffer;
  23675. data[kind] = vbs[kind].getData();
  23676. newdata[kind] = [];
  23677. }
  23678. // Save previous submeshes
  23679. var previousSubmeshes = this.subMeshes.slice(0);
  23680. var indices = this.getIndices();
  23681. var totalIndices = this.getTotalIndices();
  23682. // Generating unique vertices per face
  23683. var index;
  23684. for (index = 0; index < totalIndices; index++) {
  23685. var vertexIndex = indices[index];
  23686. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23687. kind = kinds[kindIndex];
  23688. var stride = vbs[kind].getStrideSize();
  23689. for (var offset = 0; offset < stride; offset++) {
  23690. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23691. }
  23692. }
  23693. }
  23694. // Updating indices
  23695. for (index = 0; index < totalIndices; index += 3) {
  23696. indices[index] = index;
  23697. indices[index + 1] = index + 1;
  23698. indices[index + 2] = index + 2;
  23699. }
  23700. this.setIndices(indices);
  23701. // Updating vertex buffers
  23702. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23703. kind = kinds[kindIndex];
  23704. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23705. }
  23706. // Updating submeshes
  23707. this.releaseSubMeshes();
  23708. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23709. var previousOne = previousSubmeshes[submeshIndex];
  23710. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23711. }
  23712. this._unIndexed = true;
  23713. this.synchronizeInstances();
  23714. return this;
  23715. };
  23716. /**
  23717. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23718. * This method returns the Mesh.
  23719. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23720. */
  23721. Mesh.prototype.flipFaces = function (flipNormals) {
  23722. if (flipNormals === void 0) { flipNormals = false; }
  23723. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23724. var i;
  23725. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23726. for (i = 0; i < vertex_data.normals.length; i++) {
  23727. vertex_data.normals[i] *= -1;
  23728. }
  23729. }
  23730. var temp;
  23731. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23732. // reassign indices
  23733. temp = vertex_data.indices[i + 1];
  23734. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23735. vertex_data.indices[i + 2] = temp;
  23736. }
  23737. vertex_data.applyToMesh(this);
  23738. return this;
  23739. };
  23740. // Instances
  23741. /**
  23742. * Creates a new InstancedMesh object from the mesh model.
  23743. * An instance shares the same properties and the same material than its model.
  23744. * Only these properties of each instance can then be set individually :
  23745. * - position
  23746. * - rotation
  23747. * - rotationQuaternion
  23748. * - setPivotMatrix
  23749. * - scaling
  23750. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23751. * Warning : this method is not supported for Line mesh and LineSystem
  23752. */
  23753. Mesh.prototype.createInstance = function (name) {
  23754. return new BABYLON.InstancedMesh(name, this);
  23755. };
  23756. /**
  23757. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23758. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23759. * This method returns the Mesh.
  23760. */
  23761. Mesh.prototype.synchronizeInstances = function () {
  23762. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23763. var instance = this.instances[instanceIndex];
  23764. instance._syncSubMeshes();
  23765. }
  23766. return this;
  23767. };
  23768. /**
  23769. * Simplify the mesh according to the given array of settings.
  23770. * Function will return immediately and will simplify async. It returns the Mesh.
  23771. * @param settings a collection of simplification settings.
  23772. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23773. * @param type the type of simplification to run.
  23774. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23775. */
  23776. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23777. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23778. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23779. this.getScene().simplificationQueue.addTask({
  23780. settings: settings,
  23781. parallelProcessing: parallelProcessing,
  23782. mesh: this,
  23783. simplificationType: simplificationType,
  23784. successCallback: successCallback
  23785. });
  23786. return this;
  23787. };
  23788. /**
  23789. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23790. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23791. * This should be used together with the simplification to avoid disappearing triangles.
  23792. * Returns the Mesh.
  23793. * @param successCallback an optional success callback to be called after the optimization finished.
  23794. */
  23795. Mesh.prototype.optimizeIndices = function (successCallback) {
  23796. var _this = this;
  23797. var indices = this.getIndices();
  23798. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23799. var vectorPositions = [];
  23800. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23801. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23802. }
  23803. var dupes = [];
  23804. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23805. var realPos = vectorPositions.length - 1 - iteration;
  23806. var testedPosition = vectorPositions[realPos];
  23807. for (var j = 0; j < realPos; ++j) {
  23808. var againstPosition = vectorPositions[j];
  23809. if (testedPosition.equals(againstPosition)) {
  23810. dupes[realPos] = j;
  23811. break;
  23812. }
  23813. }
  23814. }, function () {
  23815. for (var i = 0; i < indices.length; ++i) {
  23816. indices[i] = dupes[indices[i]] || indices[i];
  23817. }
  23818. //indices are now reordered
  23819. var originalSubMeshes = _this.subMeshes.slice(0);
  23820. _this.setIndices(indices);
  23821. _this.subMeshes = originalSubMeshes;
  23822. if (successCallback) {
  23823. successCallback(_this);
  23824. }
  23825. });
  23826. return this;
  23827. };
  23828. // Statics
  23829. /**
  23830. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23831. * The parameter `parsedMesh` is the mesh to be copied.
  23832. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23833. */
  23834. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23835. var mesh = new Mesh(parsedMesh.name, scene);
  23836. mesh.id = parsedMesh.id;
  23837. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23838. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23839. if (parsedMesh.metadata !== undefined) {
  23840. mesh.metadata = parsedMesh.metadata;
  23841. }
  23842. if (parsedMesh.rotationQuaternion) {
  23843. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23844. }
  23845. else if (parsedMesh.rotation) {
  23846. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23847. }
  23848. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23849. if (parsedMesh.localMatrix) {
  23850. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23851. }
  23852. else if (parsedMesh.pivotMatrix) {
  23853. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23854. }
  23855. mesh.setEnabled(parsedMesh.isEnabled);
  23856. mesh.isVisible = parsedMesh.isVisible;
  23857. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23858. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23859. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23860. if (parsedMesh.applyFog !== undefined) {
  23861. mesh.applyFog = parsedMesh.applyFog;
  23862. }
  23863. if (parsedMesh.pickable !== undefined) {
  23864. mesh.isPickable = parsedMesh.pickable;
  23865. }
  23866. if (parsedMesh.alphaIndex !== undefined) {
  23867. mesh.alphaIndex = parsedMesh.alphaIndex;
  23868. }
  23869. mesh.receiveShadows = parsedMesh.receiveShadows;
  23870. mesh.billboardMode = parsedMesh.billboardMode;
  23871. if (parsedMesh.visibility !== undefined) {
  23872. mesh.visibility = parsedMesh.visibility;
  23873. }
  23874. mesh.checkCollisions = parsedMesh.checkCollisions;
  23875. if (parsedMesh.isBlocker !== undefined) {
  23876. mesh.isBlocker = parsedMesh.isBlocker;
  23877. }
  23878. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23879. // freezeWorldMatrix
  23880. if (parsedMesh.freezeWorldMatrix) {
  23881. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23882. }
  23883. // Parent
  23884. if (parsedMesh.parentId) {
  23885. mesh._waitingParentId = parsedMesh.parentId;
  23886. }
  23887. // Actions
  23888. if (parsedMesh.actions !== undefined) {
  23889. mesh._waitingActions = parsedMesh.actions;
  23890. }
  23891. // Overlay
  23892. if (parsedMesh.overlayAlpha !== undefined) {
  23893. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23894. }
  23895. if (parsedMesh.overlayColor !== undefined) {
  23896. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23897. }
  23898. if (parsedMesh.renderOverlay !== undefined) {
  23899. mesh.renderOverlay = parsedMesh.renderOverlay;
  23900. }
  23901. // Geometry
  23902. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23903. if (parsedMesh.delayLoadingFile) {
  23904. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23905. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23906. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23907. if (parsedMesh._binaryInfo) {
  23908. mesh._binaryInfo = parsedMesh._binaryInfo;
  23909. }
  23910. mesh._delayInfo = [];
  23911. if (parsedMesh.hasUVs) {
  23912. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23913. }
  23914. if (parsedMesh.hasUVs2) {
  23915. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23916. }
  23917. if (parsedMesh.hasUVs3) {
  23918. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23919. }
  23920. if (parsedMesh.hasUVs4) {
  23921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23922. }
  23923. if (parsedMesh.hasUVs5) {
  23924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23925. }
  23926. if (parsedMesh.hasUVs6) {
  23927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23928. }
  23929. if (parsedMesh.hasColors) {
  23930. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23931. }
  23932. if (parsedMesh.hasMatricesIndices) {
  23933. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23934. }
  23935. if (parsedMesh.hasMatricesWeights) {
  23936. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23937. }
  23938. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23939. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23940. mesh._checkDelayState();
  23941. }
  23942. }
  23943. else {
  23944. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23945. }
  23946. // Material
  23947. if (parsedMesh.materialId) {
  23948. mesh.setMaterialByID(parsedMesh.materialId);
  23949. }
  23950. else {
  23951. mesh.material = null;
  23952. }
  23953. // Skeleton
  23954. if (parsedMesh.skeletonId > -1) {
  23955. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23956. if (parsedMesh.numBoneInfluencers) {
  23957. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23958. }
  23959. }
  23960. // Animations
  23961. if (parsedMesh.animations) {
  23962. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23963. var parsedAnimation = parsedMesh.animations[animationIndex];
  23964. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23965. }
  23966. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23967. }
  23968. if (parsedMesh.autoAnimate) {
  23969. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23970. }
  23971. // Layer Mask
  23972. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23973. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23974. }
  23975. else {
  23976. mesh.layerMask = 0x0FFFFFFF;
  23977. }
  23978. //(Deprecated) physics
  23979. if (parsedMesh.physicsImpostor) {
  23980. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23981. mass: parsedMesh.physicsMass,
  23982. friction: parsedMesh.physicsFriction,
  23983. restitution: parsedMesh.physicsRestitution
  23984. }, scene);
  23985. }
  23986. // Instances
  23987. if (parsedMesh.instances) {
  23988. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23989. var parsedInstance = parsedMesh.instances[index];
  23990. var instance = mesh.createInstance(parsedInstance.name);
  23991. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23992. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23993. if (parsedInstance.parentId) {
  23994. instance._waitingParentId = parsedInstance.parentId;
  23995. }
  23996. if (parsedInstance.rotationQuaternion) {
  23997. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23998. }
  23999. else if (parsedInstance.rotation) {
  24000. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24001. }
  24002. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24003. instance.checkCollisions = mesh.checkCollisions;
  24004. if (parsedMesh.animations) {
  24005. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24006. parsedAnimation = parsedMesh.animations[animationIndex];
  24007. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24008. }
  24009. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24010. }
  24011. }
  24012. }
  24013. return mesh;
  24014. };
  24015. /**
  24016. * Creates a ribbon mesh.
  24017. * Please consider using the same method from the MeshBuilder class instead.
  24018. * 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.
  24019. *
  24020. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24021. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24022. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24023. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24024. * 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.
  24025. * 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.
  24026. * 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
  24027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24030. */
  24031. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24032. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24033. pathArray: pathArray,
  24034. closeArray: closeArray,
  24035. closePath: closePath,
  24036. offset: offset,
  24037. updatable: updatable,
  24038. sideOrientation: sideOrientation,
  24039. instance: instance
  24040. }, scene);
  24041. };
  24042. /**
  24043. * Creates a plane polygonal mesh. By default, this is a disc.
  24044. * Please consider using the same method from the MeshBuilder class instead.
  24045. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24046. * 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.
  24047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24050. */
  24051. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24052. var options = {
  24053. radius: radius,
  24054. tessellation: tessellation,
  24055. sideOrientation: sideOrientation,
  24056. updatable: updatable
  24057. };
  24058. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24059. };
  24060. /**
  24061. * Creates a box mesh.
  24062. * Please consider using the same method from the MeshBuilder class instead.
  24063. * The parameter `size` sets the size (float) of each box side (default 1).
  24064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24067. */
  24068. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24069. var options = {
  24070. size: size,
  24071. sideOrientation: sideOrientation,
  24072. updatable: updatable
  24073. };
  24074. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24075. };
  24076. /**
  24077. * Creates a sphere mesh.
  24078. * Please consider using the same method from the MeshBuilder class instead.
  24079. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24080. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24081. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24084. */
  24085. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24086. var options = {
  24087. segments: segments,
  24088. diameterX: diameter,
  24089. diameterY: diameter,
  24090. diameterZ: diameter,
  24091. sideOrientation: sideOrientation,
  24092. updatable: updatable
  24093. };
  24094. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24095. };
  24096. /**
  24097. * Creates a cylinder or a cone mesh.
  24098. * Please consider using the same method from the MeshBuilder class instead.
  24099. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24100. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24101. * 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.
  24102. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24103. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24107. */
  24108. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24109. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24110. if (scene !== undefined) {
  24111. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24112. updatable = scene;
  24113. }
  24114. scene = subdivisions;
  24115. subdivisions = 1;
  24116. }
  24117. var options = {
  24118. height: height,
  24119. diameterTop: diameterTop,
  24120. diameterBottom: diameterBottom,
  24121. tessellation: tessellation,
  24122. subdivisions: subdivisions,
  24123. sideOrientation: sideOrientation,
  24124. updatable: updatable
  24125. };
  24126. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24127. };
  24128. // Torus (Code from SharpDX.org)
  24129. /**
  24130. * Creates a torus mesh.
  24131. * Please consider using the same method from the MeshBuilder class instead.
  24132. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24133. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24134. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24138. */
  24139. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24140. var options = {
  24141. diameter: diameter,
  24142. thickness: thickness,
  24143. tessellation: tessellation,
  24144. sideOrientation: sideOrientation,
  24145. updatable: updatable
  24146. };
  24147. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24148. };
  24149. /**
  24150. * Creates a torus knot mesh.
  24151. * Please consider using the same method from the MeshBuilder class instead.
  24152. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24153. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24154. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24155. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24159. */
  24160. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24161. var options = {
  24162. radius: radius,
  24163. tube: tube,
  24164. radialSegments: radialSegments,
  24165. tubularSegments: tubularSegments,
  24166. p: p,
  24167. q: q,
  24168. sideOrientation: sideOrientation,
  24169. updatable: updatable
  24170. };
  24171. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24172. };
  24173. /**
  24174. * Creates a line mesh.
  24175. * Please consider using the same method from the MeshBuilder class instead.
  24176. * 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.
  24177. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24178. * The parameter `points` is an array successive Vector3.
  24179. * 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
  24180. * When updating an instance, remember that only point positions can change, not the number of points.
  24181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24182. */
  24183. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24184. var options = {
  24185. points: points,
  24186. updatable: updatable,
  24187. instance: instance
  24188. };
  24189. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24190. };
  24191. /**
  24192. * Creates a dashed line mesh.
  24193. * Please consider using the same method from the MeshBuilder class instead.
  24194. * 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.
  24195. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24196. * The parameter `points` is an array successive Vector3.
  24197. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24198. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24199. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24200. * 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
  24201. * When updating an instance, remember that only point positions can change, not the number of points.
  24202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24203. */
  24204. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24205. var options = {
  24206. points: points,
  24207. dashSize: dashSize,
  24208. gapSize: gapSize,
  24209. dashNb: dashNb,
  24210. updatable: updatable,
  24211. instance: instance
  24212. };
  24213. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24214. };
  24215. /**
  24216. * Creates an extruded shape mesh.
  24217. * 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.
  24218. * Please consider using the same method from the MeshBuilder class instead.
  24219. *
  24220. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24221. * 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
  24222. * extruded along the Z axis.
  24223. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24224. * 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.
  24225. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24226. * 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
  24227. * 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
  24228. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24232. */
  24233. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24234. var options = {
  24235. shape: shape,
  24236. path: path,
  24237. scale: scale,
  24238. rotation: rotation,
  24239. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24240. sideOrientation: sideOrientation,
  24241. instance: instance,
  24242. updatable: updatable
  24243. };
  24244. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24245. };
  24246. /**
  24247. * Creates an custom extruded shape mesh.
  24248. * 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.
  24249. * Please consider using the same method from the MeshBuilder class instead.
  24250. *
  24251. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24252. * 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
  24253. * extruded along the Z axis.
  24254. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24255. * 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
  24256. * and the distance of this point from the begining of the path :
  24257. * ```javascript
  24258. * var rotationFunction = function(i, distance) {
  24259. * // do things
  24260. * return rotationValue; }
  24261. * ```
  24262. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24263. * 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
  24264. * and the distance of this point from the begining of the path :
  24265. * ```javascript
  24266. * var scaleFunction = function(i, distance) {
  24267. * // do things
  24268. * return scaleValue;}
  24269. * ```
  24270. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24271. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24272. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24273. * 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
  24274. * 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
  24275. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24276. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24277. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24278. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24279. */
  24280. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24281. var options = {
  24282. shape: shape,
  24283. path: path,
  24284. scaleFunction: scaleFunction,
  24285. rotationFunction: rotationFunction,
  24286. ribbonCloseArray: ribbonCloseArray,
  24287. ribbonClosePath: ribbonClosePath,
  24288. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24289. sideOrientation: sideOrientation,
  24290. instance: instance,
  24291. updatable: updatable
  24292. };
  24293. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24294. };
  24295. /**
  24296. * Creates lathe mesh.
  24297. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24298. * Please consider using the same method from the MeshBuilder class instead.
  24299. * 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
  24300. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24301. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24302. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24306. */
  24307. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24308. var options = {
  24309. shape: shape,
  24310. radius: radius,
  24311. tessellation: tessellation,
  24312. sideOrientation: sideOrientation,
  24313. updatable: updatable
  24314. };
  24315. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24316. };
  24317. /**
  24318. * Creates a plane mesh.
  24319. * Please consider using the same method from the MeshBuilder class instead.
  24320. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24324. */
  24325. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24326. var options = {
  24327. size: size,
  24328. width: size,
  24329. height: size,
  24330. sideOrientation: sideOrientation,
  24331. updatable: updatable
  24332. };
  24333. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24334. };
  24335. /**
  24336. * Creates a ground mesh.
  24337. * Please consider using the same method from the MeshBuilder class instead.
  24338. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24339. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24341. */
  24342. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24343. var options = {
  24344. width: width,
  24345. height: height,
  24346. subdivisions: subdivisions,
  24347. updatable: updatable
  24348. };
  24349. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24350. };
  24351. /**
  24352. * Creates a tiled ground mesh.
  24353. * Please consider using the same method from the MeshBuilder class instead.
  24354. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24355. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24356. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24357. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24358. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24359. * numbers of subdivisions on the ground width and height of each tile.
  24360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24361. */
  24362. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24363. var options = {
  24364. xmin: xmin,
  24365. zmin: zmin,
  24366. xmax: xmax,
  24367. zmax: zmax,
  24368. subdivisions: subdivisions,
  24369. precision: precision,
  24370. updatable: updatable
  24371. };
  24372. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24373. };
  24374. /**
  24375. * Creates a ground mesh from a height map.
  24376. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24377. * Please consider using the same method from the MeshBuilder class instead.
  24378. * The parameter `url` sets the URL of the height map image resource.
  24379. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24380. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24381. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24382. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24383. * 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).
  24384. * This function is passed the newly built mesh :
  24385. * ```javascript
  24386. * function(mesh) { // do things
  24387. * return; }
  24388. * ```
  24389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24390. */
  24391. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24392. var options = {
  24393. width: width,
  24394. height: height,
  24395. subdivisions: subdivisions,
  24396. minHeight: minHeight,
  24397. maxHeight: maxHeight,
  24398. updatable: updatable,
  24399. onReady: onReady
  24400. };
  24401. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24402. };
  24403. /**
  24404. * Creates a tube mesh.
  24405. * 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.
  24406. * Please consider using the same method from the MeshBuilder class instead.
  24407. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24408. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24409. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24410. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24411. * 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.
  24412. * It must return a radius value (positive float) :
  24413. * ```javascript
  24414. * var radiusFunction = function(i, distance) {
  24415. * // do things
  24416. * return radius; }
  24417. * ```
  24418. * 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
  24419. * 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
  24420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24421. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24423. */
  24424. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24425. var options = {
  24426. path: path,
  24427. radius: radius,
  24428. tessellation: tessellation,
  24429. radiusFunction: radiusFunction,
  24430. arc: 1,
  24431. cap: cap,
  24432. updatable: updatable,
  24433. sideOrientation: sideOrientation,
  24434. instance: instance
  24435. };
  24436. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24437. };
  24438. /**
  24439. * Creates a polyhedron mesh.
  24440. * Please consider using the same method from the MeshBuilder class instead.
  24441. * 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
  24442. * to choose the wanted type.
  24443. * The parameter `size` (positive float, default 1) sets the polygon size.
  24444. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24445. * 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`.
  24446. * 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
  24447. * 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)`).
  24448. * 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
  24449. * 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.
  24450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24453. */
  24454. Mesh.CreatePolyhedron = function (name, options, scene) {
  24455. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24456. };
  24457. /**
  24458. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24459. * Please consider using the same method from the MeshBuilder class instead.
  24460. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24461. * 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`).
  24462. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24463. * 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.
  24464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24467. */
  24468. Mesh.CreateIcoSphere = function (name, options, scene) {
  24469. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24470. };
  24471. /**
  24472. * Creates a decal mesh.
  24473. * Please consider using the same method from the MeshBuilder class instead.
  24474. * 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.
  24475. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24476. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24477. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24478. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24479. */
  24480. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24481. var options = {
  24482. position: position,
  24483. normal: normal,
  24484. size: size,
  24485. angle: angle
  24486. };
  24487. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24488. };
  24489. // Skeletons
  24490. /**
  24491. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24492. */
  24493. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24494. var source;
  24495. if (!this._sourcePositions) {
  24496. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24497. this._sourcePositions = new Float32Array(source);
  24498. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24499. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24500. }
  24501. }
  24502. return this._sourcePositions;
  24503. };
  24504. /**
  24505. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24506. */
  24507. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24508. var source;
  24509. if (!this._sourceNormals) {
  24510. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24511. this._sourceNormals = new Float32Array(source);
  24512. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24513. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24514. }
  24515. }
  24516. return this._sourceNormals;
  24517. };
  24518. /**
  24519. * Updates the vertex buffer by applying transformation from the bones.
  24520. * Returns the Mesh.
  24521. *
  24522. * @param {skeleton} skeleton to apply
  24523. */
  24524. Mesh.prototype.applySkeleton = function (skeleton) {
  24525. if (!this.geometry) {
  24526. return this;
  24527. }
  24528. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24529. return this;
  24530. }
  24531. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24532. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24533. return this;
  24534. }
  24535. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24536. return this;
  24537. }
  24538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24539. return this;
  24540. }
  24541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24542. return this;
  24543. }
  24544. if (!this._sourcePositions) {
  24545. var submeshes = this.subMeshes.slice();
  24546. this.setPositionsForCPUSkinning();
  24547. this.subMeshes = submeshes;
  24548. }
  24549. if (!this._sourceNormals) {
  24550. this.setNormalsForCPUSkinning();
  24551. }
  24552. // positionsData checks for not being Float32Array will only pass at most once
  24553. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24554. if (!(positionsData instanceof Float32Array)) {
  24555. positionsData = new Float32Array(positionsData);
  24556. }
  24557. // normalsData checks for not being Float32Array will only pass at most once
  24558. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24559. if (!(normalsData instanceof Float32Array)) {
  24560. normalsData = new Float32Array(normalsData);
  24561. }
  24562. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24563. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24564. var needExtras = this.numBoneInfluencers > 4;
  24565. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24566. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24567. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24568. var tempVector3 = BABYLON.Vector3.Zero();
  24569. var finalMatrix = new BABYLON.Matrix();
  24570. var tempMatrix = new BABYLON.Matrix();
  24571. var matWeightIdx = 0;
  24572. var inf;
  24573. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24574. var weight;
  24575. for (inf = 0; inf < 4; inf++) {
  24576. weight = matricesWeightsData[matWeightIdx + inf];
  24577. if (weight > 0) {
  24578. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24579. finalMatrix.addToSelf(tempMatrix);
  24580. }
  24581. else
  24582. break;
  24583. }
  24584. if (needExtras) {
  24585. for (inf = 0; inf < 4; inf++) {
  24586. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24587. if (weight > 0) {
  24588. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24589. finalMatrix.addToSelf(tempMatrix);
  24590. }
  24591. else
  24592. break;
  24593. }
  24594. }
  24595. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24596. tempVector3.toArray(positionsData, index);
  24597. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24598. tempVector3.toArray(normalsData, index);
  24599. finalMatrix.reset();
  24600. }
  24601. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24602. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24603. return this;
  24604. };
  24605. // Tools
  24606. /**
  24607. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24608. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24609. */
  24610. Mesh.MinMax = function (meshes) {
  24611. var minVector = null;
  24612. var maxVector = null;
  24613. meshes.forEach(function (mesh, index, array) {
  24614. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24615. if (!minVector) {
  24616. minVector = boundingBox.minimumWorld;
  24617. maxVector = boundingBox.maximumWorld;
  24618. }
  24619. else {
  24620. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24621. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24622. }
  24623. });
  24624. return {
  24625. min: minVector,
  24626. max: maxVector
  24627. };
  24628. };
  24629. /**
  24630. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24631. */
  24632. Mesh.Center = function (meshesOrMinMaxVector) {
  24633. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24634. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24635. };
  24636. /**
  24637. * Merge the array of meshes into a single mesh for performance reasons.
  24638. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24639. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24640. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24641. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24642. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24643. */
  24644. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24645. if (disposeSource === void 0) { disposeSource = true; }
  24646. var index;
  24647. if (!allow32BitsIndices) {
  24648. var totalVertices = 0;
  24649. // Counting vertices
  24650. for (index = 0; index < meshes.length; index++) {
  24651. if (meshes[index]) {
  24652. totalVertices += meshes[index].getTotalVertices();
  24653. if (totalVertices > 65536) {
  24654. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24655. return null;
  24656. }
  24657. }
  24658. }
  24659. }
  24660. // Merge
  24661. var vertexData;
  24662. var otherVertexData;
  24663. var indiceArray = new Array();
  24664. var source;
  24665. for (index = 0; index < meshes.length; index++) {
  24666. if (meshes[index]) {
  24667. meshes[index].computeWorldMatrix(true);
  24668. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24669. otherVertexData.transform(meshes[index].getWorldMatrix());
  24670. if (vertexData) {
  24671. vertexData.merge(otherVertexData);
  24672. }
  24673. else {
  24674. vertexData = otherVertexData;
  24675. source = meshes[index];
  24676. }
  24677. if (subdivideWithSubMeshes) {
  24678. indiceArray.push(meshes[index].getTotalIndices());
  24679. }
  24680. }
  24681. }
  24682. if (!meshSubclass) {
  24683. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24684. }
  24685. vertexData.applyToMesh(meshSubclass);
  24686. // Setting properties
  24687. meshSubclass.material = source.material;
  24688. meshSubclass.checkCollisions = source.checkCollisions;
  24689. // Cleaning
  24690. if (disposeSource) {
  24691. for (index = 0; index < meshes.length; index++) {
  24692. if (meshes[index]) {
  24693. meshes[index].dispose();
  24694. }
  24695. }
  24696. }
  24697. // Subdivide
  24698. if (subdivideWithSubMeshes) {
  24699. //-- Suppresions du submesh global
  24700. meshSubclass.releaseSubMeshes();
  24701. index = 0;
  24702. var offset = 0;
  24703. //-- aplique la subdivision en fonction du tableau d'indices
  24704. while (index < indiceArray.length) {
  24705. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24706. offset += indiceArray[index];
  24707. index++;
  24708. }
  24709. }
  24710. return meshSubclass;
  24711. };
  24712. return Mesh;
  24713. }(BABYLON.AbstractMesh));
  24714. // Consts
  24715. Mesh._FRONTSIDE = 0;
  24716. Mesh._BACKSIDE = 1;
  24717. Mesh._DOUBLESIDE = 2;
  24718. Mesh._DEFAULTSIDE = 0;
  24719. Mesh._NO_CAP = 0;
  24720. Mesh._CAP_START = 1;
  24721. Mesh._CAP_END = 2;
  24722. Mesh._CAP_ALL = 3;
  24723. BABYLON.Mesh = Mesh;
  24724. })(BABYLON || (BABYLON = {}));
  24725. //# sourceMappingURL=babylon.mesh.js.map
  24726. var BABYLON;
  24727. (function (BABYLON) {
  24728. var SubMesh = (function () {
  24729. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24730. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24731. this.materialIndex = materialIndex;
  24732. this.verticesStart = verticesStart;
  24733. this.verticesCount = verticesCount;
  24734. this.indexStart = indexStart;
  24735. this.indexCount = indexCount;
  24736. this._renderId = 0;
  24737. this._mesh = mesh;
  24738. this._renderingMesh = renderingMesh || mesh;
  24739. mesh.subMeshes.push(this);
  24740. this._trianglePlanes = [];
  24741. this._id = mesh.subMeshes.length - 1;
  24742. if (createBoundingBox) {
  24743. this.refreshBoundingInfo();
  24744. mesh.computeWorldMatrix(true);
  24745. }
  24746. }
  24747. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24748. get: function () {
  24749. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. /**
  24755. * Returns the submesh BoudingInfo object.
  24756. */
  24757. SubMesh.prototype.getBoundingInfo = function () {
  24758. if (this.IsGlobal) {
  24759. return this._mesh.getBoundingInfo();
  24760. }
  24761. return this._boundingInfo;
  24762. };
  24763. /**
  24764. * Sets the submesh BoundingInfo.
  24765. * Return the SubMesh.
  24766. */
  24767. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24768. this._boundingInfo = boundingInfo;
  24769. return this;
  24770. };
  24771. /**
  24772. * Returns the mesh of the current submesh.
  24773. */
  24774. SubMesh.prototype.getMesh = function () {
  24775. return this._mesh;
  24776. };
  24777. /**
  24778. * Returns the rendering mesh of the submesh.
  24779. */
  24780. SubMesh.prototype.getRenderingMesh = function () {
  24781. return this._renderingMesh;
  24782. };
  24783. /**
  24784. * Returns the submesh material.
  24785. */
  24786. SubMesh.prototype.getMaterial = function () {
  24787. var rootMaterial = this._renderingMesh.material;
  24788. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  24789. var multiMaterial = rootMaterial;
  24790. return multiMaterial.getSubMaterial(this.materialIndex);
  24791. }
  24792. if (!rootMaterial) {
  24793. return this._mesh.getScene().defaultMaterial;
  24794. }
  24795. return rootMaterial;
  24796. };
  24797. // Methods
  24798. /**
  24799. * Sets a new updated BoundingInfo object to the submesh.
  24800. * Returns the SubMesh.
  24801. */
  24802. SubMesh.prototype.refreshBoundingInfo = function () {
  24803. this._lastColliderWorldVertices = null;
  24804. if (this.IsGlobal) {
  24805. return;
  24806. }
  24807. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24808. if (!data) {
  24809. this._boundingInfo = this._mesh._boundingInfo;
  24810. return;
  24811. }
  24812. var indices = this._renderingMesh.getIndices();
  24813. var extend;
  24814. //is this the only submesh?
  24815. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24816. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24817. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24818. }
  24819. else {
  24820. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24821. }
  24822. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24823. return this;
  24824. };
  24825. SubMesh.prototype._checkCollision = function (collider) {
  24826. return this.getBoundingInfo()._checkCollision(collider);
  24827. };
  24828. /**
  24829. * Updates the submesh BoundingInfo.
  24830. * Returns the Submesh.
  24831. */
  24832. SubMesh.prototype.updateBoundingInfo = function (world) {
  24833. if (!this.getBoundingInfo()) {
  24834. this.refreshBoundingInfo();
  24835. }
  24836. this.getBoundingInfo().update(world);
  24837. return this;
  24838. };
  24839. /**
  24840. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24841. * Boolean returned.
  24842. */
  24843. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24844. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24845. };
  24846. /**
  24847. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24848. * Boolean returned.
  24849. */
  24850. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24851. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24852. };
  24853. /**
  24854. * Renders the submesh.
  24855. * Returns it.
  24856. */
  24857. SubMesh.prototype.render = function (enableAlphaMode) {
  24858. this._renderingMesh.render(this, enableAlphaMode);
  24859. return this;
  24860. };
  24861. /**
  24862. * Returns a new Index Buffer.
  24863. * Type returned : WebGLBuffer.
  24864. */
  24865. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24866. if (!this._linesIndexBuffer) {
  24867. var linesIndices = [];
  24868. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24869. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24870. }
  24871. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24872. this.linesIndexCount = linesIndices.length;
  24873. }
  24874. return this._linesIndexBuffer;
  24875. };
  24876. /**
  24877. * True is the passed Ray intersects the submesh bounding box.
  24878. * Boolean returned.
  24879. */
  24880. SubMesh.prototype.canIntersects = function (ray) {
  24881. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24882. };
  24883. /**
  24884. * Returns an object IntersectionInfo.
  24885. */
  24886. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24887. var intersectInfo = null;
  24888. // LineMesh first as it's also a Mesh...
  24889. if (this._mesh instanceof BABYLON.LinesMesh) {
  24890. var lineMesh = this._mesh;
  24891. // Line test
  24892. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24893. var p0 = positions[indices[index]];
  24894. var p1 = positions[indices[index + 1]];
  24895. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24896. if (length < 0) {
  24897. continue;
  24898. }
  24899. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24900. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24901. if (fastCheck) {
  24902. break;
  24903. }
  24904. }
  24905. }
  24906. }
  24907. else {
  24908. // Triangles test
  24909. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24910. var p0 = positions[indices[index]];
  24911. var p1 = positions[indices[index + 1]];
  24912. var p2 = positions[indices[index + 2]];
  24913. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24914. if (currentIntersectInfo) {
  24915. if (currentIntersectInfo.distance < 0) {
  24916. continue;
  24917. }
  24918. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24919. intersectInfo = currentIntersectInfo;
  24920. intersectInfo.faceId = index / 3;
  24921. if (fastCheck) {
  24922. break;
  24923. }
  24924. }
  24925. }
  24926. }
  24927. }
  24928. return intersectInfo;
  24929. };
  24930. // Clone
  24931. /**
  24932. * Creates a new Submesh from the passed Mesh.
  24933. */
  24934. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24935. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24936. if (!this.IsGlobal) {
  24937. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24938. }
  24939. return result;
  24940. };
  24941. // Dispose
  24942. /**
  24943. * Disposes the Submesh.
  24944. * Returns nothing.
  24945. */
  24946. SubMesh.prototype.dispose = function () {
  24947. if (this._linesIndexBuffer) {
  24948. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24949. this._linesIndexBuffer = null;
  24950. }
  24951. // Remove from mesh
  24952. var index = this._mesh.subMeshes.indexOf(this);
  24953. this._mesh.subMeshes.splice(index, 1);
  24954. };
  24955. // Statics
  24956. /**
  24957. * Creates a new Submesh from the passed parameters :
  24958. * - materialIndex (integer) : the index of the main mesh material.
  24959. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24960. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24961. * - mesh (Mesh) : the main mesh to create the submesh from.
  24962. * - renderingMesh (optional Mesh) : rendering mesh.
  24963. */
  24964. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24965. var minVertexIndex = Number.MAX_VALUE;
  24966. var maxVertexIndex = -Number.MAX_VALUE;
  24967. renderingMesh = renderingMesh || mesh;
  24968. var indices = renderingMesh.getIndices();
  24969. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24970. var vertexIndex = indices[index];
  24971. if (vertexIndex < minVertexIndex)
  24972. minVertexIndex = vertexIndex;
  24973. if (vertexIndex > maxVertexIndex)
  24974. maxVertexIndex = vertexIndex;
  24975. }
  24976. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24977. };
  24978. return SubMesh;
  24979. }());
  24980. BABYLON.SubMesh = SubMesh;
  24981. })(BABYLON || (BABYLON = {}));
  24982. //# sourceMappingURL=babylon.subMesh.js.map
  24983. var BABYLON;
  24984. (function (BABYLON) {
  24985. var MeshBuilder = (function () {
  24986. function MeshBuilder() {
  24987. }
  24988. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  24989. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  24990. return BABYLON.Mesh.DOUBLESIDE;
  24991. }
  24992. if (orientation === undefined || orientation === null) {
  24993. return BABYLON.Mesh.FRONTSIDE;
  24994. }
  24995. return orientation;
  24996. };
  24997. /**
  24998. * Creates a box mesh.
  24999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25000. * The parameter `size` sets the size (float) of each box side (default 1).
  25001. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25002. * 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).
  25003. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25007. */
  25008. MeshBuilder.CreateBox = function (name, options, scene) {
  25009. var box = new BABYLON.Mesh(name, scene);
  25010. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25011. box.sideOrientation = options.sideOrientation;
  25012. var vertexData = BABYLON.VertexData.CreateBox(options);
  25013. vertexData.applyToMesh(box, options.updatable);
  25014. return box;
  25015. };
  25016. /**
  25017. * Creates a sphere mesh.
  25018. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25019. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25020. * 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`).
  25021. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25022. * 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
  25023. * 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).
  25024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25027. */
  25028. MeshBuilder.CreateSphere = function (name, options, scene) {
  25029. var sphere = new BABYLON.Mesh(name, scene);
  25030. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25031. sphere.sideOrientation = options.sideOrientation;
  25032. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25033. vertexData.applyToMesh(sphere, options.updatable);
  25034. return sphere;
  25035. };
  25036. /**
  25037. * Creates a plane polygonal mesh. By default, this is a disc.
  25038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25039. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25040. * 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.
  25041. * 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
  25042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25045. */
  25046. MeshBuilder.CreateDisc = function (name, options, scene) {
  25047. var disc = new BABYLON.Mesh(name, scene);
  25048. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25049. disc.sideOrientation = options.sideOrientation;
  25050. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25051. vertexData.applyToMesh(disc, options.updatable);
  25052. return disc;
  25053. };
  25054. /**
  25055. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25056. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25057. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25058. * 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`).
  25059. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25060. * 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.
  25061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25064. */
  25065. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25066. var sphere = new BABYLON.Mesh(name, scene);
  25067. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25068. sphere.sideOrientation = options.sideOrientation;
  25069. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25070. vertexData.applyToMesh(sphere, options.updatable);
  25071. return sphere;
  25072. };
  25073. ;
  25074. /**
  25075. * Creates a ribbon mesh.
  25076. * 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.
  25077. *
  25078. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25079. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25080. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25081. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25082. * 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.
  25083. * 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.
  25084. * 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
  25085. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25087. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25089. */
  25090. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25091. var pathArray = options.pathArray;
  25092. var closeArray = options.closeArray;
  25093. var closePath = options.closePath;
  25094. var offset = options.offset;
  25095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25096. var instance = options.instance;
  25097. var updatable = options.updatable;
  25098. if (instance) {
  25099. // positionFunction : ribbon case
  25100. // only pathArray and sideOrientation parameters are taken into account for positions update
  25101. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25102. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25103. var positionFunction = function (positions) {
  25104. var minlg = pathArray[0].length;
  25105. var i = 0;
  25106. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25107. for (var si = 1; si <= ns; si++) {
  25108. for (var p = 0; p < pathArray.length; p++) {
  25109. var path = pathArray[p];
  25110. var l = path.length;
  25111. minlg = (minlg < l) ? minlg : l;
  25112. var j = 0;
  25113. while (j < minlg) {
  25114. positions[i] = path[j].x;
  25115. positions[i + 1] = path[j].y;
  25116. positions[i + 2] = path[j].z;
  25117. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25118. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25119. }
  25120. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25121. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25122. }
  25123. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25124. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25125. }
  25126. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25127. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25128. }
  25129. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25130. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25131. }
  25132. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25133. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25134. }
  25135. j++;
  25136. i += 3;
  25137. }
  25138. if (instance._closePath) {
  25139. positions[i] = path[0].x;
  25140. positions[i + 1] = path[0].y;
  25141. positions[i + 2] = path[0].z;
  25142. i += 3;
  25143. }
  25144. }
  25145. }
  25146. };
  25147. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25148. positionFunction(positions);
  25149. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25150. instance._boundingInfo.update(instance._worldMatrix);
  25151. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25152. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25153. var indices = instance.getIndices();
  25154. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25155. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25156. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25157. if (instance._closePath) {
  25158. var indexFirst = 0;
  25159. var indexLast = 0;
  25160. for (var p = 0; p < pathArray.length; p++) {
  25161. indexFirst = instance._idx[p] * 3;
  25162. if (p + 1 < pathArray.length) {
  25163. indexLast = (instance._idx[p + 1] - 1) * 3;
  25164. }
  25165. else {
  25166. indexLast = normals.length - 3;
  25167. }
  25168. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25169. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25170. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25171. normals[indexLast] = normals[indexFirst];
  25172. normals[indexLast + 1] = normals[indexFirst + 1];
  25173. normals[indexLast + 2] = normals[indexFirst + 2];
  25174. }
  25175. }
  25176. if (!(instance.areNormalsFrozen)) {
  25177. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25178. }
  25179. }
  25180. return instance;
  25181. }
  25182. else {
  25183. var ribbon = new BABYLON.Mesh(name, scene);
  25184. ribbon.sideOrientation = sideOrientation;
  25185. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25186. if (closePath) {
  25187. ribbon._idx = vertexData._idx;
  25188. }
  25189. ribbon._closePath = closePath;
  25190. ribbon._closeArray = closeArray;
  25191. vertexData.applyToMesh(ribbon, updatable);
  25192. return ribbon;
  25193. }
  25194. };
  25195. /**
  25196. * Creates a cylinder or a cone mesh.
  25197. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25198. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25199. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25200. * 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.
  25201. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25202. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25203. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25204. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25205. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25206. * 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).
  25207. * 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
  25208. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25209. * 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
  25210. * 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.
  25211. * If `enclose` is false, a ring surface is one element.
  25212. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25213. * 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
  25214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25217. */
  25218. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25219. var cylinder = new BABYLON.Mesh(name, scene);
  25220. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25221. cylinder.sideOrientation = options.sideOrientation;
  25222. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25223. vertexData.applyToMesh(cylinder, options.updatable);
  25224. return cylinder;
  25225. };
  25226. /**
  25227. * Creates a torus mesh.
  25228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25229. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25230. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25231. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25232. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25233. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25235. */
  25236. MeshBuilder.CreateTorus = function (name, options, scene) {
  25237. var torus = new BABYLON.Mesh(name, scene);
  25238. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25239. torus.sideOrientation = options.sideOrientation;
  25240. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25241. vertexData.applyToMesh(torus, options.updatable);
  25242. return torus;
  25243. };
  25244. /**
  25245. * Creates a torus knot mesh.
  25246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25247. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25248. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25249. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25250. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25254. */
  25255. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25256. var torusKnot = new BABYLON.Mesh(name, scene);
  25257. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25258. torusKnot.sideOrientation = options.sideOrientation;
  25259. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25260. vertexData.applyToMesh(torusKnot, options.updatable);
  25261. return torusKnot;
  25262. };
  25263. /**
  25264. * Creates a line system mesh.
  25265. * A line system is a pool of many lines gathered in a single mesh.
  25266. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25267. * 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.
  25268. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25269. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25270. * 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
  25271. * 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
  25272. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25274. */
  25275. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25276. var instance = options.instance;
  25277. var lines = options.lines;
  25278. if (instance) {
  25279. var positionFunction = function (positions) {
  25280. var i = 0;
  25281. for (var l = 0; l < lines.length; l++) {
  25282. var points = lines[l];
  25283. for (var p = 0; p < points.length; p++) {
  25284. positions[i] = points[p].x;
  25285. positions[i + 1] = points[p].y;
  25286. positions[i + 2] = points[p].z;
  25287. i += 3;
  25288. }
  25289. }
  25290. };
  25291. instance.updateMeshPositions(positionFunction, false);
  25292. return instance;
  25293. }
  25294. // line system creation
  25295. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25296. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25297. vertexData.applyToMesh(lineSystem, options.updatable);
  25298. return lineSystem;
  25299. };
  25300. /**
  25301. * Creates a line mesh.
  25302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25303. * 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.
  25304. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25305. * The parameter `points` is an array successive Vector3.
  25306. * 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
  25307. * When updating an instance, remember that only point positions can change, not the number of points.
  25308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25309. */
  25310. MeshBuilder.CreateLines = function (name, options, scene) {
  25311. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25312. return lines;
  25313. };
  25314. /**
  25315. * Creates a dashed line mesh.
  25316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  25317. * 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.
  25318. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25319. * The parameter `points` is an array successive Vector3.
  25320. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25321. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25322. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25323. * 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
  25324. * When updating an instance, remember that only point positions can change, not the number of points.
  25325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25326. */
  25327. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  25328. var points = options.points;
  25329. var instance = options.instance;
  25330. var gapSize = options.gapSize;
  25331. var dashNb = options.dashNb;
  25332. var dashSize = options.dashSize;
  25333. if (instance) {
  25334. var positionFunction = function (positions) {
  25335. var curvect = BABYLON.Vector3.Zero();
  25336. var nbSeg = positions.length / 6;
  25337. var lg = 0;
  25338. var nb = 0;
  25339. var shft = 0;
  25340. var dashshft = 0;
  25341. var curshft = 0;
  25342. var p = 0;
  25343. var i = 0;
  25344. var j = 0;
  25345. for (i = 0; i < points.length - 1; i++) {
  25346. points[i + 1].subtractToRef(points[i], curvect);
  25347. lg += curvect.length();
  25348. }
  25349. shft = lg / nbSeg;
  25350. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  25351. for (i = 0; i < points.length - 1; i++) {
  25352. points[i + 1].subtractToRef(points[i], curvect);
  25353. nb = Math.floor(curvect.length() / shft);
  25354. curvect.normalize();
  25355. j = 0;
  25356. while (j < nb && p < positions.length) {
  25357. curshft = shft * j;
  25358. positions[p] = points[i].x + curshft * curvect.x;
  25359. positions[p + 1] = points[i].y + curshft * curvect.y;
  25360. positions[p + 2] = points[i].z + curshft * curvect.z;
  25361. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  25362. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  25363. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  25364. p += 6;
  25365. j++;
  25366. }
  25367. }
  25368. while (p < positions.length) {
  25369. positions[p] = points[i].x;
  25370. positions[p + 1] = points[i].y;
  25371. positions[p + 2] = points[i].z;
  25372. p += 3;
  25373. }
  25374. };
  25375. instance.updateMeshPositions(positionFunction, false);
  25376. return instance;
  25377. }
  25378. // dashed lines creation
  25379. var dashedLines = new BABYLON.LinesMesh(name, scene);
  25380. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  25381. vertexData.applyToMesh(dashedLines, options.updatable);
  25382. dashedLines.dashSize = dashSize;
  25383. dashedLines.gapSize = gapSize;
  25384. return dashedLines;
  25385. };
  25386. /**
  25387. * Creates an extruded shape mesh.
  25388. * 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.
  25389. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  25390. *
  25391. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25392. * 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
  25393. * extruded along the Z axis.
  25394. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25395. * 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.
  25396. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25397. * 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
  25398. * 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
  25399. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25402. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25404. */
  25405. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  25406. var path = options.path;
  25407. var shape = options.shape;
  25408. var scale = options.scale || 1;
  25409. var rotation = options.rotation || 0;
  25410. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25411. var updatable = options.updatable;
  25412. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25413. var instance = options.instance;
  25414. var invertUV = options.invertUV || false;
  25415. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  25416. };
  25417. /**
  25418. * Creates an custom extruded shape mesh.
  25419. * 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.
  25420. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  25421. *
  25422. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25423. * 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
  25424. * extruded along the Z axis.
  25425. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25426. * 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
  25427. * and the distance of this point from the begining of the path :
  25428. * ```javascript
  25429. * var rotationFunction = function(i, distance) {
  25430. * // do things
  25431. * return rotationValue; }
  25432. * ```
  25433. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25434. * 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
  25435. * and the distance of this point from the begining of the path :
  25436. * ```javascript
  25437. * var scaleFunction = function(i, distance) {
  25438. * // do things
  25439. * return scaleValue;}
  25440. * ```
  25441. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25442. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25443. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25444. * 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
  25445. * 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
  25446. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25449. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25451. */
  25452. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  25453. var path = options.path;
  25454. var shape = options.shape;
  25455. var scaleFunction = options.scaleFunction || (function () { return 1; });
  25456. var rotationFunction = options.rotationFunction || (function () { return 0; });
  25457. var ribbonCloseArray = options.ribbonCloseArray || false;
  25458. var ribbonClosePath = options.ribbonClosePath || false;
  25459. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25460. var updatable = options.updatable;
  25461. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25462. var instance = options.instance;
  25463. var invertUV = options.invertUV || false;
  25464. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  25465. };
  25466. /**
  25467. * Creates lathe mesh.
  25468. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  25470. *
  25471. * 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
  25472. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25473. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25474. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25475. * 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.
  25476. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  25477. * 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
  25478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25479. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25480. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25482. */
  25483. MeshBuilder.CreateLathe = function (name, options, scene) {
  25484. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  25485. var closed = (options.closed === undefined) ? true : options.closed;
  25486. var shape = options.shape;
  25487. var radius = options.radius || 1;
  25488. var tessellation = options.tessellation || 64;
  25489. var updatable = options.updatable;
  25490. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25491. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25492. var pi2 = Math.PI * 2;
  25493. var paths = new Array();
  25494. var invertUV = options.invertUV || false;
  25495. var i = 0;
  25496. var p = 0;
  25497. var step = pi2 / tessellation * arc;
  25498. var rotated;
  25499. var path = new Array();
  25500. ;
  25501. for (i = 0; i <= tessellation; i++) {
  25502. var path = [];
  25503. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  25504. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  25505. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  25506. }
  25507. for (p = 0; p < shape.length; p++) {
  25508. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  25509. path.push(rotated);
  25510. }
  25511. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  25512. 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));
  25513. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  25514. }
  25515. paths.push(path);
  25516. }
  25517. // lathe ribbon
  25518. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  25519. return lathe;
  25520. };
  25521. /**
  25522. * Creates a plane mesh.
  25523. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25524. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25525. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  25526. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  25527. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25528. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25529. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25530. */
  25531. MeshBuilder.CreatePlane = function (name, options, scene) {
  25532. var plane = new BABYLON.Mesh(name, scene);
  25533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25534. plane.sideOrientation = options.sideOrientation;
  25535. var vertexData = BABYLON.VertexData.CreatePlane(options);
  25536. vertexData.applyToMesh(plane, options.updatable);
  25537. if (options.sourcePlane) {
  25538. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  25539. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  25540. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  25541. plane.rotate(vectorProduct, product);
  25542. }
  25543. return plane;
  25544. };
  25545. /**
  25546. * Creates a ground mesh.
  25547. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25548. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25549. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25551. */
  25552. MeshBuilder.CreateGround = function (name, options, scene) {
  25553. var ground = new BABYLON.GroundMesh(name, scene);
  25554. ground._setReady(false);
  25555. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25556. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25557. ground._width = options.width || 1;
  25558. ground._height = options.height || 1;
  25559. ground._maxX = ground._width / 2;
  25560. ground._maxZ = ground._height / 2;
  25561. ground._minX = -ground._maxX;
  25562. ground._minZ = -ground._maxZ;
  25563. var vertexData = BABYLON.VertexData.CreateGround(options);
  25564. vertexData.applyToMesh(ground, options.updatable);
  25565. ground._setReady(true);
  25566. return ground;
  25567. };
  25568. /**
  25569. * Creates a tiled ground mesh.
  25570. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  25571. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25572. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25573. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25574. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25575. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25576. * numbers of subdivisions on the ground width and height of each tile.
  25577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25578. */
  25579. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  25580. var tiledGround = new BABYLON.Mesh(name, scene);
  25581. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  25582. vertexData.applyToMesh(tiledGround, options.updatable);
  25583. return tiledGround;
  25584. };
  25585. /**
  25586. * Creates a ground mesh from a height map.
  25587. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25588. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  25589. * The parameter `url` sets the URL of the height map image resource.
  25590. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25591. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25592. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25593. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25594. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  25595. * 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).
  25596. * This function is passed the newly built mesh :
  25597. * ```javascript
  25598. * function(mesh) { // do things
  25599. * return; }
  25600. * ```
  25601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25602. */
  25603. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  25604. var width = options.width || 10.0;
  25605. var height = options.height || 10.0;
  25606. var subdivisions = options.subdivisions || 1 | 0;
  25607. var minHeight = options.minHeight || 0.0;
  25608. var maxHeight = options.maxHeight || 10.0;
  25609. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25610. var updatable = options.updatable;
  25611. var onReady = options.onReady;
  25612. var ground = new BABYLON.GroundMesh(name, scene);
  25613. ground._subdivisionsX = subdivisions;
  25614. ground._subdivisionsY = subdivisions;
  25615. ground._width = width;
  25616. ground._height = height;
  25617. ground._maxX = ground._width / 2.0;
  25618. ground._maxZ = ground._height / 2.0;
  25619. ground._minX = -ground._maxX;
  25620. ground._minZ = -ground._maxZ;
  25621. ground._setReady(false);
  25622. var onload = function (img) {
  25623. // Getting height map data
  25624. var canvas = document.createElement("canvas");
  25625. var context = canvas.getContext("2d");
  25626. var bufferWidth = img.width;
  25627. var bufferHeight = img.height;
  25628. canvas.width = bufferWidth;
  25629. canvas.height = bufferHeight;
  25630. context.drawImage(img, 0, 0);
  25631. // Create VertexData from map data
  25632. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25633. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  25634. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  25635. width: width, height: height,
  25636. subdivisions: subdivisions,
  25637. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  25638. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  25639. });
  25640. vertexData.applyToMesh(ground, updatable);
  25641. ground._setReady(true);
  25642. //execute ready callback, if set
  25643. if (onReady) {
  25644. onReady(ground);
  25645. }
  25646. };
  25647. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25648. return ground;
  25649. };
  25650. /**
  25651. * Creates a tube mesh.
  25652. * 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.
  25653. *
  25654. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  25655. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25656. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25657. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25658. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25659. * 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.
  25660. * It must return a radius value (positive float) :
  25661. * ```javascript
  25662. * var radiusFunction = function(i, distance) {
  25663. * // do things
  25664. * return radius; }
  25665. * ```
  25666. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  25667. * 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
  25668. * 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
  25669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25671. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25673. */
  25674. MeshBuilder.CreateTube = function (name, options, scene) {
  25675. var path = options.path;
  25676. var radius = options.radius || 1.0;
  25677. var tessellation = options.tessellation || 64 | 0;
  25678. var radiusFunction = options.radiusFunction;
  25679. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25680. var invertUV = options.invertUV || false;
  25681. var updatable = options.updatable;
  25682. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25683. var instance = options.instance;
  25684. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  25685. // tube geometry
  25686. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  25687. var tangents = path3D.getTangents();
  25688. var normals = path3D.getNormals();
  25689. var distances = path3D.getDistances();
  25690. var pi2 = Math.PI * 2;
  25691. var step = pi2 / tessellation * arc;
  25692. var returnRadius = function () { return radius; };
  25693. var radiusFunctionFinal = radiusFunction || returnRadius;
  25694. var circlePath;
  25695. var rad;
  25696. var normal;
  25697. var rotated;
  25698. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25699. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25700. for (var i = 0; i < path.length; i++) {
  25701. rad = radiusFunctionFinal(i, distances[i]); // current radius
  25702. circlePath = Array(); // current circle array
  25703. normal = normals[i]; // current normal
  25704. for (var t = 0; t < tessellation; t++) {
  25705. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  25706. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  25707. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  25708. rotated.scaleInPlace(rad).addInPlace(path[i]);
  25709. circlePath[t] = rotated;
  25710. }
  25711. circlePaths[index] = circlePath;
  25712. index++;
  25713. }
  25714. // cap
  25715. var capPath = function (nbPoints, pathIndex) {
  25716. var pointCap = Array();
  25717. for (var i = 0; i < nbPoints; i++) {
  25718. pointCap.push(path[pathIndex]);
  25719. }
  25720. return pointCap;
  25721. };
  25722. switch (cap) {
  25723. case BABYLON.Mesh.NO_CAP:
  25724. break;
  25725. case BABYLON.Mesh.CAP_START:
  25726. circlePaths[0] = capPath(tessellation, 0);
  25727. circlePaths[1] = circlePaths[2].slice(0);
  25728. break;
  25729. case BABYLON.Mesh.CAP_END:
  25730. circlePaths[index] = circlePaths[index - 1].slice(0);
  25731. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25732. break;
  25733. case BABYLON.Mesh.CAP_ALL:
  25734. circlePaths[0] = capPath(tessellation, 0);
  25735. circlePaths[1] = circlePaths[2].slice(0);
  25736. circlePaths[index] = circlePaths[index - 1].slice(0);
  25737. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25738. break;
  25739. default:
  25740. break;
  25741. }
  25742. return circlePaths;
  25743. };
  25744. var path3D;
  25745. var pathArray;
  25746. if (instance) {
  25747. var arc = options.arc || instance.arc;
  25748. path3D = (instance.path3D).update(path);
  25749. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  25750. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  25751. instance.path3D = path3D;
  25752. instance.pathArray = pathArray;
  25753. instance.arc = arc;
  25754. return instance;
  25755. }
  25756. // tube creation
  25757. path3D = new BABYLON.Path3D(path);
  25758. var newPathArray = new Array();
  25759. cap = (cap < 0 || cap > 3) ? 0 : cap;
  25760. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  25761. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  25762. tube.pathArray = pathArray;
  25763. tube.path3D = path3D;
  25764. tube.tessellation = tessellation;
  25765. tube.cap = cap;
  25766. tube.arc = options.arc;
  25767. return tube;
  25768. };
  25769. /**
  25770. * Creates a polyhedron mesh.
  25771. *
  25772. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  25773. * 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
  25774. * to choose the wanted type.
  25775. * The parameter `size` (positive float, default 1) sets the polygon size.
  25776. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25777. * 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`.
  25778. * 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
  25779. * 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)`).
  25780. * 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
  25781. * 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.
  25782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25785. */
  25786. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  25787. var polyhedron = new BABYLON.Mesh(name, scene);
  25788. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25789. polyhedron.sideOrientation = options.sideOrientation;
  25790. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  25791. vertexData.applyToMesh(polyhedron, options.updatable);
  25792. return polyhedron;
  25793. };
  25794. /**
  25795. * Creates a decal mesh.
  25796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  25797. * 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.
  25798. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25799. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25800. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25801. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25802. */
  25803. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  25804. var indices = sourceMesh.getIndices();
  25805. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25806. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25807. var position = options.position || BABYLON.Vector3.Zero();
  25808. var normal = options.normal || BABYLON.Vector3.Up();
  25809. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  25810. var angle = options.angle || 0;
  25811. // Getting correct rotation
  25812. if (!normal) {
  25813. var target = new BABYLON.Vector3(0, 0, 1);
  25814. var camera = sourceMesh.getScene().activeCamera;
  25815. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  25816. normal = camera.globalPosition.subtract(cameraWorldTarget);
  25817. }
  25818. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  25819. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  25820. var pitch = Math.atan2(normal.y, len);
  25821. // Matrix
  25822. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  25823. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  25824. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  25825. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  25826. var vertexData = new BABYLON.VertexData();
  25827. vertexData.indices = [];
  25828. vertexData.positions = [];
  25829. vertexData.normals = [];
  25830. vertexData.uvs = [];
  25831. var currentVertexDataIndex = 0;
  25832. var extractDecalVector3 = function (indexId) {
  25833. var vertexId = indices[indexId];
  25834. var result = new BABYLON.PositionNormalVertex();
  25835. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  25836. // Send vector to decal local world
  25837. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  25838. // Get normal
  25839. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  25840. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  25841. return result;
  25842. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  25843. var clip = function (vertices, axis) {
  25844. if (vertices.length === 0) {
  25845. return vertices;
  25846. }
  25847. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  25848. var clipVertices = function (v0, v1) {
  25849. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  25850. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  25851. };
  25852. var result = new Array();
  25853. for (var index = 0; index < vertices.length; index += 3) {
  25854. var v1Out;
  25855. var v2Out;
  25856. var v3Out;
  25857. var total = 0;
  25858. var nV1, nV2, nV3, nV4;
  25859. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  25860. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  25861. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  25862. v1Out = d1 > 0;
  25863. v2Out = d2 > 0;
  25864. v3Out = d3 > 0;
  25865. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  25866. switch (total) {
  25867. case 0:
  25868. result.push(vertices[index]);
  25869. result.push(vertices[index + 1]);
  25870. result.push(vertices[index + 2]);
  25871. break;
  25872. case 1:
  25873. if (v1Out) {
  25874. nV1 = vertices[index + 1];
  25875. nV2 = vertices[index + 2];
  25876. nV3 = clipVertices(vertices[index], nV1);
  25877. nV4 = clipVertices(vertices[index], nV2);
  25878. }
  25879. if (v2Out) {
  25880. nV1 = vertices[index];
  25881. nV2 = vertices[index + 2];
  25882. nV3 = clipVertices(vertices[index + 1], nV1);
  25883. nV4 = clipVertices(vertices[index + 1], nV2);
  25884. result.push(nV3);
  25885. result.push(nV2.clone());
  25886. result.push(nV1.clone());
  25887. result.push(nV2.clone());
  25888. result.push(nV3.clone());
  25889. result.push(nV4);
  25890. break;
  25891. }
  25892. if (v3Out) {
  25893. nV1 = vertices[index];
  25894. nV2 = vertices[index + 1];
  25895. nV3 = clipVertices(vertices[index + 2], nV1);
  25896. nV4 = clipVertices(vertices[index + 2], nV2);
  25897. }
  25898. result.push(nV1.clone());
  25899. result.push(nV2.clone());
  25900. result.push(nV3);
  25901. result.push(nV4);
  25902. result.push(nV3.clone());
  25903. result.push(nV2.clone());
  25904. break;
  25905. case 2:
  25906. if (!v1Out) {
  25907. nV1 = vertices[index].clone();
  25908. nV2 = clipVertices(nV1, vertices[index + 1]);
  25909. nV3 = clipVertices(nV1, vertices[index + 2]);
  25910. result.push(nV1);
  25911. result.push(nV2);
  25912. result.push(nV3);
  25913. }
  25914. if (!v2Out) {
  25915. nV1 = vertices[index + 1].clone();
  25916. nV2 = clipVertices(nV1, vertices[index + 2]);
  25917. nV3 = clipVertices(nV1, vertices[index]);
  25918. result.push(nV1);
  25919. result.push(nV2);
  25920. result.push(nV3);
  25921. }
  25922. if (!v3Out) {
  25923. nV1 = vertices[index + 2].clone();
  25924. nV2 = clipVertices(nV1, vertices[index]);
  25925. nV3 = clipVertices(nV1, vertices[index + 1]);
  25926. result.push(nV1);
  25927. result.push(nV2);
  25928. result.push(nV3);
  25929. }
  25930. break;
  25931. case 3:
  25932. break;
  25933. }
  25934. }
  25935. return result;
  25936. };
  25937. for (var index = 0; index < indices.length; index += 3) {
  25938. var faceVertices = new Array();
  25939. faceVertices.push(extractDecalVector3(index));
  25940. faceVertices.push(extractDecalVector3(index + 1));
  25941. faceVertices.push(extractDecalVector3(index + 2));
  25942. // Clip
  25943. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  25944. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  25945. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  25946. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  25947. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  25948. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  25949. if (faceVertices.length === 0) {
  25950. continue;
  25951. }
  25952. // Add UVs and get back to world
  25953. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  25954. var vertex = faceVertices[vIndex];
  25955. //TODO check for Int32Array | Uint32Array | Uint16Array
  25956. vertexData.indices.push(currentVertexDataIndex);
  25957. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  25958. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  25959. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  25960. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  25961. currentVertexDataIndex++;
  25962. }
  25963. }
  25964. // Return mesh
  25965. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  25966. vertexData.applyToMesh(decal);
  25967. decal.position = position.clone();
  25968. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  25969. return decal;
  25970. };
  25971. // Privates
  25972. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  25973. // extrusion geometry
  25974. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  25975. var tangents = path3D.getTangents();
  25976. var normals = path3D.getNormals();
  25977. var binormals = path3D.getBinormals();
  25978. var distances = path3D.getDistances();
  25979. var angle = 0;
  25980. var returnScale = function () { return scale; };
  25981. var returnRotation = function () { return rotation; };
  25982. var rotate = custom ? rotateFunction : returnRotation;
  25983. var scl = custom ? scaleFunction : returnScale;
  25984. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25985. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25986. for (var i = 0; i < curve.length; i++) {
  25987. var shapePath = new Array();
  25988. var angleStep = rotate(i, distances[i]);
  25989. var scaleRatio = scl(i, distances[i]);
  25990. for (var p = 0; p < shape.length; p++) {
  25991. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  25992. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  25993. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  25994. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  25995. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  25996. shapePath[p] = rotated;
  25997. }
  25998. shapePaths[index] = shapePath;
  25999. angle += angleStep;
  26000. index++;
  26001. }
  26002. // cap
  26003. var capPath = function (shapePath) {
  26004. var pointCap = Array();
  26005. var barycenter = BABYLON.Vector3.Zero();
  26006. var i;
  26007. for (i = 0; i < shapePath.length; i++) {
  26008. barycenter.addInPlace(shapePath[i]);
  26009. }
  26010. barycenter.scaleInPlace(1.0 / shapePath.length);
  26011. for (i = 0; i < shapePath.length; i++) {
  26012. pointCap.push(barycenter);
  26013. }
  26014. return pointCap;
  26015. };
  26016. switch (cap) {
  26017. case BABYLON.Mesh.NO_CAP:
  26018. break;
  26019. case BABYLON.Mesh.CAP_START:
  26020. shapePaths[0] = capPath(shapePaths[2]);
  26021. shapePaths[1] = shapePaths[2];
  26022. break;
  26023. case BABYLON.Mesh.CAP_END:
  26024. shapePaths[index] = shapePaths[index - 1];
  26025. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26026. break;
  26027. case BABYLON.Mesh.CAP_ALL:
  26028. shapePaths[0] = capPath(shapePaths[2]);
  26029. shapePaths[1] = shapePaths[2];
  26030. shapePaths[index] = shapePaths[index - 1];
  26031. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26032. break;
  26033. default:
  26034. break;
  26035. }
  26036. return shapePaths;
  26037. };
  26038. var path3D;
  26039. var pathArray;
  26040. if (instance) {
  26041. path3D = (instance.path3D).update(curve);
  26042. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26043. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26044. return instance;
  26045. }
  26046. // extruded shape creation
  26047. path3D = new BABYLON.Path3D(curve);
  26048. var newShapePaths = new Array();
  26049. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26050. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26051. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26052. extrudedGeneric.pathArray = pathArray;
  26053. extrudedGeneric.path3D = path3D;
  26054. extrudedGeneric.cap = cap;
  26055. return extrudedGeneric;
  26056. };
  26057. return MeshBuilder;
  26058. }());
  26059. BABYLON.MeshBuilder = MeshBuilder;
  26060. })(BABYLON || (BABYLON = {}));
  26061. //# sourceMappingURL=babylon.meshBuilder.js.map
  26062. var BABYLON;
  26063. (function (BABYLON) {
  26064. var BaseTexture = (function () {
  26065. function BaseTexture(scene) {
  26066. this.hasAlpha = false;
  26067. this.getAlphaFromRGB = false;
  26068. this.level = 1;
  26069. this.coordinatesIndex = 0;
  26070. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26071. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26072. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26073. this.anisotropicFilteringLevel = 4;
  26074. this.isCube = false;
  26075. this.isRenderTarget = false;
  26076. this.animations = new Array();
  26077. /**
  26078. * An event triggered when the texture is disposed.
  26079. * @type {BABYLON.Observable}
  26080. */
  26081. this.onDisposeObservable = new BABYLON.Observable();
  26082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26083. this._scene = scene;
  26084. this._scene.textures.push(this);
  26085. this._uid = null;
  26086. }
  26087. Object.defineProperty(BaseTexture.prototype, "uid", {
  26088. get: function () {
  26089. if (!this._uid) {
  26090. this._uid = BABYLON.Tools.RandomId();
  26091. }
  26092. return this._uid;
  26093. },
  26094. enumerable: true,
  26095. configurable: true
  26096. });
  26097. BaseTexture.prototype.toString = function () {
  26098. return this.name;
  26099. };
  26100. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26101. set: function (callback) {
  26102. if (this._onDisposeObserver) {
  26103. this.onDisposeObservable.remove(this._onDisposeObserver);
  26104. }
  26105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. BaseTexture.prototype.getScene = function () {
  26111. return this._scene;
  26112. };
  26113. BaseTexture.prototype.getTextureMatrix = function () {
  26114. return null;
  26115. };
  26116. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26117. return null;
  26118. };
  26119. BaseTexture.prototype.getInternalTexture = function () {
  26120. return this._texture;
  26121. };
  26122. BaseTexture.prototype.isReady = function () {
  26123. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26124. return true;
  26125. }
  26126. if (this._texture) {
  26127. return this._texture.isReady;
  26128. }
  26129. return false;
  26130. };
  26131. BaseTexture.prototype.getSize = function () {
  26132. if (this._texture._width) {
  26133. return new BABYLON.Size(this._texture._width, this._texture._height);
  26134. }
  26135. if (this._texture._size) {
  26136. return new BABYLON.Size(this._texture._size, this._texture._size);
  26137. }
  26138. return BABYLON.Size.Zero();
  26139. };
  26140. BaseTexture.prototype.getBaseSize = function () {
  26141. if (!this.isReady() || !this._texture)
  26142. return BABYLON.Size.Zero();
  26143. if (this._texture._size) {
  26144. return new BABYLON.Size(this._texture._size, this._texture._size);
  26145. }
  26146. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26147. };
  26148. BaseTexture.prototype.scale = function (ratio) {
  26149. };
  26150. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26151. get: function () {
  26152. return false;
  26153. },
  26154. enumerable: true,
  26155. configurable: true
  26156. });
  26157. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26158. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26159. for (var index = 0; index < texturesCache.length; index++) {
  26160. var texturesCacheEntry = texturesCache[index];
  26161. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26162. texturesCache.splice(index, 1);
  26163. return;
  26164. }
  26165. }
  26166. };
  26167. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26168. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26169. for (var index = 0; index < texturesCache.length; index++) {
  26170. var texturesCacheEntry = texturesCache[index];
  26171. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26172. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26173. texturesCacheEntry.references++;
  26174. return texturesCacheEntry;
  26175. }
  26176. }
  26177. }
  26178. return null;
  26179. };
  26180. BaseTexture.prototype.delayLoad = function () {
  26181. };
  26182. BaseTexture.prototype.clone = function () {
  26183. return null;
  26184. };
  26185. BaseTexture.prototype.releaseInternalTexture = function () {
  26186. if (this._texture) {
  26187. this._scene.getEngine().releaseInternalTexture(this._texture);
  26188. delete this._texture;
  26189. }
  26190. };
  26191. BaseTexture.prototype.dispose = function () {
  26192. // Animations
  26193. this.getScene().stopAnimation(this);
  26194. // Remove from scene
  26195. var index = this._scene.textures.indexOf(this);
  26196. if (index >= 0) {
  26197. this._scene.textures.splice(index, 1);
  26198. }
  26199. if (this._texture === undefined) {
  26200. return;
  26201. }
  26202. // Release
  26203. this.releaseInternalTexture();
  26204. // Callback
  26205. this.onDisposeObservable.notifyObservers(this);
  26206. this.onDisposeObservable.clear();
  26207. };
  26208. BaseTexture.prototype.serialize = function () {
  26209. if (!this.name) {
  26210. return null;
  26211. }
  26212. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26213. // Animations
  26214. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26215. return serializationObject;
  26216. };
  26217. return BaseTexture;
  26218. }());
  26219. __decorate([
  26220. BABYLON.serialize()
  26221. ], BaseTexture.prototype, "name", void 0);
  26222. __decorate([
  26223. BABYLON.serialize()
  26224. ], BaseTexture.prototype, "hasAlpha", void 0);
  26225. __decorate([
  26226. BABYLON.serialize()
  26227. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26228. __decorate([
  26229. BABYLON.serialize()
  26230. ], BaseTexture.prototype, "level", void 0);
  26231. __decorate([
  26232. BABYLON.serialize()
  26233. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26234. __decorate([
  26235. BABYLON.serialize()
  26236. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26237. __decorate([
  26238. BABYLON.serialize()
  26239. ], BaseTexture.prototype, "wrapU", void 0);
  26240. __decorate([
  26241. BABYLON.serialize()
  26242. ], BaseTexture.prototype, "wrapV", void 0);
  26243. __decorate([
  26244. BABYLON.serialize()
  26245. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26246. __decorate([
  26247. BABYLON.serialize()
  26248. ], BaseTexture.prototype, "isCube", void 0);
  26249. __decorate([
  26250. BABYLON.serialize()
  26251. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26252. BABYLON.BaseTexture = BaseTexture;
  26253. })(BABYLON || (BABYLON = {}));
  26254. //# sourceMappingURL=babylon.baseTexture.js.map
  26255. var BABYLON;
  26256. (function (BABYLON) {
  26257. var Texture = (function (_super) {
  26258. __extends(Texture, _super);
  26259. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26260. if (noMipmap === void 0) { noMipmap = false; }
  26261. if (invertY === void 0) { invertY = true; }
  26262. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26263. if (onLoad === void 0) { onLoad = null; }
  26264. if (onError === void 0) { onError = null; }
  26265. if (buffer === void 0) { buffer = null; }
  26266. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26267. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26268. var _this = _super.call(this, scene) || this;
  26269. _this.uOffset = 0;
  26270. _this.vOffset = 0;
  26271. _this.uScale = 1.0;
  26272. _this.vScale = 1.0;
  26273. _this.uAng = 0;
  26274. _this.vAng = 0;
  26275. _this.wAng = 0;
  26276. _this.name = url;
  26277. _this.url = url;
  26278. _this._noMipmap = noMipmap;
  26279. _this._invertY = invertY;
  26280. _this._samplingMode = samplingMode;
  26281. _this._buffer = buffer;
  26282. _this._deleteBuffer = deleteBuffer;
  26283. _this._format = format;
  26284. if (!url) {
  26285. return _this;
  26286. }
  26287. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26288. var load = function () {
  26289. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26290. _this.onLoadObservable.notifyObservers(true);
  26291. }
  26292. if (onLoad) {
  26293. onLoad();
  26294. }
  26295. };
  26296. if (!_this._texture) {
  26297. if (!scene.useDelayedTextureLoading) {
  26298. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26299. if (deleteBuffer) {
  26300. delete _this._buffer;
  26301. }
  26302. }
  26303. else {
  26304. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26305. _this._delayedOnLoad = load;
  26306. _this._delayedOnError = onError;
  26307. }
  26308. }
  26309. else {
  26310. if (_this._texture.isReady) {
  26311. BABYLON.Tools.SetImmediate(function () { return load(); });
  26312. }
  26313. else {
  26314. _this._texture.onLoadedCallbacks.push(load);
  26315. }
  26316. }
  26317. return _this;
  26318. }
  26319. Object.defineProperty(Texture.prototype, "noMipmap", {
  26320. get: function () {
  26321. return this._noMipmap;
  26322. },
  26323. enumerable: true,
  26324. configurable: true
  26325. });
  26326. Texture.prototype.delayLoad = function () {
  26327. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26328. return;
  26329. }
  26330. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26331. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26332. if (!this._texture) {
  26333. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26334. if (this._deleteBuffer) {
  26335. delete this._buffer;
  26336. }
  26337. }
  26338. };
  26339. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26340. if (!this._texture) {
  26341. return;
  26342. }
  26343. this._samplingMode = samplingMode;
  26344. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26345. };
  26346. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26347. x *= this.uScale;
  26348. y *= this.vScale;
  26349. x -= 0.5 * this.uScale;
  26350. y -= 0.5 * this.vScale;
  26351. z -= 0.5;
  26352. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26353. t.x += 0.5 * this.uScale + this.uOffset;
  26354. t.y += 0.5 * this.vScale + this.vOffset;
  26355. t.z += 0.5;
  26356. };
  26357. Texture.prototype.getTextureMatrix = function () {
  26358. if (this.uOffset === this._cachedUOffset &&
  26359. this.vOffset === this._cachedVOffset &&
  26360. this.uScale === this._cachedUScale &&
  26361. this.vScale === this._cachedVScale &&
  26362. this.uAng === this._cachedUAng &&
  26363. this.vAng === this._cachedVAng &&
  26364. this.wAng === this._cachedWAng) {
  26365. return this._cachedTextureMatrix;
  26366. }
  26367. this._cachedUOffset = this.uOffset;
  26368. this._cachedVOffset = this.vOffset;
  26369. this._cachedUScale = this.uScale;
  26370. this._cachedVScale = this.vScale;
  26371. this._cachedUAng = this.uAng;
  26372. this._cachedVAng = this.vAng;
  26373. this._cachedWAng = this.wAng;
  26374. if (!this._cachedTextureMatrix) {
  26375. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26376. this._rowGenerationMatrix = new BABYLON.Matrix();
  26377. this._t0 = BABYLON.Vector3.Zero();
  26378. this._t1 = BABYLON.Vector3.Zero();
  26379. this._t2 = BABYLON.Vector3.Zero();
  26380. }
  26381. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26382. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26383. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26384. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26385. this._t1.subtractInPlace(this._t0);
  26386. this._t2.subtractInPlace(this._t0);
  26387. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26388. this._cachedTextureMatrix.m[0] = this._t1.x;
  26389. this._cachedTextureMatrix.m[1] = this._t1.y;
  26390. this._cachedTextureMatrix.m[2] = this._t1.z;
  26391. this._cachedTextureMatrix.m[4] = this._t2.x;
  26392. this._cachedTextureMatrix.m[5] = this._t2.y;
  26393. this._cachedTextureMatrix.m[6] = this._t2.z;
  26394. this._cachedTextureMatrix.m[8] = this._t0.x;
  26395. this._cachedTextureMatrix.m[9] = this._t0.y;
  26396. this._cachedTextureMatrix.m[10] = this._t0.z;
  26397. return this._cachedTextureMatrix;
  26398. };
  26399. Texture.prototype.getReflectionTextureMatrix = function () {
  26400. if (this.uOffset === this._cachedUOffset &&
  26401. this.vOffset === this._cachedVOffset &&
  26402. this.uScale === this._cachedUScale &&
  26403. this.vScale === this._cachedVScale &&
  26404. this.coordinatesMode === this._cachedCoordinatesMode) {
  26405. return this._cachedTextureMatrix;
  26406. }
  26407. if (!this._cachedTextureMatrix) {
  26408. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26409. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26410. }
  26411. this._cachedCoordinatesMode = this.coordinatesMode;
  26412. switch (this.coordinatesMode) {
  26413. case Texture.PLANAR_MODE:
  26414. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26415. this._cachedTextureMatrix[0] = this.uScale;
  26416. this._cachedTextureMatrix[5] = this.vScale;
  26417. this._cachedTextureMatrix[12] = this.uOffset;
  26418. this._cachedTextureMatrix[13] = this.vOffset;
  26419. break;
  26420. case Texture.PROJECTION_MODE:
  26421. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26422. this._projectionModeMatrix.m[0] = 0.5;
  26423. this._projectionModeMatrix.m[5] = -0.5;
  26424. this._projectionModeMatrix.m[10] = 0.0;
  26425. this._projectionModeMatrix.m[12] = 0.5;
  26426. this._projectionModeMatrix.m[13] = 0.5;
  26427. this._projectionModeMatrix.m[14] = 1.0;
  26428. this._projectionModeMatrix.m[15] = 1.0;
  26429. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26430. break;
  26431. default:
  26432. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26433. break;
  26434. }
  26435. return this._cachedTextureMatrix;
  26436. };
  26437. Texture.prototype.clone = function () {
  26438. var _this = this;
  26439. return BABYLON.SerializationHelper.Clone(function () {
  26440. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26441. }, this);
  26442. };
  26443. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26444. get: function () {
  26445. if (!this._onLoadObservarble) {
  26446. this._onLoadObservarble = new BABYLON.Observable();
  26447. }
  26448. return this._onLoadObservarble;
  26449. },
  26450. enumerable: true,
  26451. configurable: true
  26452. });
  26453. // Statics
  26454. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26455. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26456. if (onLoad === void 0) { onLoad = null; }
  26457. if (onError === void 0) { onError = null; }
  26458. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26459. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26460. };
  26461. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26462. if (parsedTexture.customType) {
  26463. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26464. return customTexture.Parse(parsedTexture, scene, rootUrl);
  26465. }
  26466. if (parsedTexture.isCube) {
  26467. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26468. }
  26469. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26470. return null;
  26471. }
  26472. var texture = BABYLON.SerializationHelper.Parse(function () {
  26473. if (parsedTexture.mirrorPlane) {
  26474. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26475. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26476. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26477. return mirrorTexture;
  26478. }
  26479. else if (parsedTexture.isRenderTarget) {
  26480. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26481. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26482. return renderTargetTexture;
  26483. }
  26484. else {
  26485. var texture;
  26486. if (parsedTexture.base64String) {
  26487. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  26488. }
  26489. else {
  26490. texture = new Texture(rootUrl + parsedTexture.name, scene);
  26491. }
  26492. return texture;
  26493. }
  26494. }, parsedTexture, scene);
  26495. // Animations
  26496. if (parsedTexture.animations) {
  26497. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26498. var parsedAnimation = parsedTexture.animations[animationIndex];
  26499. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26500. }
  26501. }
  26502. return texture;
  26503. };
  26504. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26505. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26506. if (noMipmap === void 0) { noMipmap = false; }
  26507. if (invertY === void 0) { invertY = true; }
  26508. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26509. if (onLoad === void 0) { onLoad = null; }
  26510. if (onError === void 0) { onError = null; }
  26511. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26512. if (name.substr(0, 5) !== "data:") {
  26513. name = "data:" + name;
  26514. }
  26515. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26516. };
  26517. return Texture;
  26518. }(BABYLON.BaseTexture));
  26519. // Constants
  26520. Texture.NEAREST_SAMPLINGMODE = 1;
  26521. Texture.BILINEAR_SAMPLINGMODE = 2;
  26522. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26523. Texture.EXPLICIT_MODE = 0;
  26524. Texture.SPHERICAL_MODE = 1;
  26525. Texture.PLANAR_MODE = 2;
  26526. Texture.CUBIC_MODE = 3;
  26527. Texture.PROJECTION_MODE = 4;
  26528. Texture.SKYBOX_MODE = 5;
  26529. Texture.INVCUBIC_MODE = 6;
  26530. Texture.EQUIRECTANGULAR_MODE = 7;
  26531. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26532. Texture.CLAMP_ADDRESSMODE = 0;
  26533. Texture.WRAP_ADDRESSMODE = 1;
  26534. Texture.MIRROR_ADDRESSMODE = 2;
  26535. __decorate([
  26536. BABYLON.serialize()
  26537. ], Texture.prototype, "url", void 0);
  26538. __decorate([
  26539. BABYLON.serialize()
  26540. ], Texture.prototype, "uOffset", void 0);
  26541. __decorate([
  26542. BABYLON.serialize()
  26543. ], Texture.prototype, "vOffset", void 0);
  26544. __decorate([
  26545. BABYLON.serialize()
  26546. ], Texture.prototype, "uScale", void 0);
  26547. __decorate([
  26548. BABYLON.serialize()
  26549. ], Texture.prototype, "vScale", void 0);
  26550. __decorate([
  26551. BABYLON.serialize()
  26552. ], Texture.prototype, "uAng", void 0);
  26553. __decorate([
  26554. BABYLON.serialize()
  26555. ], Texture.prototype, "vAng", void 0);
  26556. __decorate([
  26557. BABYLON.serialize()
  26558. ], Texture.prototype, "wAng", void 0);
  26559. BABYLON.Texture = Texture;
  26560. })(BABYLON || (BABYLON = {}));
  26561. //# sourceMappingURL=babylon.texture.js.map
  26562. var BABYLON;
  26563. (function (BABYLON) {
  26564. var CubeTexture = (function (_super) {
  26565. __extends(CubeTexture, _super);
  26566. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  26567. if (onLoad === void 0) { onLoad = null; }
  26568. if (onError === void 0) { onError = null; }
  26569. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26570. var _this = _super.call(this, scene) || this;
  26571. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  26572. _this.name = rootUrl;
  26573. _this.url = rootUrl;
  26574. _this._noMipmap = noMipmap;
  26575. _this.hasAlpha = false;
  26576. _this._format = format;
  26577. if (!rootUrl && !files) {
  26578. return _this;
  26579. }
  26580. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  26581. if (!files) {
  26582. if (!extensions) {
  26583. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  26584. }
  26585. files = [];
  26586. for (var index = 0; index < extensions.length; index++) {
  26587. files.push(rootUrl + extensions[index]);
  26588. }
  26589. _this._extensions = extensions;
  26590. }
  26591. _this._files = files;
  26592. if (!_this._texture) {
  26593. if (!scene.useDelayedTextureLoading) {
  26594. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  26595. }
  26596. else {
  26597. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26598. }
  26599. }
  26600. else if (onLoad) {
  26601. if (_this._texture.isReady) {
  26602. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  26603. }
  26604. else {
  26605. _this._texture.onLoadedCallbacks.push(onLoad);
  26606. }
  26607. }
  26608. _this.isCube = true;
  26609. _this._textureMatrix = BABYLON.Matrix.Identity();
  26610. return _this;
  26611. }
  26612. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  26613. return new CubeTexture("", scene, null, noMipmap, files);
  26614. };
  26615. // Methods
  26616. CubeTexture.prototype.delayLoad = function () {
  26617. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26618. return;
  26619. }
  26620. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26621. this._texture = this._getFromCache(this.url, this._noMipmap);
  26622. if (!this._texture) {
  26623. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  26624. }
  26625. };
  26626. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  26627. return this._textureMatrix;
  26628. };
  26629. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  26630. var texture = BABYLON.SerializationHelper.Parse(function () {
  26631. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  26632. }, parsedTexture, scene);
  26633. // Animations
  26634. if (parsedTexture.animations) {
  26635. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26636. var parsedAnimation = parsedTexture.animations[animationIndex];
  26637. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26638. }
  26639. }
  26640. return texture;
  26641. };
  26642. CubeTexture.prototype.clone = function () {
  26643. var _this = this;
  26644. return BABYLON.SerializationHelper.Clone(function () {
  26645. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  26646. }, this);
  26647. };
  26648. return CubeTexture;
  26649. }(BABYLON.BaseTexture));
  26650. BABYLON.CubeTexture = CubeTexture;
  26651. })(BABYLON || (BABYLON = {}));
  26652. //# sourceMappingURL=babylon.cubeTexture.js.map
  26653. var BABYLON;
  26654. (function (BABYLON) {
  26655. var RenderTargetTexture = (function (_super) {
  26656. __extends(RenderTargetTexture, _super);
  26657. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  26658. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  26659. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26660. if (isCube === void 0) { isCube = false; }
  26661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26662. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  26663. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  26664. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  26665. _this.isCube = isCube;
  26666. /**
  26667. * Use this list to define the list of mesh you want to render.
  26668. */
  26669. _this.renderList = new Array();
  26670. _this.renderParticles = true;
  26671. _this.renderSprites = false;
  26672. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  26673. // Events
  26674. /**
  26675. * An event triggered when the texture is unbind.
  26676. * @type {BABYLON.Observable}
  26677. */
  26678. _this.onAfterUnbindObservable = new BABYLON.Observable();
  26679. /**
  26680. * An event triggered before rendering the texture
  26681. * @type {BABYLON.Observable}
  26682. */
  26683. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26684. /**
  26685. * An event triggered after rendering the texture
  26686. * @type {BABYLON.Observable}
  26687. */
  26688. _this.onAfterRenderObservable = new BABYLON.Observable();
  26689. /**
  26690. * An event triggered after the texture clear
  26691. * @type {BABYLON.Observable}
  26692. */
  26693. _this.onClearObservable = new BABYLON.Observable();
  26694. _this._currentRefreshId = -1;
  26695. _this._refreshRate = 1;
  26696. _this.name = name;
  26697. _this.isRenderTarget = true;
  26698. _this._size = size;
  26699. _this._generateMipMaps = generateMipMaps;
  26700. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  26701. _this._renderTargetOptions = {
  26702. generateMipMaps: generateMipMaps,
  26703. type: type,
  26704. samplingMode: samplingMode,
  26705. generateDepthBuffer: generateDepthBuffer,
  26706. generateStencilBuffer: generateStencilBuffer
  26707. };
  26708. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26709. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26710. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26711. }
  26712. if (isCube) {
  26713. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  26714. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  26715. _this._textureMatrix = BABYLON.Matrix.Identity();
  26716. }
  26717. else {
  26718. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  26719. }
  26720. // Rendering groups
  26721. _this._renderingManager = new BABYLON.RenderingManager(scene);
  26722. return _this;
  26723. }
  26724. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  26725. get: function () {
  26726. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  26727. },
  26728. enumerable: true,
  26729. configurable: true
  26730. });
  26731. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  26732. get: function () {
  26733. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  26734. },
  26735. enumerable: true,
  26736. configurable: true
  26737. });
  26738. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  26739. get: function () {
  26740. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  26741. },
  26742. enumerable: true,
  26743. configurable: true
  26744. });
  26745. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  26746. set: function (callback) {
  26747. if (this._onAfterUnbindObserver) {
  26748. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  26749. }
  26750. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  26751. },
  26752. enumerable: true,
  26753. configurable: true
  26754. });
  26755. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  26756. set: function (callback) {
  26757. if (this._onBeforeRenderObserver) {
  26758. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26759. }
  26760. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  26766. set: function (callback) {
  26767. if (this._onAfterRenderObserver) {
  26768. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26769. }
  26770. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26771. },
  26772. enumerable: true,
  26773. configurable: true
  26774. });
  26775. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  26776. set: function (callback) {
  26777. if (this._onClearObserver) {
  26778. this.onClearObservable.remove(this._onClearObserver);
  26779. }
  26780. this._onClearObserver = this.onClearObservable.add(callback);
  26781. },
  26782. enumerable: true,
  26783. configurable: true
  26784. });
  26785. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  26786. this._currentRefreshId = -1;
  26787. };
  26788. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  26789. get: function () {
  26790. return this._refreshRate;
  26791. },
  26792. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  26793. set: function (value) {
  26794. this._refreshRate = value;
  26795. this.resetRefreshCounter();
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. RenderTargetTexture.prototype._shouldRender = function () {
  26801. if (this._currentRefreshId === -1) {
  26802. this._currentRefreshId = 1;
  26803. return true;
  26804. }
  26805. if (this.refreshRate === this._currentRefreshId) {
  26806. this._currentRefreshId = 1;
  26807. return true;
  26808. }
  26809. this._currentRefreshId++;
  26810. return false;
  26811. };
  26812. RenderTargetTexture.prototype.isReady = function () {
  26813. if (!this.getScene().renderTargetsEnabled) {
  26814. return false;
  26815. }
  26816. return _super.prototype.isReady.call(this);
  26817. };
  26818. RenderTargetTexture.prototype.getRenderSize = function () {
  26819. return this._size;
  26820. };
  26821. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  26822. get: function () {
  26823. return true;
  26824. },
  26825. enumerable: true,
  26826. configurable: true
  26827. });
  26828. RenderTargetTexture.prototype.scale = function (ratio) {
  26829. var newSize = this._size * ratio;
  26830. this.resize(newSize);
  26831. };
  26832. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  26833. if (this.isCube) {
  26834. return this._textureMatrix;
  26835. }
  26836. return _super.prototype.getReflectionTextureMatrix.call(this);
  26837. };
  26838. RenderTargetTexture.prototype.resize = function (size) {
  26839. this.releaseInternalTexture();
  26840. if (this.isCube) {
  26841. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  26842. }
  26843. else {
  26844. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  26845. }
  26846. };
  26847. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  26848. var scene = this.getScene();
  26849. var engine = scene.getEngine();
  26850. if (this.useCameraPostProcesses !== undefined) {
  26851. useCameraPostProcess = this.useCameraPostProcesses;
  26852. }
  26853. if (this._waitingRenderList) {
  26854. this.renderList = [];
  26855. for (var index = 0; index < this._waitingRenderList.length; index++) {
  26856. var id = this._waitingRenderList[index];
  26857. this.renderList.push(scene.getMeshByID(id));
  26858. }
  26859. delete this._waitingRenderList;
  26860. }
  26861. // Is predicate defined?
  26862. if (this.renderListPredicate) {
  26863. this.renderList.splice(0); // Clear previous renderList
  26864. var sceneMeshes = this.getScene().meshes;
  26865. for (var index = 0; index < sceneMeshes.length; index++) {
  26866. var mesh = sceneMeshes[index];
  26867. if (this.renderListPredicate(mesh)) {
  26868. this.renderList.push(mesh);
  26869. }
  26870. }
  26871. }
  26872. if (this.renderList && this.renderList.length === 0) {
  26873. return;
  26874. }
  26875. // Set custom projection.
  26876. // Needs to be before binding to prevent changing the aspect ratio.
  26877. if (this.activeCamera) {
  26878. engine.setViewport(this.activeCamera.viewport);
  26879. if (this.activeCamera !== scene.activeCamera) {
  26880. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  26881. }
  26882. }
  26883. else {
  26884. engine.setViewport(scene.activeCamera.viewport);
  26885. }
  26886. // Prepare renderingManager
  26887. this._renderingManager.reset();
  26888. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  26889. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  26890. var sceneRenderId = scene.getRenderId();
  26891. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  26892. var mesh = currentRenderList[meshIndex];
  26893. if (mesh) {
  26894. if (!mesh.isReady()) {
  26895. // Reset _currentRefreshId
  26896. this.resetRefreshCounter();
  26897. continue;
  26898. }
  26899. mesh._preActivateForIntermediateRendering(sceneRenderId);
  26900. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  26901. mesh._activate(sceneRenderId);
  26902. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26903. var subMesh = mesh.subMeshes[subIndex];
  26904. scene._activeIndices.addCount(subMesh.indexCount, false);
  26905. this._renderingManager.dispatch(subMesh);
  26906. }
  26907. }
  26908. }
  26909. }
  26910. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  26911. var particleSystem = scene.particleSystems[particleIndex];
  26912. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  26913. continue;
  26914. }
  26915. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  26916. this._renderingManager.dispatchParticles(particleSystem);
  26917. }
  26918. }
  26919. if (this.isCube) {
  26920. for (var face = 0; face < 6; face++) {
  26921. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26922. scene.incrementRenderId();
  26923. scene.resetCachedMaterial();
  26924. }
  26925. }
  26926. else {
  26927. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26928. }
  26929. this.onAfterUnbindObservable.notifyObservers(this);
  26930. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  26931. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  26932. }
  26933. engine.setViewport(scene.activeCamera.viewport);
  26934. scene.resetCachedMaterial();
  26935. };
  26936. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  26937. var scene = this.getScene();
  26938. var engine = scene.getEngine();
  26939. // Bind
  26940. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  26941. if (this.isCube) {
  26942. engine.bindFramebuffer(this._texture, faceIndex);
  26943. }
  26944. else {
  26945. engine.bindFramebuffer(this._texture);
  26946. }
  26947. }
  26948. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  26949. // Clear
  26950. if (this.onClearObservable.hasObservers()) {
  26951. this.onClearObservable.notifyObservers(engine);
  26952. }
  26953. else {
  26954. engine.clear(scene.clearColor, true, true, true);
  26955. }
  26956. if (!this._doNotChangeAspectRatio) {
  26957. scene.updateTransformMatrix(true);
  26958. }
  26959. // Render
  26960. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  26961. if (useCameraPostProcess) {
  26962. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  26963. }
  26964. if (!this._doNotChangeAspectRatio) {
  26965. scene.updateTransformMatrix(true);
  26966. }
  26967. this.onAfterRenderObservable.notifyObservers(faceIndex);
  26968. // Dump ?
  26969. if (dumpForDebug) {
  26970. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  26971. }
  26972. // Unbind
  26973. if (!this.isCube || faceIndex === 5) {
  26974. if (this.isCube) {
  26975. if (faceIndex === 5) {
  26976. engine.generateMipMapsForCubemap(this._texture);
  26977. }
  26978. }
  26979. engine.unBindFramebuffer(this._texture, this.isCube);
  26980. }
  26981. };
  26982. /**
  26983. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  26984. * This allowed control for front to back rendering or reversly depending of the special needs.
  26985. *
  26986. * @param renderingGroupId The rendering group id corresponding to its index
  26987. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  26988. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  26989. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  26990. */
  26991. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  26992. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  26993. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  26994. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  26995. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  26996. };
  26997. /**
  26998. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  26999. *
  27000. * @param renderingGroupId The rendering group id corresponding to its index
  27001. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27002. */
  27003. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27004. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27005. };
  27006. RenderTargetTexture.prototype.clone = function () {
  27007. var textureSize = this.getSize();
  27008. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  27009. // Base texture
  27010. newTexture.hasAlpha = this.hasAlpha;
  27011. newTexture.level = this.level;
  27012. // RenderTarget Texture
  27013. newTexture.coordinatesMode = this.coordinatesMode;
  27014. newTexture.renderList = this.renderList.slice(0);
  27015. return newTexture;
  27016. };
  27017. RenderTargetTexture.prototype.serialize = function () {
  27018. if (!this.name) {
  27019. return null;
  27020. }
  27021. var serializationObject = _super.prototype.serialize.call(this);
  27022. serializationObject.renderTargetSize = this.getRenderSize();
  27023. serializationObject.renderList = [];
  27024. for (var index = 0; index < this.renderList.length; index++) {
  27025. serializationObject.renderList.push(this.renderList[index].id);
  27026. }
  27027. return serializationObject;
  27028. };
  27029. return RenderTargetTexture;
  27030. }(BABYLON.Texture));
  27031. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27032. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27033. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27034. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27035. })(BABYLON || (BABYLON = {}));
  27036. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27037. var BABYLON;
  27038. (function (BABYLON) {
  27039. var ProceduralTexture = (function (_super) {
  27040. __extends(ProceduralTexture, _super);
  27041. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27043. if (isCube === void 0) { isCube = false; }
  27044. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27045. _this.isCube = isCube;
  27046. _this.isEnabled = true;
  27047. _this._currentRefreshId = -1;
  27048. _this._refreshRate = 1;
  27049. _this._vertexBuffers = {};
  27050. _this._uniforms = new Array();
  27051. _this._samplers = new Array();
  27052. _this._textures = new Array();
  27053. _this._floats = new Array();
  27054. _this._floatsArrays = {};
  27055. _this._colors3 = new Array();
  27056. _this._colors4 = new Array();
  27057. _this._vectors2 = new Array();
  27058. _this._vectors3 = new Array();
  27059. _this._matrices = new Array();
  27060. _this._fallbackTextureUsed = false;
  27061. scene._proceduralTextures.push(_this);
  27062. _this.name = name;
  27063. _this.isRenderTarget = true;
  27064. _this._size = size;
  27065. _this._generateMipMaps = generateMipMaps;
  27066. _this.setFragment(fragment);
  27067. _this._fallbackTexture = fallbackTexture;
  27068. var engine = scene.getEngine();
  27069. if (isCube) {
  27070. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27071. _this.setFloat("face", 0);
  27072. }
  27073. else {
  27074. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27075. }
  27076. // VBO
  27077. var vertices = [];
  27078. vertices.push(1, 1);
  27079. vertices.push(-1, 1);
  27080. vertices.push(-1, -1);
  27081. vertices.push(1, -1);
  27082. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27083. // Indices
  27084. var indices = [];
  27085. indices.push(0);
  27086. indices.push(1);
  27087. indices.push(2);
  27088. indices.push(0);
  27089. indices.push(2);
  27090. indices.push(3);
  27091. _this._indexBuffer = engine.createIndexBuffer(indices);
  27092. return _this;
  27093. }
  27094. ProceduralTexture.prototype.reset = function () {
  27095. if (this._effect === undefined) {
  27096. return;
  27097. }
  27098. var engine = this.getScene().getEngine();
  27099. engine._releaseEffect(this._effect);
  27100. };
  27101. ProceduralTexture.prototype.isReady = function () {
  27102. var _this = this;
  27103. var engine = this.getScene().getEngine();
  27104. var shaders;
  27105. if (!this._fragment) {
  27106. return false;
  27107. }
  27108. if (this._fallbackTextureUsed) {
  27109. return true;
  27110. }
  27111. if (this._fragment.fragmentElement !== undefined) {
  27112. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27113. }
  27114. else {
  27115. shaders = { vertex: "procedural", fragment: this._fragment };
  27116. }
  27117. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27118. _this.releaseInternalTexture();
  27119. if (_this._fallbackTexture) {
  27120. _this._texture = _this._fallbackTexture._texture;
  27121. _this._texture.references++;
  27122. }
  27123. _this._fallbackTextureUsed = true;
  27124. });
  27125. return this._effect.isReady();
  27126. };
  27127. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27128. this._currentRefreshId = -1;
  27129. };
  27130. ProceduralTexture.prototype.setFragment = function (fragment) {
  27131. this._fragment = fragment;
  27132. };
  27133. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27134. get: function () {
  27135. return this._refreshRate;
  27136. },
  27137. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27138. set: function (value) {
  27139. this._refreshRate = value;
  27140. this.resetRefreshCounter();
  27141. },
  27142. enumerable: true,
  27143. configurable: true
  27144. });
  27145. ProceduralTexture.prototype._shouldRender = function () {
  27146. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27147. return false;
  27148. }
  27149. if (this._fallbackTextureUsed) {
  27150. return false;
  27151. }
  27152. if (this._currentRefreshId === -1) {
  27153. this._currentRefreshId = 1;
  27154. return true;
  27155. }
  27156. if (this.refreshRate === this._currentRefreshId) {
  27157. this._currentRefreshId = 1;
  27158. return true;
  27159. }
  27160. this._currentRefreshId++;
  27161. return false;
  27162. };
  27163. ProceduralTexture.prototype.getRenderSize = function () {
  27164. return this._size;
  27165. };
  27166. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27167. if (this._fallbackTextureUsed) {
  27168. return;
  27169. }
  27170. this.releaseInternalTexture();
  27171. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27172. };
  27173. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27174. if (this._uniforms.indexOf(uniformName) === -1) {
  27175. this._uniforms.push(uniformName);
  27176. }
  27177. };
  27178. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27179. if (this._samplers.indexOf(name) === -1) {
  27180. this._samplers.push(name);
  27181. }
  27182. this._textures[name] = texture;
  27183. return this;
  27184. };
  27185. ProceduralTexture.prototype.setFloat = function (name, value) {
  27186. this._checkUniform(name);
  27187. this._floats[name] = value;
  27188. return this;
  27189. };
  27190. ProceduralTexture.prototype.setFloats = function (name, value) {
  27191. this._checkUniform(name);
  27192. this._floatsArrays[name] = value;
  27193. return this;
  27194. };
  27195. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27196. this._checkUniform(name);
  27197. this._colors3[name] = value;
  27198. return this;
  27199. };
  27200. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27201. this._checkUniform(name);
  27202. this._colors4[name] = value;
  27203. return this;
  27204. };
  27205. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27206. this._checkUniform(name);
  27207. this._vectors2[name] = value;
  27208. return this;
  27209. };
  27210. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27211. this._checkUniform(name);
  27212. this._vectors3[name] = value;
  27213. return this;
  27214. };
  27215. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27216. this._checkUniform(name);
  27217. this._matrices[name] = value;
  27218. return this;
  27219. };
  27220. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27221. var scene = this.getScene();
  27222. var engine = scene.getEngine();
  27223. // Render
  27224. engine.enableEffect(this._effect);
  27225. engine.setState(false);
  27226. // Texture
  27227. for (var name in this._textures) {
  27228. this._effect.setTexture(name, this._textures[name]);
  27229. }
  27230. // Float
  27231. for (name in this._floats) {
  27232. this._effect.setFloat(name, this._floats[name]);
  27233. }
  27234. // Floats
  27235. for (name in this._floatsArrays) {
  27236. this._effect.setArray(name, this._floatsArrays[name]);
  27237. }
  27238. // Color3
  27239. for (name in this._colors3) {
  27240. this._effect.setColor3(name, this._colors3[name]);
  27241. }
  27242. // Color4
  27243. for (name in this._colors4) {
  27244. var color = this._colors4[name];
  27245. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27246. }
  27247. // Vector2
  27248. for (name in this._vectors2) {
  27249. this._effect.setVector2(name, this._vectors2[name]);
  27250. }
  27251. // Vector3
  27252. for (name in this._vectors3) {
  27253. this._effect.setVector3(name, this._vectors3[name]);
  27254. }
  27255. // Matrix
  27256. for (name in this._matrices) {
  27257. this._effect.setMatrix(name, this._matrices[name]);
  27258. }
  27259. if (this.isCube) {
  27260. for (var face = 0; face < 6; face++) {
  27261. engine.bindFramebuffer(this._texture, face);
  27262. // VBOs
  27263. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27264. this._effect.setFloat("face", face);
  27265. // Clear
  27266. engine.clear(scene.clearColor, true, true, true);
  27267. // Draw order
  27268. engine.draw(true, 0, 6);
  27269. // Mipmaps
  27270. if (face === 5) {
  27271. engine.generateMipMapsForCubemap(this._texture);
  27272. }
  27273. }
  27274. }
  27275. else {
  27276. engine.bindFramebuffer(this._texture);
  27277. // VBOs
  27278. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27279. // Clear
  27280. engine.clear(scene.clearColor, true, true, true);
  27281. // Draw order
  27282. engine.draw(true, 0, 6);
  27283. }
  27284. // Unbind
  27285. engine.unBindFramebuffer(this._texture, this.isCube);
  27286. if (this.onGenerated) {
  27287. this.onGenerated();
  27288. }
  27289. };
  27290. ProceduralTexture.prototype.clone = function () {
  27291. var textureSize = this.getSize();
  27292. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27293. // Base texture
  27294. newTexture.hasAlpha = this.hasAlpha;
  27295. newTexture.level = this.level;
  27296. // RenderTarget Texture
  27297. newTexture.coordinatesMode = this.coordinatesMode;
  27298. return newTexture;
  27299. };
  27300. ProceduralTexture.prototype.dispose = function () {
  27301. var index = this.getScene()._proceduralTextures.indexOf(this);
  27302. if (index >= 0) {
  27303. this.getScene()._proceduralTextures.splice(index, 1);
  27304. }
  27305. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27306. if (vertexBuffer) {
  27307. vertexBuffer.dispose();
  27308. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27309. }
  27310. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  27311. this._indexBuffer = null;
  27312. }
  27313. _super.prototype.dispose.call(this);
  27314. };
  27315. return ProceduralTexture;
  27316. }(BABYLON.Texture));
  27317. BABYLON.ProceduralTexture = ProceduralTexture;
  27318. })(BABYLON || (BABYLON = {}));
  27319. //# sourceMappingURL=babylon.proceduralTexture.js.map
  27320. /// <reference path="babylon.renderTargetTexture.ts" />
  27321. var BABYLON;
  27322. (function (BABYLON) {
  27323. var MirrorTexture = (function (_super) {
  27324. __extends(MirrorTexture, _super);
  27325. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  27326. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27328. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27329. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  27330. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  27331. _this._transformMatrix = BABYLON.Matrix.Zero();
  27332. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  27333. _this.onBeforeRenderObservable.add(function () {
  27334. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  27335. _this._savedViewMatrix = scene.getViewMatrix();
  27336. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  27337. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  27338. scene.clipPlane = _this.mirrorPlane;
  27339. scene.getEngine().cullBackFaces = false;
  27340. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  27341. });
  27342. _this.onAfterRenderObservable.add(function () {
  27343. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  27344. scene.getEngine().cullBackFaces = true;
  27345. scene._mirroredCameraPosition = null;
  27346. delete scene.clipPlane;
  27347. });
  27348. return _this;
  27349. }
  27350. MirrorTexture.prototype.clone = function () {
  27351. var textureSize = this.getSize();
  27352. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  27353. // Base texture
  27354. newTexture.hasAlpha = this.hasAlpha;
  27355. newTexture.level = this.level;
  27356. // Mirror Texture
  27357. newTexture.mirrorPlane = this.mirrorPlane.clone();
  27358. newTexture.renderList = this.renderList.slice(0);
  27359. return newTexture;
  27360. };
  27361. MirrorTexture.prototype.serialize = function () {
  27362. if (!this.name) {
  27363. return null;
  27364. }
  27365. var serializationObject = _super.prototype.serialize.call(this);
  27366. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  27367. return serializationObject;
  27368. };
  27369. return MirrorTexture;
  27370. }(BABYLON.RenderTargetTexture));
  27371. BABYLON.MirrorTexture = MirrorTexture;
  27372. })(BABYLON || (BABYLON = {}));
  27373. //# sourceMappingURL=babylon.mirrorTexture.js.map
  27374. /// <reference path="babylon.renderTargetTexture.ts" />
  27375. var BABYLON;
  27376. (function (BABYLON) {
  27377. /**
  27378. * Creates a refraction texture used by refraction channel of the standard material.
  27379. * @param name the texture name
  27380. * @param size size of the underlying texture
  27381. * @param scene root scene
  27382. */
  27383. var RefractionTexture = (function (_super) {
  27384. __extends(RefractionTexture, _super);
  27385. function RefractionTexture(name, size, scene, generateMipMaps) {
  27386. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  27387. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  27388. _this.depth = 2.0;
  27389. _this.onBeforeRenderObservable.add(function () {
  27390. scene.clipPlane = _this.refractionPlane;
  27391. });
  27392. _this.onAfterRenderObservable.add(function () {
  27393. delete scene.clipPlane;
  27394. });
  27395. return _this;
  27396. }
  27397. RefractionTexture.prototype.clone = function () {
  27398. var textureSize = this.getSize();
  27399. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  27400. // Base texture
  27401. newTexture.hasAlpha = this.hasAlpha;
  27402. newTexture.level = this.level;
  27403. // Refraction Texture
  27404. newTexture.refractionPlane = this.refractionPlane.clone();
  27405. newTexture.renderList = this.renderList.slice(0);
  27406. newTexture.depth = this.depth;
  27407. return newTexture;
  27408. };
  27409. RefractionTexture.prototype.serialize = function () {
  27410. if (!this.name) {
  27411. return null;
  27412. }
  27413. var serializationObject = _super.prototype.serialize.call(this);
  27414. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  27415. serializationObject.depth = this.depth;
  27416. return serializationObject;
  27417. };
  27418. return RefractionTexture;
  27419. }(BABYLON.RenderTargetTexture));
  27420. BABYLON.RefractionTexture = RefractionTexture;
  27421. })(BABYLON || (BABYLON = {}));
  27422. //# sourceMappingURL=babylon.refractionTexture.js.map
  27423. /// <reference path="babylon.texture.ts" />
  27424. var BABYLON;
  27425. (function (BABYLON) {
  27426. var DynamicTexture = (function (_super) {
  27427. __extends(DynamicTexture, _super);
  27428. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  27429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27430. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27431. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  27432. _this.name = name;
  27433. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27434. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27435. _this._generateMipMaps = generateMipMaps;
  27436. if (options.getContext) {
  27437. _this._canvas = options;
  27438. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27439. }
  27440. else {
  27441. _this._canvas = document.createElement("canvas");
  27442. if (options.width) {
  27443. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27444. }
  27445. else {
  27446. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  27447. }
  27448. }
  27449. var textureSize = _this.getSize();
  27450. _this._canvas.width = textureSize.width;
  27451. _this._canvas.height = textureSize.height;
  27452. _this._context = _this._canvas.getContext("2d");
  27453. return _this;
  27454. }
  27455. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  27456. get: function () {
  27457. return true;
  27458. },
  27459. enumerable: true,
  27460. configurable: true
  27461. });
  27462. DynamicTexture.prototype.scale = function (ratio) {
  27463. var textureSize = this.getSize();
  27464. textureSize.width *= ratio;
  27465. textureSize.height *= ratio;
  27466. this._canvas.width = textureSize.width;
  27467. this._canvas.height = textureSize.height;
  27468. this.releaseInternalTexture();
  27469. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  27470. };
  27471. DynamicTexture.prototype.getContext = function () {
  27472. return this._context;
  27473. };
  27474. DynamicTexture.prototype.clear = function () {
  27475. var size = this.getSize();
  27476. this._context.fillRect(0, 0, size.width, size.height);
  27477. };
  27478. DynamicTexture.prototype.update = function (invertY) {
  27479. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  27480. };
  27481. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  27482. if (update === void 0) { update = true; }
  27483. var size = this.getSize();
  27484. if (clearColor) {
  27485. this._context.fillStyle = clearColor;
  27486. this._context.fillRect(0, 0, size.width, size.height);
  27487. }
  27488. this._context.font = font;
  27489. if (x === null) {
  27490. var textSize = this._context.measureText(text);
  27491. x = (size.width - textSize.width) / 2;
  27492. }
  27493. this._context.fillStyle = color;
  27494. this._context.fillText(text, x, y);
  27495. if (update) {
  27496. this.update(invertY);
  27497. }
  27498. };
  27499. DynamicTexture.prototype.clone = function () {
  27500. var textureSize = this.getSize();
  27501. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  27502. // Base texture
  27503. newTexture.hasAlpha = this.hasAlpha;
  27504. newTexture.level = this.level;
  27505. // Dynamic Texture
  27506. newTexture.wrapU = this.wrapU;
  27507. newTexture.wrapV = this.wrapV;
  27508. return newTexture;
  27509. };
  27510. return DynamicTexture;
  27511. }(BABYLON.Texture));
  27512. BABYLON.DynamicTexture = DynamicTexture;
  27513. })(BABYLON || (BABYLON = {}));
  27514. //# sourceMappingURL=babylon.dynamicTexture.js.map
  27515. var BABYLON;
  27516. (function (BABYLON) {
  27517. var VideoTexture = (function (_super) {
  27518. __extends(VideoTexture, _super);
  27519. /**
  27520. * Creates a video texture.
  27521. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  27522. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  27523. * @param {BABYLON.Scene} scene is obviously the current scene.
  27524. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  27525. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  27526. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  27527. */
  27528. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  27529. if (generateMipMaps === void 0) { generateMipMaps = false; }
  27530. if (invertY === void 0) { invertY = false; }
  27531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27532. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  27533. _this._autoLaunch = true;
  27534. var urls;
  27535. _this.name = name;
  27536. if (urlsOrVideo instanceof HTMLVideoElement) {
  27537. _this.video = urlsOrVideo;
  27538. }
  27539. else {
  27540. urls = urlsOrVideo;
  27541. _this.video = document.createElement("video");
  27542. _this.video.autoplay = false;
  27543. _this.video.loop = true;
  27544. }
  27545. _this._generateMipMaps = generateMipMaps;
  27546. _this._samplingMode = samplingMode;
  27547. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  27548. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27549. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27550. }
  27551. else {
  27552. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27553. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27554. _this._generateMipMaps = false;
  27555. }
  27556. if (urls) {
  27557. _this.video.addEventListener("canplaythrough", function () {
  27558. _this._createTexture();
  27559. });
  27560. urls.forEach(function (url) {
  27561. var source = document.createElement("source");
  27562. source.src = url;
  27563. _this.video.appendChild(source);
  27564. });
  27565. }
  27566. else {
  27567. _this._createTexture();
  27568. }
  27569. _this._lastUpdate = BABYLON.Tools.Now;
  27570. return _this;
  27571. }
  27572. VideoTexture.prototype._createTexture = function () {
  27573. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  27574. this._texture.isReady = true;
  27575. };
  27576. VideoTexture.prototype.update = function () {
  27577. if (this._autoLaunch) {
  27578. this._autoLaunch = false;
  27579. this.video.play();
  27580. }
  27581. var now = BABYLON.Tools.Now;
  27582. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  27583. return false;
  27584. }
  27585. this._lastUpdate = now;
  27586. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  27587. return true;
  27588. };
  27589. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  27590. var video = document.createElement("video");
  27591. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  27592. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  27593. if (navigator.getUserMedia) {
  27594. navigator.getUserMedia({
  27595. video: {
  27596. width: {
  27597. min: (constraints && constraints.minWidth) || 256,
  27598. max: (constraints && constraints.maxWidth) || 640
  27599. },
  27600. height: {
  27601. min: (constraints && constraints.minHeight) || 256,
  27602. max: (constraints && constraints.maxHeight) || 480
  27603. }
  27604. }
  27605. }, function (stream) {
  27606. if (video.mozSrcObject !== undefined) {
  27607. video.mozSrcObject = stream;
  27608. }
  27609. else {
  27610. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  27611. }
  27612. video.play();
  27613. if (onReady) {
  27614. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  27615. }
  27616. }, function (e) {
  27617. BABYLON.Tools.Error(e.name);
  27618. });
  27619. }
  27620. };
  27621. return VideoTexture;
  27622. }(BABYLON.Texture));
  27623. BABYLON.VideoTexture = VideoTexture;
  27624. })(BABYLON || (BABYLON = {}));
  27625. //# sourceMappingURL=babylon.videoTexture.js.map
  27626. /// <reference path="babylon.proceduralTexture.ts" />
  27627. var BABYLON;
  27628. (function (BABYLON) {
  27629. var CustomProceduralTexture = (function (_super) {
  27630. __extends(CustomProceduralTexture, _super);
  27631. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  27632. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  27633. _this._animate = true;
  27634. _this._time = 0;
  27635. _this._texturePath = texturePath;
  27636. //Try to load json
  27637. _this.loadJson(texturePath);
  27638. _this.refreshRate = 1;
  27639. return _this;
  27640. }
  27641. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  27642. var _this = this;
  27643. var that = this;
  27644. function noConfigFile() {
  27645. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  27646. try {
  27647. that.setFragment(that._texturePath);
  27648. }
  27649. catch (ex) {
  27650. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  27651. }
  27652. }
  27653. var configFileUrl = jsonUrl + "/config.json";
  27654. var xhr = new XMLHttpRequest();
  27655. xhr.open("GET", configFileUrl, true);
  27656. xhr.addEventListener("load", function () {
  27657. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  27658. try {
  27659. _this._config = JSON.parse(xhr.response);
  27660. _this.updateShaderUniforms();
  27661. _this.updateTextures();
  27662. _this.setFragment(_this._texturePath + "/custom");
  27663. _this._animate = _this._config.animate;
  27664. _this.refreshRate = _this._config.refreshrate;
  27665. }
  27666. catch (ex) {
  27667. noConfigFile();
  27668. }
  27669. }
  27670. else {
  27671. noConfigFile();
  27672. }
  27673. }, false);
  27674. xhr.addEventListener("error", function () {
  27675. noConfigFile();
  27676. }, false);
  27677. try {
  27678. xhr.send();
  27679. }
  27680. catch (ex) {
  27681. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  27682. }
  27683. };
  27684. CustomProceduralTexture.prototype.isReady = function () {
  27685. if (!_super.prototype.isReady.call(this)) {
  27686. return false;
  27687. }
  27688. for (var name in this._textures) {
  27689. var texture = this._textures[name];
  27690. if (!texture.isReady()) {
  27691. return false;
  27692. }
  27693. }
  27694. return true;
  27695. };
  27696. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27697. if (this._animate) {
  27698. this._time += this.getScene().getAnimationRatio() * 0.03;
  27699. this.updateShaderUniforms();
  27700. }
  27701. _super.prototype.render.call(this, useCameraPostProcess);
  27702. };
  27703. CustomProceduralTexture.prototype.updateTextures = function () {
  27704. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  27705. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  27706. }
  27707. };
  27708. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  27709. if (this._config) {
  27710. for (var j = 0; j < this._config.uniforms.length; j++) {
  27711. var uniform = this._config.uniforms[j];
  27712. switch (uniform.type) {
  27713. case "float":
  27714. this.setFloat(uniform.name, uniform.value);
  27715. break;
  27716. case "color3":
  27717. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  27718. break;
  27719. case "color4":
  27720. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  27721. break;
  27722. case "vector2":
  27723. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  27724. break;
  27725. case "vector3":
  27726. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  27727. break;
  27728. }
  27729. }
  27730. }
  27731. this.setFloat("time", this._time);
  27732. };
  27733. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  27734. get: function () {
  27735. return this._animate;
  27736. },
  27737. set: function (value) {
  27738. this._animate = value;
  27739. },
  27740. enumerable: true,
  27741. configurable: true
  27742. });
  27743. return CustomProceduralTexture;
  27744. }(BABYLON.ProceduralTexture));
  27745. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  27746. })(BABYLON || (BABYLON = {}));
  27747. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  27748. var BABYLON;
  27749. (function (BABYLON) {
  27750. var EffectFallbacks = (function () {
  27751. function EffectFallbacks() {
  27752. this._defines = {};
  27753. this._currentRank = 32;
  27754. this._maxRank = -1;
  27755. }
  27756. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27757. if (!this._defines[rank]) {
  27758. if (rank < this._currentRank) {
  27759. this._currentRank = rank;
  27760. }
  27761. if (rank > this._maxRank) {
  27762. this._maxRank = rank;
  27763. }
  27764. this._defines[rank] = new Array();
  27765. }
  27766. this._defines[rank].push(define);
  27767. };
  27768. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27769. this._meshRank = rank;
  27770. this._mesh = mesh;
  27771. if (rank > this._maxRank) {
  27772. this._maxRank = rank;
  27773. }
  27774. };
  27775. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  27776. get: function () {
  27777. return this._currentRank <= this._maxRank;
  27778. },
  27779. enumerable: true,
  27780. configurable: true
  27781. });
  27782. EffectFallbacks.prototype.reduce = function (currentDefines) {
  27783. var currentFallbacks = this._defines[this._currentRank];
  27784. for (var index = 0; index < currentFallbacks.length; index++) {
  27785. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  27786. }
  27787. if (this._mesh && this._currentRank === this._meshRank) {
  27788. this._mesh.computeBonesUsingShaders = false;
  27789. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  27790. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  27791. }
  27792. this._currentRank++;
  27793. return currentDefines;
  27794. };
  27795. return EffectFallbacks;
  27796. }());
  27797. BABYLON.EffectFallbacks = EffectFallbacks;
  27798. var Effect = (function () {
  27799. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  27800. var _this = this;
  27801. this.uniqueId = 0;
  27802. this._isReady = false;
  27803. this._compilationError = "";
  27804. this._valueCache = {};
  27805. this._engine = engine;
  27806. this.name = baseName;
  27807. this.defines = defines;
  27808. this._uniformsNames = uniformsNames.concat(samplers);
  27809. this._samplers = samplers;
  27810. this._attributesNames = attributesNames;
  27811. this.onError = onError;
  27812. this.onCompiled = onCompiled;
  27813. this._indexParameters = indexParameters;
  27814. this.uniqueId = Effect._uniqueIdSeed++;
  27815. var vertexSource;
  27816. var fragmentSource;
  27817. if (baseName.vertexElement) {
  27818. vertexSource = document.getElementById(baseName.vertexElement);
  27819. if (!vertexSource) {
  27820. vertexSource = baseName.vertexElement;
  27821. }
  27822. }
  27823. else {
  27824. vertexSource = baseName.vertex || baseName;
  27825. }
  27826. if (baseName.fragmentElement) {
  27827. fragmentSource = document.getElementById(baseName.fragmentElement);
  27828. if (!fragmentSource) {
  27829. fragmentSource = baseName.fragmentElement;
  27830. }
  27831. }
  27832. else {
  27833. fragmentSource = baseName.fragment || baseName;
  27834. }
  27835. this._loadVertexShader(vertexSource, function (vertexCode) {
  27836. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  27837. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  27838. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  27839. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  27840. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  27841. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  27842. });
  27843. });
  27844. });
  27845. });
  27846. });
  27847. });
  27848. }
  27849. Object.defineProperty(Effect.prototype, "key", {
  27850. get: function () {
  27851. return this._key;
  27852. },
  27853. enumerable: true,
  27854. configurable: true
  27855. });
  27856. // Properties
  27857. Effect.prototype.isReady = function () {
  27858. return this._isReady;
  27859. };
  27860. Effect.prototype.getProgram = function () {
  27861. return this._program;
  27862. };
  27863. Effect.prototype.getAttributesNames = function () {
  27864. return this._attributesNames;
  27865. };
  27866. Effect.prototype.getAttributeLocation = function (index) {
  27867. return this._attributes[index];
  27868. };
  27869. Effect.prototype.getAttributeLocationByName = function (name) {
  27870. var index = this._attributesNames.indexOf(name);
  27871. return this._attributes[index];
  27872. };
  27873. Effect.prototype.getAttributesCount = function () {
  27874. return this._attributes.length;
  27875. };
  27876. Effect.prototype.getUniformIndex = function (uniformName) {
  27877. return this._uniformsNames.indexOf(uniformName);
  27878. };
  27879. Effect.prototype.getUniform = function (uniformName) {
  27880. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  27881. };
  27882. Effect.prototype.getSamplers = function () {
  27883. return this._samplers;
  27884. };
  27885. Effect.prototype.getCompilationError = function () {
  27886. return this._compilationError;
  27887. };
  27888. Effect.prototype.getVertexShaderSource = function () {
  27889. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  27890. };
  27891. Effect.prototype.getFragmentShaderSource = function () {
  27892. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  27893. };
  27894. // Methods
  27895. Effect.prototype._loadVertexShader = function (vertex, callback) {
  27896. // DOM element ?
  27897. if (vertex instanceof HTMLElement) {
  27898. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  27899. callback(vertexCode);
  27900. return;
  27901. }
  27902. // Base64 encoded ?
  27903. if (vertex.substr(0, 7) === "base64:") {
  27904. var vertexBinary = window.atob(vertex.substr(7));
  27905. callback(vertexBinary);
  27906. return;
  27907. }
  27908. // Is in local store ?
  27909. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  27910. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  27911. return;
  27912. }
  27913. var vertexShaderUrl;
  27914. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  27915. vertexShaderUrl = vertex;
  27916. }
  27917. else {
  27918. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  27919. }
  27920. // Vertex shader
  27921. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  27922. };
  27923. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  27924. // DOM element ?
  27925. if (fragment instanceof HTMLElement) {
  27926. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  27927. callback(fragmentCode);
  27928. return;
  27929. }
  27930. // Base64 encoded ?
  27931. if (fragment.substr(0, 7) === "base64:") {
  27932. var fragmentBinary = window.atob(fragment.substr(7));
  27933. callback(fragmentBinary);
  27934. return;
  27935. }
  27936. // Is in local store ?
  27937. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  27938. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  27939. return;
  27940. }
  27941. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  27942. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  27943. return;
  27944. }
  27945. var fragmentShaderUrl;
  27946. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  27947. fragmentShaderUrl = fragment;
  27948. }
  27949. else {
  27950. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  27951. }
  27952. // Fragment shader
  27953. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  27954. };
  27955. Effect.prototype._dumpShadersName = function () {
  27956. if (this.name.vertexElement) {
  27957. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  27958. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  27959. }
  27960. else if (this.name.vertex) {
  27961. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  27962. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  27963. }
  27964. else {
  27965. BABYLON.Tools.Error("Vertex shader:" + this.name);
  27966. BABYLON.Tools.Error("Fragment shader:" + this.name);
  27967. }
  27968. };
  27969. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  27970. var preparedSourceCode = this._processPrecision(sourceCode);
  27971. if (this._engine.webGLVersion == 1) {
  27972. callback(preparedSourceCode);
  27973. return;
  27974. }
  27975. // Already converted
  27976. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  27977. callback(preparedSourceCode);
  27978. return;
  27979. }
  27980. // Remove extensions
  27981. // #extension GL_OES_standard_derivatives : enable
  27982. // #extension GL_EXT_shader_texture_lod : enable
  27983. // #extension GL_EXT_frag_depth : enable
  27984. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  27985. var result = preparedSourceCode.replace(regex, "");
  27986. // Migrate to GLSL v300
  27987. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  27988. result = result.replace(/attribute[ \t]/g, "in ");
  27989. result = result.replace(/[ \t]attribute/g, " in");
  27990. if (isFragment) {
  27991. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  27992. result = result.replace(/texture2D\(/g, "texture(");
  27993. result = result.replace(/textureCube\(/g, "texture(");
  27994. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  27995. result = result.replace(/gl_FragColor/g, "glFragColor");
  27996. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  27997. }
  27998. callback(result);
  27999. };
  28000. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28001. var _this = this;
  28002. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28003. var match = regex.exec(sourceCode);
  28004. var returnValue = new String(sourceCode);
  28005. while (match != null) {
  28006. var includeFile = match[1];
  28007. if (Effect.IncludesShadersStore[includeFile]) {
  28008. // Substitution
  28009. var includeContent = Effect.IncludesShadersStore[includeFile];
  28010. if (match[2]) {
  28011. var splits = match[3].split(",");
  28012. for (var index = 0; index < splits.length; index += 2) {
  28013. var source = new RegExp(splits[index], "g");
  28014. var dest = splits[index + 1];
  28015. includeContent = includeContent.replace(source, dest);
  28016. }
  28017. }
  28018. if (match[4]) {
  28019. var indexString = match[5];
  28020. if (indexString.indexOf("..") !== -1) {
  28021. var indexSplits = indexString.split("..");
  28022. var minIndex = parseInt(indexSplits[0]);
  28023. var maxIndex = parseInt(indexSplits[1]);
  28024. var sourceIncludeContent = includeContent.slice(0);
  28025. includeContent = "";
  28026. if (isNaN(maxIndex)) {
  28027. maxIndex = this._indexParameters[indexSplits[1]];
  28028. }
  28029. for (var i = minIndex; i <= maxIndex; i++) {
  28030. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28031. }
  28032. }
  28033. else {
  28034. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28035. }
  28036. }
  28037. // Replace
  28038. returnValue = returnValue.replace(match[0], includeContent);
  28039. }
  28040. else {
  28041. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28042. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28043. Effect.IncludesShadersStore[includeFile] = fileContent;
  28044. _this._processIncludes(returnValue, callback);
  28045. });
  28046. return;
  28047. }
  28048. match = regex.exec(sourceCode);
  28049. }
  28050. callback(returnValue);
  28051. };
  28052. Effect.prototype._processPrecision = function (source) {
  28053. if (source.indexOf("precision highp float") === -1) {
  28054. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28055. source = "precision mediump float;\n" + source;
  28056. }
  28057. else {
  28058. source = "precision highp float;\n" + source;
  28059. }
  28060. }
  28061. else {
  28062. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28063. source = source.replace("precision highp float", "precision mediump float");
  28064. }
  28065. }
  28066. return source;
  28067. };
  28068. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28069. try {
  28070. var engine = this._engine;
  28071. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28072. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28073. this._attributes = engine.getAttributes(this._program, attributesNames);
  28074. var index;
  28075. for (index = 0; index < this._samplers.length; index++) {
  28076. var sampler = this.getUniform(this._samplers[index]);
  28077. if (sampler == null) {
  28078. this._samplers.splice(index, 1);
  28079. index--;
  28080. }
  28081. }
  28082. engine.bindSamplers(this);
  28083. this._compilationError = "";
  28084. this._isReady = true;
  28085. if (this.onCompiled) {
  28086. this.onCompiled(this);
  28087. }
  28088. }
  28089. catch (e) {
  28090. this._compilationError = e.message;
  28091. // Let's go through fallbacks then
  28092. BABYLON.Tools.Error("Unable to compile effect: ");
  28093. BABYLON.Tools.Error("Defines: " + defines);
  28094. BABYLON.Tools.Error("Error: " + this._compilationError);
  28095. this._dumpShadersName();
  28096. if (fallbacks && fallbacks.isMoreFallbacks) {
  28097. BABYLON.Tools.Error("Trying next fallback.");
  28098. defines = fallbacks.reduce(defines);
  28099. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28100. }
  28101. else {
  28102. if (this.onError) {
  28103. this.onError(this, this._compilationError);
  28104. }
  28105. }
  28106. }
  28107. };
  28108. Object.defineProperty(Effect.prototype, "isSupported", {
  28109. get: function () {
  28110. return this._compilationError === "";
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. Effect.prototype._bindTexture = function (channel, texture) {
  28116. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28117. };
  28118. Effect.prototype.setTexture = function (channel, texture) {
  28119. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28120. };
  28121. Effect.prototype.setTextureArray = function (channel, textures) {
  28122. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28123. var initialPos = this._samplers.indexOf(channel);
  28124. for (var index = 1; index < textures.length; index++) {
  28125. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28126. }
  28127. }
  28128. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28129. };
  28130. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28131. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28132. };
  28133. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28134. var changed = false;
  28135. var cache = this._valueCache[uniformName];
  28136. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28137. changed = true;
  28138. cache = new BABYLON.Matrix();
  28139. }
  28140. var tm = cache.m;
  28141. var om = matrix.m;
  28142. for (var index = 0; index < 16; index++) {
  28143. if (tm[index] !== om[index]) {
  28144. tm[index] = om[index];
  28145. changed = true;
  28146. }
  28147. }
  28148. this._valueCache[uniformName] = cache;
  28149. return changed;
  28150. };
  28151. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28152. var cache = this._valueCache[uniformName];
  28153. if (!cache) {
  28154. cache = [x, y];
  28155. this._valueCache[uniformName] = cache;
  28156. return true;
  28157. }
  28158. var changed = false;
  28159. if (cache[0] !== x) {
  28160. cache[0] = x;
  28161. changed = true;
  28162. }
  28163. if (cache[1] !== y) {
  28164. cache[1] = y;
  28165. changed = true;
  28166. }
  28167. return changed;
  28168. };
  28169. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28170. var cache = this._valueCache[uniformName];
  28171. if (!cache) {
  28172. cache = [x, y, z];
  28173. this._valueCache[uniformName] = cache;
  28174. return true;
  28175. }
  28176. var changed = false;
  28177. if (cache[0] !== x) {
  28178. cache[0] = x;
  28179. changed = true;
  28180. }
  28181. if (cache[1] !== y) {
  28182. cache[1] = y;
  28183. changed = true;
  28184. }
  28185. if (cache[2] !== z) {
  28186. cache[2] = z;
  28187. changed = true;
  28188. }
  28189. return changed;
  28190. };
  28191. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28192. var cache = this._valueCache[uniformName];
  28193. if (!cache) {
  28194. cache = [x, y, z, w];
  28195. this._valueCache[uniformName] = cache;
  28196. return true;
  28197. }
  28198. var changed = false;
  28199. if (cache[0] !== x) {
  28200. cache[0] = x;
  28201. changed = true;
  28202. }
  28203. if (cache[1] !== y) {
  28204. cache[1] = y;
  28205. changed = true;
  28206. }
  28207. if (cache[2] !== z) {
  28208. cache[2] = z;
  28209. changed = true;
  28210. }
  28211. if (cache[3] !== w) {
  28212. cache[3] = w;
  28213. changed = true;
  28214. }
  28215. return changed;
  28216. };
  28217. Effect.prototype.setIntArray = function (uniformName, array) {
  28218. this._valueCache[uniformName] = null;
  28219. this._engine.setIntArray(this.getUniform(uniformName), array);
  28220. return this;
  28221. };
  28222. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28223. this._valueCache[uniformName] = null;
  28224. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28225. return this;
  28226. };
  28227. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28228. this._valueCache[uniformName] = null;
  28229. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28230. return this;
  28231. };
  28232. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28233. this._valueCache[uniformName] = null;
  28234. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28235. return this;
  28236. };
  28237. Effect.prototype.setFloatArray = function (uniformName, array) {
  28238. this._valueCache[uniformName] = null;
  28239. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28240. return this;
  28241. };
  28242. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28243. this._valueCache[uniformName] = null;
  28244. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28245. return this;
  28246. };
  28247. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28248. this._valueCache[uniformName] = null;
  28249. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28250. return this;
  28251. };
  28252. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28253. this._valueCache[uniformName] = null;
  28254. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28255. return this;
  28256. };
  28257. Effect.prototype.setArray = function (uniformName, array) {
  28258. this._valueCache[uniformName] = null;
  28259. this._engine.setArray(this.getUniform(uniformName), array);
  28260. return this;
  28261. };
  28262. Effect.prototype.setArray2 = function (uniformName, array) {
  28263. this._valueCache[uniformName] = null;
  28264. this._engine.setArray2(this.getUniform(uniformName), array);
  28265. return this;
  28266. };
  28267. Effect.prototype.setArray3 = function (uniformName, array) {
  28268. this._valueCache[uniformName] = null;
  28269. this._engine.setArray3(this.getUniform(uniformName), array);
  28270. return this;
  28271. };
  28272. Effect.prototype.setArray4 = function (uniformName, array) {
  28273. this._valueCache[uniformName] = null;
  28274. this._engine.setArray4(this.getUniform(uniformName), array);
  28275. return this;
  28276. };
  28277. Effect.prototype.setMatrices = function (uniformName, matrices) {
  28278. this._valueCache[uniformName] = null;
  28279. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  28280. return this;
  28281. };
  28282. Effect.prototype.setMatrix = function (uniformName, matrix) {
  28283. if (this._cacheMatrix(uniformName, matrix)) {
  28284. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  28285. }
  28286. return this;
  28287. };
  28288. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  28289. this._valueCache[uniformName] = null;
  28290. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  28291. return this;
  28292. };
  28293. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  28294. this._valueCache[uniformName] = null;
  28295. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  28296. return this;
  28297. };
  28298. Effect.prototype.setFloat = function (uniformName, value) {
  28299. var cache = this._valueCache[uniformName];
  28300. if (cache !== undefined && cache === value)
  28301. return this;
  28302. this._valueCache[uniformName] = value;
  28303. this._engine.setFloat(this.getUniform(uniformName), value);
  28304. return this;
  28305. };
  28306. Effect.prototype.setBool = function (uniformName, bool) {
  28307. var cache = this._valueCache[uniformName];
  28308. if (cache !== undefined && cache === bool)
  28309. return this;
  28310. this._valueCache[uniformName] = bool;
  28311. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  28312. return this;
  28313. };
  28314. Effect.prototype.setVector2 = function (uniformName, vector2) {
  28315. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  28316. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  28317. }
  28318. return this;
  28319. };
  28320. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  28321. if (this._cacheFloat2(uniformName, x, y)) {
  28322. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  28323. }
  28324. return this;
  28325. };
  28326. Effect.prototype.setVector3 = function (uniformName, vector3) {
  28327. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  28328. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  28329. }
  28330. return this;
  28331. };
  28332. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  28333. if (this._cacheFloat3(uniformName, x, y, z)) {
  28334. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  28335. }
  28336. return this;
  28337. };
  28338. Effect.prototype.setVector4 = function (uniformName, vector4) {
  28339. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  28340. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  28341. }
  28342. return this;
  28343. };
  28344. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  28345. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  28346. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  28347. }
  28348. return this;
  28349. };
  28350. Effect.prototype.setColor3 = function (uniformName, color3) {
  28351. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  28352. this._engine.setColor3(this.getUniform(uniformName), color3);
  28353. }
  28354. return this;
  28355. };
  28356. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  28357. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  28358. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  28359. }
  28360. return this;
  28361. };
  28362. Effect.prototype._recombineShader = function (node) {
  28363. if (node.define) {
  28364. if (node.condition) {
  28365. var defineIndex = this.defines.indexOf("#define " + node.define);
  28366. if (defineIndex === -1) {
  28367. return null;
  28368. }
  28369. var nextComma = this.defines.indexOf("\n", defineIndex);
  28370. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  28371. var condition = defineValue + node.condition;
  28372. if (!eval(condition)) {
  28373. return null;
  28374. }
  28375. }
  28376. else if (node.ndef) {
  28377. if (this.defines.indexOf("#define " + node.define) !== -1) {
  28378. return null;
  28379. }
  28380. }
  28381. else if (this.defines.indexOf("#define " + node.define) === -1) {
  28382. return null;
  28383. }
  28384. }
  28385. var result = "";
  28386. for (var index = 0; index < node.children.length; index++) {
  28387. var line = node.children[index];
  28388. if (line.children) {
  28389. var combined = this._recombineShader(line);
  28390. if (combined !== null) {
  28391. result += combined + "\r\n";
  28392. }
  28393. continue;
  28394. }
  28395. if (line.length > 0) {
  28396. result += line + "\r\n";
  28397. }
  28398. }
  28399. return result;
  28400. };
  28401. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  28402. var root = {
  28403. children: []
  28404. };
  28405. var currentNode = root;
  28406. var lines = shaderString.split("\n");
  28407. for (var index = 0; index < lines.length; index++) {
  28408. var line = lines[index].trim();
  28409. // #ifdef
  28410. var pos = line.indexOf("#ifdef ");
  28411. if (pos !== -1) {
  28412. var define = line.substr(pos + 7);
  28413. var newNode = {
  28414. condition: null,
  28415. ndef: false,
  28416. define: define,
  28417. children: [],
  28418. parent: currentNode
  28419. };
  28420. currentNode.children.push(newNode);
  28421. currentNode = newNode;
  28422. continue;
  28423. }
  28424. // #ifndef
  28425. var pos = line.indexOf("#ifndef ");
  28426. if (pos !== -1) {
  28427. var define = line.substr(pos + 8);
  28428. newNode = {
  28429. condition: null,
  28430. define: define,
  28431. ndef: true,
  28432. children: [],
  28433. parent: currentNode
  28434. };
  28435. currentNode.children.push(newNode);
  28436. currentNode = newNode;
  28437. continue;
  28438. }
  28439. // #if
  28440. var pos = line.indexOf("#if ");
  28441. if (pos !== -1) {
  28442. var define = line.substr(pos + 4).trim();
  28443. var conditionPos = define.indexOf(" ");
  28444. newNode = {
  28445. condition: define.substr(conditionPos + 1),
  28446. define: define.substr(0, conditionPos),
  28447. ndef: false,
  28448. children: [],
  28449. parent: currentNode
  28450. };
  28451. currentNode.children.push(newNode);
  28452. currentNode = newNode;
  28453. continue;
  28454. }
  28455. // #endif
  28456. pos = line.indexOf("#endif");
  28457. if (pos !== -1) {
  28458. currentNode = currentNode.parent;
  28459. continue;
  28460. }
  28461. currentNode.children.push(line);
  28462. }
  28463. // Recombine
  28464. return this._recombineShader(root);
  28465. };
  28466. return Effect;
  28467. }());
  28468. Effect._uniqueIdSeed = 0;
  28469. // Statics
  28470. Effect.ShadersStore = {};
  28471. Effect.IncludesShadersStore = {};
  28472. BABYLON.Effect = Effect;
  28473. })(BABYLON || (BABYLON = {}));
  28474. //# sourceMappingURL=babylon.effect.js.map
  28475. var BABYLON;
  28476. (function (BABYLON) {
  28477. var MaterialHelper = (function () {
  28478. function MaterialHelper() {
  28479. }
  28480. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  28481. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28482. var lightIndex = 0;
  28483. var needNormals = false;
  28484. var needRebuild = false;
  28485. var needShadows = false;
  28486. var lightmapMode = false;
  28487. for (var index = 0; index < scene.lights.length; index++) {
  28488. var light = scene.lights[index];
  28489. if (!light.isEnabled()) {
  28490. continue;
  28491. }
  28492. // Excluded check
  28493. if (light._excludedMeshesIds.length > 0) {
  28494. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  28495. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  28496. if (excludedMesh) {
  28497. light.excludedMeshes.push(excludedMesh);
  28498. }
  28499. }
  28500. light._excludedMeshesIds = [];
  28501. }
  28502. // Included check
  28503. if (light._includedOnlyMeshesIds.length > 0) {
  28504. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  28505. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  28506. if (includedOnlyMesh) {
  28507. light.includedOnlyMeshes.push(includedOnlyMesh);
  28508. }
  28509. }
  28510. light._includedOnlyMeshesIds = [];
  28511. }
  28512. if (!light.canAffectMesh(mesh)) {
  28513. continue;
  28514. }
  28515. needNormals = true;
  28516. if (defines["LIGHT" + lightIndex] === undefined) {
  28517. needRebuild = true;
  28518. }
  28519. defines["LIGHT" + lightIndex] = true;
  28520. var type;
  28521. if (light instanceof BABYLON.SpotLight) {
  28522. type = "SPOTLIGHT" + lightIndex;
  28523. }
  28524. else if (light instanceof BABYLON.HemisphericLight) {
  28525. type = "HEMILIGHT" + lightIndex;
  28526. }
  28527. else if (light instanceof BABYLON.PointLight) {
  28528. type = "POINTLIGHT" + lightIndex;
  28529. }
  28530. else {
  28531. type = "DIRLIGHT" + lightIndex;
  28532. }
  28533. if (defines[type] === undefined) {
  28534. needRebuild = true;
  28535. }
  28536. defines[type] = true;
  28537. // Specular
  28538. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  28539. defines["SPECULARTERM"] = true;
  28540. }
  28541. // Shadows
  28542. if (scene.shadowsEnabled) {
  28543. var shadowGenerator = light.getShadowGenerator();
  28544. if (mesh && mesh.receiveShadows && shadowGenerator) {
  28545. if (defines["SHADOW" + lightIndex] === undefined) {
  28546. needRebuild = true;
  28547. }
  28548. defines["SHADOW" + lightIndex] = true;
  28549. defines["SHADOWS"] = true;
  28550. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  28551. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  28552. needRebuild = true;
  28553. }
  28554. defines["SHADOWVSM" + lightIndex] = true;
  28555. }
  28556. if (shadowGenerator.usePoissonSampling) {
  28557. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  28558. needRebuild = true;
  28559. }
  28560. defines["SHADOWPCF" + lightIndex] = true;
  28561. }
  28562. needShadows = true;
  28563. }
  28564. }
  28565. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  28566. lightmapMode = true;
  28567. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  28568. needRebuild = true;
  28569. }
  28570. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  28571. needRebuild = true;
  28572. }
  28573. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  28574. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  28575. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  28576. }
  28577. }
  28578. lightIndex++;
  28579. if (lightIndex === maxSimultaneousLights)
  28580. break;
  28581. }
  28582. var caps = scene.getEngine().getCaps();
  28583. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  28584. if (defines["SHADOWFULLFLOAT"] === undefined) {
  28585. needRebuild = true;
  28586. }
  28587. defines["SHADOWFULLFLOAT"] = true;
  28588. }
  28589. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  28590. needRebuild = true;
  28591. }
  28592. if (lightmapMode) {
  28593. defines["LIGHTMAPEXCLUDED"] = true;
  28594. }
  28595. if (needRebuild) {
  28596. defines.rebuild();
  28597. }
  28598. return needNormals;
  28599. };
  28600. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  28601. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28602. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28603. if (!defines["LIGHT" + lightIndex]) {
  28604. break;
  28605. }
  28606. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  28607. samplersList.push("shadowSampler" + lightIndex);
  28608. }
  28609. };
  28610. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  28611. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28612. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28613. if (!defines["LIGHT" + lightIndex]) {
  28614. break;
  28615. }
  28616. if (lightIndex > 0) {
  28617. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  28618. }
  28619. if (defines["SHADOW" + lightIndex]) {
  28620. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  28621. }
  28622. if (defines["SHADOWPCF" + lightIndex]) {
  28623. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  28624. }
  28625. if (defines["SHADOWVSM" + lightIndex]) {
  28626. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  28627. }
  28628. }
  28629. };
  28630. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  28631. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  28632. fallbacks.addCPUSkinningFallback(0, mesh);
  28633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28635. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  28636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28638. }
  28639. }
  28640. };
  28641. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  28642. if (defines["INSTANCES"]) {
  28643. attribs.push("world0");
  28644. attribs.push("world1");
  28645. attribs.push("world2");
  28646. attribs.push("world3");
  28647. }
  28648. };
  28649. // Bindings
  28650. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  28651. var shadowGenerator = light.getShadowGenerator();
  28652. if (mesh.receiveShadows && shadowGenerator) {
  28653. if (!light.needCube()) {
  28654. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  28655. }
  28656. else {
  28657. if (!depthValuesAlreadySet) {
  28658. depthValuesAlreadySet = true;
  28659. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  28660. }
  28661. }
  28662. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  28663. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  28664. }
  28665. return depthValuesAlreadySet;
  28666. };
  28667. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  28668. if (light instanceof BABYLON.PointLight) {
  28669. // Point Light
  28670. light.transferToEffect(effect, "vLightData" + lightIndex);
  28671. }
  28672. else if (light instanceof BABYLON.DirectionalLight) {
  28673. // Directional Light
  28674. light.transferToEffect(effect, "vLightData" + lightIndex);
  28675. }
  28676. else if (light instanceof BABYLON.SpotLight) {
  28677. // Spot Light
  28678. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  28679. }
  28680. else if (light instanceof BABYLON.HemisphericLight) {
  28681. // Hemispheric Light
  28682. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  28683. }
  28684. };
  28685. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  28686. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28687. var lightIndex = 0;
  28688. var depthValuesAlreadySet = false;
  28689. for (var index = 0; index < scene.lights.length; index++) {
  28690. var light = scene.lights[index];
  28691. if (!light.isEnabled()) {
  28692. continue;
  28693. }
  28694. if (!light.canAffectMesh(mesh)) {
  28695. continue;
  28696. }
  28697. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28698. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  28699. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  28700. if (defines["SPECULARTERM"]) {
  28701. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  28702. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  28703. }
  28704. // Shadows
  28705. if (scene.shadowsEnabled) {
  28706. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  28707. }
  28708. lightIndex++;
  28709. if (lightIndex === maxSimultaneousLights)
  28710. break;
  28711. }
  28712. };
  28713. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  28714. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  28715. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  28716. effect.setColor3("vFogColor", scene.fogColor);
  28717. }
  28718. };
  28719. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  28720. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28721. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  28722. if (matrices) {
  28723. effect.setMatrices("mBones", matrices);
  28724. }
  28725. }
  28726. };
  28727. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  28728. if (defines["LOGARITHMICDEPTH"]) {
  28729. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  28730. }
  28731. };
  28732. MaterialHelper.BindClipPlane = function (effect, scene) {
  28733. if (scene.clipPlane) {
  28734. var clipPlane = scene.clipPlane;
  28735. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28736. }
  28737. };
  28738. return MaterialHelper;
  28739. }());
  28740. BABYLON.MaterialHelper = MaterialHelper;
  28741. })(BABYLON || (BABYLON = {}));
  28742. //# sourceMappingURL=babylon.materialHelper.js.map
  28743. var BABYLON;
  28744. (function (BABYLON) {
  28745. var FresnelParameters = (function () {
  28746. function FresnelParameters() {
  28747. this.isEnabled = true;
  28748. this.leftColor = BABYLON.Color3.White();
  28749. this.rightColor = BABYLON.Color3.Black();
  28750. this.bias = 0;
  28751. this.power = 1;
  28752. }
  28753. FresnelParameters.prototype.clone = function () {
  28754. var newFresnelParameters = new FresnelParameters();
  28755. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  28756. return newFresnelParameters;
  28757. };
  28758. FresnelParameters.prototype.serialize = function () {
  28759. var serializationObject = {};
  28760. serializationObject.isEnabled = this.isEnabled;
  28761. serializationObject.leftColor = this.leftColor;
  28762. serializationObject.rightColor = this.rightColor;
  28763. serializationObject.bias = this.bias;
  28764. serializationObject.power = this.power;
  28765. return serializationObject;
  28766. };
  28767. FresnelParameters.Parse = function (parsedFresnelParameters) {
  28768. var fresnelParameters = new FresnelParameters();
  28769. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  28770. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  28771. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  28772. fresnelParameters.bias = parsedFresnelParameters.bias;
  28773. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  28774. return fresnelParameters;
  28775. };
  28776. return FresnelParameters;
  28777. }());
  28778. BABYLON.FresnelParameters = FresnelParameters;
  28779. })(BABYLON || (BABYLON = {}));
  28780. //# sourceMappingURL=babylon.fresnelParameters.js.map
  28781. var BABYLON;
  28782. (function (BABYLON) {
  28783. var MaterialDefines = (function () {
  28784. function MaterialDefines() {
  28785. }
  28786. MaterialDefines.prototype.rebuild = function () {
  28787. if (this._keys) {
  28788. delete this._keys;
  28789. }
  28790. this._keys = Object.keys(this);
  28791. };
  28792. MaterialDefines.prototype.isEqual = function (other) {
  28793. if (this._keys.length !== other._keys.length) {
  28794. return false;
  28795. }
  28796. for (var index = 0; index < this._keys.length; index++) {
  28797. var prop = this._keys[index];
  28798. if (this[prop] !== other[prop]) {
  28799. return false;
  28800. }
  28801. }
  28802. return true;
  28803. };
  28804. MaterialDefines.prototype.cloneTo = function (other) {
  28805. if (this._keys.length !== other._keys.length) {
  28806. other._keys = this._keys.slice(0);
  28807. }
  28808. for (var index = 0; index < this._keys.length; index++) {
  28809. var prop = this._keys[index];
  28810. other[prop] = this[prop];
  28811. }
  28812. };
  28813. MaterialDefines.prototype.reset = function () {
  28814. for (var index = 0; index < this._keys.length; index++) {
  28815. var prop = this._keys[index];
  28816. if (typeof (this[prop]) === "number") {
  28817. this[prop] = 0;
  28818. }
  28819. else {
  28820. this[prop] = false;
  28821. }
  28822. }
  28823. };
  28824. MaterialDefines.prototype.toString = function () {
  28825. var result = "";
  28826. for (var index = 0; index < this._keys.length; index++) {
  28827. var prop = this._keys[index];
  28828. if (typeof (this[prop]) === "number") {
  28829. result += "#define " + prop + " " + this[prop] + "\n";
  28830. }
  28831. else if (this[prop]) {
  28832. result += "#define " + prop + "\n";
  28833. }
  28834. }
  28835. return result;
  28836. };
  28837. return MaterialDefines;
  28838. }());
  28839. BABYLON.MaterialDefines = MaterialDefines;
  28840. var Material = (function () {
  28841. function Material(name, scene, doNotAdd) {
  28842. this.checkReadyOnEveryCall = false;
  28843. this.checkReadyOnlyOnce = false;
  28844. this.state = "";
  28845. this.alpha = 1.0;
  28846. this.backFaceCulling = true;
  28847. this.doNotSerialize = false;
  28848. /**
  28849. * An event triggered when the material is disposed.
  28850. * @type {BABYLON.Observable}
  28851. */
  28852. this.onDisposeObservable = new BABYLON.Observable();
  28853. /**
  28854. * An event triggered when the material is bound.
  28855. * @type {BABYLON.Observable}
  28856. */
  28857. this.onBindObservable = new BABYLON.Observable();
  28858. /**
  28859. * An event triggered when the material is unbound.
  28860. * @type {BABYLON.Observable}
  28861. */
  28862. this.onUnBindObservable = new BABYLON.Observable();
  28863. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28864. this.disableDepthWrite = false;
  28865. this.fogEnabled = true;
  28866. this.pointSize = 1.0;
  28867. this.zOffset = 0;
  28868. this._wasPreviouslyReady = false;
  28869. this._fillMode = Material.TriangleFillMode;
  28870. this.name = name;
  28871. this.id = name;
  28872. this._scene = scene;
  28873. if (scene.useRightHandedSystem) {
  28874. this.sideOrientation = Material.ClockWiseSideOrientation;
  28875. }
  28876. else {
  28877. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28878. }
  28879. if (!doNotAdd) {
  28880. scene.materials.push(this);
  28881. }
  28882. }
  28883. Object.defineProperty(Material, "TriangleFillMode", {
  28884. get: function () {
  28885. return Material._TriangleFillMode;
  28886. },
  28887. enumerable: true,
  28888. configurable: true
  28889. });
  28890. Object.defineProperty(Material, "WireFrameFillMode", {
  28891. get: function () {
  28892. return Material._WireFrameFillMode;
  28893. },
  28894. enumerable: true,
  28895. configurable: true
  28896. });
  28897. Object.defineProperty(Material, "PointFillMode", {
  28898. get: function () {
  28899. return Material._PointFillMode;
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28905. get: function () {
  28906. return Material._ClockWiseSideOrientation;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28912. get: function () {
  28913. return Material._CounterClockWiseSideOrientation;
  28914. },
  28915. enumerable: true,
  28916. configurable: true
  28917. });
  28918. Object.defineProperty(Material.prototype, "onDispose", {
  28919. set: function (callback) {
  28920. if (this._onDisposeObserver) {
  28921. this.onDisposeObservable.remove(this._onDisposeObserver);
  28922. }
  28923. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28924. },
  28925. enumerable: true,
  28926. configurable: true
  28927. });
  28928. Object.defineProperty(Material.prototype, "onBind", {
  28929. set: function (callback) {
  28930. if (this._onBindObserver) {
  28931. this.onBindObservable.remove(this._onBindObserver);
  28932. }
  28933. this._onBindObserver = this.onBindObservable.add(callback);
  28934. },
  28935. enumerable: true,
  28936. configurable: true
  28937. });
  28938. Object.defineProperty(Material.prototype, "wireframe", {
  28939. get: function () {
  28940. return this._fillMode === Material.WireFrameFillMode;
  28941. },
  28942. set: function (value) {
  28943. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28944. },
  28945. enumerable: true,
  28946. configurable: true
  28947. });
  28948. Object.defineProperty(Material.prototype, "pointsCloud", {
  28949. get: function () {
  28950. return this._fillMode === Material.PointFillMode;
  28951. },
  28952. set: function (value) {
  28953. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(Material.prototype, "fillMode", {
  28959. get: function () {
  28960. return this._fillMode;
  28961. },
  28962. set: function (value) {
  28963. this._fillMode = value;
  28964. },
  28965. enumerable: true,
  28966. configurable: true
  28967. });
  28968. /**
  28969. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28970. * subclasses should override adding information pertainent to themselves
  28971. */
  28972. Material.prototype.toString = function (fullDetails) {
  28973. var ret = "Name: " + this.name;
  28974. if (fullDetails) {
  28975. }
  28976. return ret;
  28977. };
  28978. Material.prototype.getClassName = function () {
  28979. return "Material";
  28980. };
  28981. Object.defineProperty(Material.prototype, "isFrozen", {
  28982. get: function () {
  28983. return this.checkReadyOnlyOnce;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. Material.prototype.freeze = function () {
  28989. this.checkReadyOnlyOnce = true;
  28990. };
  28991. Material.prototype.unfreeze = function () {
  28992. this.checkReadyOnlyOnce = false;
  28993. };
  28994. Material.prototype.isReady = function (mesh, useInstances) {
  28995. return true;
  28996. };
  28997. Material.prototype.getEffect = function () {
  28998. return this._effect;
  28999. };
  29000. Material.prototype.getScene = function () {
  29001. return this._scene;
  29002. };
  29003. Material.prototype.needAlphaBlending = function () {
  29004. return (this.alpha < 1.0);
  29005. };
  29006. Material.prototype.needAlphaTesting = function () {
  29007. return false;
  29008. };
  29009. Material.prototype.getAlphaTestTexture = function () {
  29010. return null;
  29011. };
  29012. Material.prototype.markDirty = function () {
  29013. this._wasPreviouslyReady = false;
  29014. };
  29015. Material.prototype._preBind = function () {
  29016. var engine = this._scene.getEngine();
  29017. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29018. engine.enableEffect(this._effect);
  29019. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29020. };
  29021. Material.prototype.bind = function (world, mesh) {
  29022. this._scene._cachedMaterial = this;
  29023. this.onBindObservable.notifyObservers(mesh);
  29024. if (this.disableDepthWrite) {
  29025. var engine = this._scene.getEngine();
  29026. this._cachedDepthWriteState = engine.getDepthWrite();
  29027. engine.setDepthWrite(false);
  29028. }
  29029. };
  29030. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29031. };
  29032. Material.prototype.unbind = function () {
  29033. this.onUnBindObservable.notifyObservers(this);
  29034. if (this.disableDepthWrite) {
  29035. var engine = this._scene.getEngine();
  29036. engine.setDepthWrite(this._cachedDepthWriteState);
  29037. }
  29038. };
  29039. Material.prototype.clone = function (name) {
  29040. return null;
  29041. };
  29042. Material.prototype.getBindedMeshes = function () {
  29043. var result = new Array();
  29044. for (var index = 0; index < this._scene.meshes.length; index++) {
  29045. var mesh = this._scene.meshes[index];
  29046. if (mesh.material === this) {
  29047. result.push(mesh);
  29048. }
  29049. }
  29050. return result;
  29051. };
  29052. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29053. // Animations
  29054. this.getScene().stopAnimation(this);
  29055. // Remove from scene
  29056. var index = this._scene.materials.indexOf(this);
  29057. if (index >= 0) {
  29058. this._scene.materials.splice(index, 1);
  29059. }
  29060. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29061. if (forceDisposeEffect && this._effect) {
  29062. this._scene.getEngine()._releaseEffect(this._effect);
  29063. this._effect = null;
  29064. }
  29065. // Remove from meshes
  29066. for (index = 0; index < this._scene.meshes.length; index++) {
  29067. var mesh = this._scene.meshes[index];
  29068. if (mesh.material === this) {
  29069. mesh.material = null;
  29070. }
  29071. }
  29072. // Callback
  29073. this.onDisposeObservable.notifyObservers(this);
  29074. this.onDisposeObservable.clear();
  29075. this.onBindObservable.clear();
  29076. this.onUnBindObservable.clear();
  29077. };
  29078. Material.prototype.serialize = function () {
  29079. return BABYLON.SerializationHelper.Serialize(this);
  29080. };
  29081. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29082. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29083. multiMaterial.id = parsedMultiMaterial.id;
  29084. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29085. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29086. var subMatId = parsedMultiMaterial.materials[matIndex];
  29087. if (subMatId) {
  29088. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29089. }
  29090. else {
  29091. multiMaterial.subMaterials.push(null);
  29092. }
  29093. }
  29094. return multiMaterial;
  29095. };
  29096. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29097. if (!parsedMaterial.customType) {
  29098. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29099. }
  29100. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29101. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29102. ;
  29103. };
  29104. return Material;
  29105. }());
  29106. Material._TriangleFillMode = 0;
  29107. Material._WireFrameFillMode = 1;
  29108. Material._PointFillMode = 2;
  29109. Material._ClockWiseSideOrientation = 0;
  29110. Material._CounterClockWiseSideOrientation = 1;
  29111. __decorate([
  29112. BABYLON.serialize()
  29113. ], Material.prototype, "id", void 0);
  29114. __decorate([
  29115. BABYLON.serialize()
  29116. ], Material.prototype, "name", void 0);
  29117. __decorate([
  29118. BABYLON.serialize()
  29119. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29120. __decorate([
  29121. BABYLON.serialize()
  29122. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29123. __decorate([
  29124. BABYLON.serialize()
  29125. ], Material.prototype, "state", void 0);
  29126. __decorate([
  29127. BABYLON.serialize()
  29128. ], Material.prototype, "alpha", void 0);
  29129. __decorate([
  29130. BABYLON.serialize()
  29131. ], Material.prototype, "backFaceCulling", void 0);
  29132. __decorate([
  29133. BABYLON.serialize()
  29134. ], Material.prototype, "sideOrientation", void 0);
  29135. __decorate([
  29136. BABYLON.serialize()
  29137. ], Material.prototype, "alphaMode", void 0);
  29138. __decorate([
  29139. BABYLON.serialize()
  29140. ], Material.prototype, "disableDepthWrite", void 0);
  29141. __decorate([
  29142. BABYLON.serialize()
  29143. ], Material.prototype, "fogEnabled", void 0);
  29144. __decorate([
  29145. BABYLON.serialize()
  29146. ], Material.prototype, "pointSize", void 0);
  29147. __decorate([
  29148. BABYLON.serialize()
  29149. ], Material.prototype, "zOffset", void 0);
  29150. __decorate([
  29151. BABYLON.serialize()
  29152. ], Material.prototype, "wireframe", null);
  29153. __decorate([
  29154. BABYLON.serialize()
  29155. ], Material.prototype, "pointsCloud", null);
  29156. __decorate([
  29157. BABYLON.serialize()
  29158. ], Material.prototype, "fillMode", null);
  29159. BABYLON.Material = Material;
  29160. })(BABYLON || (BABYLON = {}));
  29161. //# sourceMappingURL=babylon.material.js.map
  29162. var BABYLON;
  29163. (function (BABYLON) {
  29164. var StandardMaterialDefines = (function (_super) {
  29165. __extends(StandardMaterialDefines, _super);
  29166. function StandardMaterialDefines() {
  29167. var _this = _super.call(this) || this;
  29168. _this.DIFFUSE = false;
  29169. _this.AMBIENT = false;
  29170. _this.OPACITY = false;
  29171. _this.OPACITYRGB = false;
  29172. _this.REFLECTION = false;
  29173. _this.EMISSIVE = false;
  29174. _this.SPECULAR = false;
  29175. _this.BUMP = false;
  29176. _this.PARALLAX = false;
  29177. _this.PARALLAXOCCLUSION = false;
  29178. _this.SPECULAROVERALPHA = false;
  29179. _this.CLIPPLANE = false;
  29180. _this.ALPHATEST = false;
  29181. _this.ALPHAFROMDIFFUSE = false;
  29182. _this.POINTSIZE = false;
  29183. _this.FOG = false;
  29184. _this.SPECULARTERM = false;
  29185. _this.DIFFUSEFRESNEL = false;
  29186. _this.OPACITYFRESNEL = false;
  29187. _this.REFLECTIONFRESNEL = false;
  29188. _this.REFRACTIONFRESNEL = false;
  29189. _this.EMISSIVEFRESNEL = false;
  29190. _this.FRESNEL = false;
  29191. _this.NORMAL = false;
  29192. _this.UV1 = false;
  29193. _this.UV2 = false;
  29194. _this.VERTEXCOLOR = false;
  29195. _this.VERTEXALPHA = false;
  29196. _this.NUM_BONE_INFLUENCERS = 0;
  29197. _this.BonesPerMesh = 0;
  29198. _this.INSTANCES = false;
  29199. _this.GLOSSINESS = false;
  29200. _this.ROUGHNESS = false;
  29201. _this.EMISSIVEASILLUMINATION = false;
  29202. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29203. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29204. _this.LIGHTMAP = false;
  29205. _this.USELIGHTMAPASSHADOWMAP = false;
  29206. _this.REFLECTIONMAP_3D = false;
  29207. _this.REFLECTIONMAP_SPHERICAL = false;
  29208. _this.REFLECTIONMAP_PLANAR = false;
  29209. _this.REFLECTIONMAP_CUBIC = false;
  29210. _this.REFLECTIONMAP_PROJECTION = false;
  29211. _this.REFLECTIONMAP_SKYBOX = false;
  29212. _this.REFLECTIONMAP_EXPLICIT = false;
  29213. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29214. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29215. _this.INVERTCUBICMAP = false;
  29216. _this.LOGARITHMICDEPTH = false;
  29217. _this.REFRACTION = false;
  29218. _this.REFRACTIONMAP_3D = false;
  29219. _this.REFLECTIONOVERALPHA = false;
  29220. _this.INVERTNORMALMAPX = false;
  29221. _this.INVERTNORMALMAPY = false;
  29222. _this.SHADOWFULLFLOAT = false;
  29223. _this.CAMERACOLORGRADING = false;
  29224. _this.CAMERACOLORCURVES = false;
  29225. _this.rebuild();
  29226. return _this;
  29227. }
  29228. return StandardMaterialDefines;
  29229. }(BABYLON.MaterialDefines));
  29230. var StandardMaterial = (function (_super) {
  29231. __extends(StandardMaterial, _super);
  29232. function StandardMaterial(name, scene) {
  29233. var _this = _super.call(this, name, scene) || this;
  29234. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29235. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29236. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29237. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29238. _this.specularPower = 64;
  29239. _this.useAlphaFromDiffuseTexture = false;
  29240. _this.useEmissiveAsIllumination = false;
  29241. _this.linkEmissiveWithDiffuse = false;
  29242. _this.useReflectionFresnelFromSpecular = false;
  29243. _this.useSpecularOverAlpha = false;
  29244. _this.useReflectionOverAlpha = false;
  29245. _this.disableLighting = false;
  29246. _this.useParallax = false;
  29247. _this.useParallaxOcclusion = false;
  29248. _this.parallaxScaleBias = 0.05;
  29249. _this.roughness = 0;
  29250. _this.indexOfRefraction = 0.98;
  29251. _this.invertRefractionY = true;
  29252. _this.useLightmapAsShadowmap = false;
  29253. _this.useGlossinessFromSpecularMapAlpha = false;
  29254. _this.maxSimultaneousLights = 4;
  29255. /**
  29256. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29257. */
  29258. _this.invertNormalMapX = false;
  29259. /**
  29260. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29261. */
  29262. _this.invertNormalMapY = false;
  29263. /**
  29264. * Color Grading 2D Lookup Texture.
  29265. * This allows special effects like sepia, black and white to sixties rendering style.
  29266. */
  29267. _this.cameraColorGradingTexture = null;
  29268. /**
  29269. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29270. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29271. * 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;
  29272. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29273. */
  29274. _this.cameraColorCurves = null;
  29275. _this._renderTargets = new BABYLON.SmartArray(16);
  29276. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29277. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29278. _this._defines = new StandardMaterialDefines();
  29279. _this._cachedDefines = new StandardMaterialDefines();
  29280. _this._cachedDefines.BonesPerMesh = -1;
  29281. _this.getRenderTargetTextures = function () {
  29282. _this._renderTargets.reset();
  29283. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  29284. _this._renderTargets.push(_this.reflectionTexture);
  29285. }
  29286. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  29287. _this._renderTargets.push(_this.refractionTexture);
  29288. }
  29289. return _this._renderTargets;
  29290. };
  29291. return _this;
  29292. }
  29293. StandardMaterial.prototype.getClassName = function () {
  29294. return "StandardMaterial";
  29295. };
  29296. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29297. get: function () {
  29298. return this._useLogarithmicDepth;
  29299. },
  29300. set: function (value) {
  29301. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. StandardMaterial.prototype.needAlphaBlending = function () {
  29307. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  29308. };
  29309. StandardMaterial.prototype.needAlphaTesting = function () {
  29310. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  29311. };
  29312. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29313. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  29314. };
  29315. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29316. return this.diffuseTexture;
  29317. };
  29318. // Methods
  29319. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29320. if (!mesh) {
  29321. return true;
  29322. }
  29323. if (this._defines.INSTANCES !== useInstances) {
  29324. return false;
  29325. }
  29326. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  29327. return true;
  29328. }
  29329. return false;
  29330. };
  29331. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  29332. if (this.isFrozen) {
  29333. if (this._wasPreviouslyReady) {
  29334. return true;
  29335. }
  29336. }
  29337. var scene = this.getScene();
  29338. var engine = scene.getEngine();
  29339. var needUVs = false;
  29340. var needNormals = false;
  29341. this._defines.reset();
  29342. // Lights
  29343. if (scene.lightsEnabled && !this.disableLighting) {
  29344. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  29345. }
  29346. if (!this.checkReadyOnEveryCall) {
  29347. if (this._renderId === scene.getRenderId()) {
  29348. if (this._checkCache(scene, mesh, useInstances)) {
  29349. return true;
  29350. }
  29351. }
  29352. }
  29353. // Textures
  29354. if (scene.texturesEnabled) {
  29355. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29356. if (!this.diffuseTexture.isReady()) {
  29357. return false;
  29358. }
  29359. else {
  29360. needUVs = true;
  29361. this._defines.DIFFUSE = true;
  29362. }
  29363. }
  29364. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29365. if (!this.ambientTexture.isReady()) {
  29366. return false;
  29367. }
  29368. else {
  29369. needUVs = true;
  29370. this._defines.AMBIENT = true;
  29371. }
  29372. }
  29373. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29374. if (!this.opacityTexture.isReady()) {
  29375. return false;
  29376. }
  29377. else {
  29378. needUVs = true;
  29379. this._defines.OPACITY = true;
  29380. if (this.opacityTexture.getAlphaFromRGB) {
  29381. this._defines.OPACITYRGB = true;
  29382. }
  29383. }
  29384. }
  29385. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29386. if (!this.reflectionTexture.isReady()) {
  29387. return false;
  29388. }
  29389. else {
  29390. needNormals = true;
  29391. this._defines.REFLECTION = true;
  29392. if (this.roughness > 0) {
  29393. this._defines.ROUGHNESS = true;
  29394. }
  29395. if (this.useReflectionOverAlpha) {
  29396. this._defines.REFLECTIONOVERALPHA = true;
  29397. }
  29398. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29399. this._defines.INVERTCUBICMAP = true;
  29400. }
  29401. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  29402. switch (this.reflectionTexture.coordinatesMode) {
  29403. case BABYLON.Texture.CUBIC_MODE:
  29404. case BABYLON.Texture.INVCUBIC_MODE:
  29405. this._defines.REFLECTIONMAP_CUBIC = true;
  29406. break;
  29407. case BABYLON.Texture.EXPLICIT_MODE:
  29408. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29409. break;
  29410. case BABYLON.Texture.PLANAR_MODE:
  29411. this._defines.REFLECTIONMAP_PLANAR = true;
  29412. break;
  29413. case BABYLON.Texture.PROJECTION_MODE:
  29414. this._defines.REFLECTIONMAP_PROJECTION = true;
  29415. break;
  29416. case BABYLON.Texture.SKYBOX_MODE:
  29417. this._defines.REFLECTIONMAP_SKYBOX = true;
  29418. break;
  29419. case BABYLON.Texture.SPHERICAL_MODE:
  29420. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29421. break;
  29422. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29423. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29424. break;
  29425. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29426. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29427. break;
  29428. }
  29429. }
  29430. }
  29431. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29432. if (!this.emissiveTexture.isReady()) {
  29433. return false;
  29434. }
  29435. else {
  29436. needUVs = true;
  29437. this._defines.EMISSIVE = true;
  29438. }
  29439. }
  29440. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29441. if (!this.lightmapTexture.isReady()) {
  29442. return false;
  29443. }
  29444. else {
  29445. needUVs = true;
  29446. this._defines.LIGHTMAP = true;
  29447. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  29448. }
  29449. }
  29450. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29451. if (!this.specularTexture.isReady()) {
  29452. return false;
  29453. }
  29454. else {
  29455. needUVs = true;
  29456. this._defines.SPECULAR = true;
  29457. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  29458. }
  29459. }
  29460. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29461. if (!this.bumpTexture.isReady()) {
  29462. return false;
  29463. }
  29464. else {
  29465. needUVs = true;
  29466. this._defines.BUMP = true;
  29467. if (this.useParallax) {
  29468. this._defines.PARALLAX = true;
  29469. if (this.useParallaxOcclusion) {
  29470. this._defines.PARALLAXOCCLUSION = true;
  29471. }
  29472. }
  29473. if (this.invertNormalMapX) {
  29474. this._defines.INVERTNORMALMAPX = true;
  29475. }
  29476. if (this.invertNormalMapY) {
  29477. this._defines.INVERTNORMALMAPY = true;
  29478. }
  29479. if (scene._mirroredCameraPosition) {
  29480. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29481. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29482. }
  29483. }
  29484. }
  29485. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29486. if (!this.refractionTexture.isReady()) {
  29487. return false;
  29488. }
  29489. else {
  29490. needUVs = true;
  29491. this._defines.REFRACTION = true;
  29492. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29493. }
  29494. }
  29495. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29496. if (!this.cameraColorGradingTexture.isReady()) {
  29497. return false;
  29498. }
  29499. else {
  29500. this._defines.CAMERACOLORGRADING = true;
  29501. }
  29502. }
  29503. }
  29504. // Effect
  29505. if (scene.clipPlane) {
  29506. this._defines.CLIPPLANE = true;
  29507. }
  29508. if (engine.getAlphaTesting()) {
  29509. this._defines.ALPHATEST = true;
  29510. }
  29511. if (this._shouldUseAlphaFromDiffuseTexture()) {
  29512. this._defines.ALPHAFROMDIFFUSE = true;
  29513. }
  29514. if (this.useEmissiveAsIllumination) {
  29515. this._defines.EMISSIVEASILLUMINATION = true;
  29516. }
  29517. if (this.linkEmissiveWithDiffuse) {
  29518. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  29519. }
  29520. if (this.useLogarithmicDepth) {
  29521. this._defines.LOGARITHMICDEPTH = true;
  29522. }
  29523. if (this.cameraColorCurves) {
  29524. this._defines.CAMERACOLORCURVES = true;
  29525. }
  29526. // Point size
  29527. if (this.pointsCloud || scene.forcePointsCloud) {
  29528. this._defines.POINTSIZE = true;
  29529. }
  29530. // Fog
  29531. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29532. this._defines.FOG = true;
  29533. }
  29534. if (StandardMaterial.FresnelEnabled) {
  29535. // Fresnel
  29536. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  29537. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29538. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  29539. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  29540. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29541. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29542. this._defines.DIFFUSEFRESNEL = true;
  29543. }
  29544. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29545. this._defines.OPACITYFRESNEL = true;
  29546. }
  29547. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29548. this._defines.REFLECTIONFRESNEL = true;
  29549. if (this.useReflectionFresnelFromSpecular) {
  29550. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  29551. }
  29552. }
  29553. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29554. this._defines.REFRACTIONFRESNEL = true;
  29555. }
  29556. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29557. this._defines.EMISSIVEFRESNEL = true;
  29558. }
  29559. needNormals = true;
  29560. this._defines.FRESNEL = true;
  29561. }
  29562. }
  29563. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29564. this._defines.SPECULAROVERALPHA = true;
  29565. }
  29566. // Attribs
  29567. if (mesh) {
  29568. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29569. this._defines.NORMAL = true;
  29570. }
  29571. if (needUVs) {
  29572. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29573. this._defines.UV1 = true;
  29574. }
  29575. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29576. this._defines.UV2 = true;
  29577. }
  29578. }
  29579. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29580. this._defines.VERTEXCOLOR = true;
  29581. if (mesh.hasVertexAlpha) {
  29582. this._defines.VERTEXALPHA = true;
  29583. }
  29584. }
  29585. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29586. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29587. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29588. }
  29589. // Instances
  29590. if (useInstances) {
  29591. this._defines.INSTANCES = true;
  29592. }
  29593. }
  29594. // Get correct effect
  29595. if (!this._defines.isEqual(this._cachedDefines)) {
  29596. this._defines.cloneTo(this._cachedDefines);
  29597. scene.resetCachedMaterial();
  29598. // Fallbacks
  29599. var fallbacks = new BABYLON.EffectFallbacks();
  29600. if (this._defines.REFLECTION) {
  29601. fallbacks.addFallback(0, "REFLECTION");
  29602. }
  29603. if (this._defines.SPECULAR) {
  29604. fallbacks.addFallback(0, "SPECULAR");
  29605. }
  29606. if (this._defines.BUMP) {
  29607. fallbacks.addFallback(0, "BUMP");
  29608. }
  29609. if (this._defines.PARALLAX) {
  29610. fallbacks.addFallback(1, "PARALLAX");
  29611. }
  29612. if (this._defines.PARALLAXOCCLUSION) {
  29613. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29614. }
  29615. if (this._defines.SPECULAROVERALPHA) {
  29616. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29617. }
  29618. if (this._defines.FOG) {
  29619. fallbacks.addFallback(1, "FOG");
  29620. }
  29621. if (this._defines.POINTSIZE) {
  29622. fallbacks.addFallback(0, "POINTSIZE");
  29623. }
  29624. if (this._defines.LOGARITHMICDEPTH) {
  29625. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29626. }
  29627. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29628. if (this._defines.SPECULARTERM) {
  29629. fallbacks.addFallback(0, "SPECULARTERM");
  29630. }
  29631. if (this._defines.DIFFUSEFRESNEL) {
  29632. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29633. }
  29634. if (this._defines.OPACITYFRESNEL) {
  29635. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29636. }
  29637. if (this._defines.REFLECTIONFRESNEL) {
  29638. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29639. }
  29640. if (this._defines.EMISSIVEFRESNEL) {
  29641. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29642. }
  29643. if (this._defines.FRESNEL) {
  29644. fallbacks.addFallback(4, "FRESNEL");
  29645. }
  29646. //Attributes
  29647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29648. if (this._defines.NORMAL) {
  29649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29650. }
  29651. if (this._defines.UV1) {
  29652. attribs.push(BABYLON.VertexBuffer.UVKind);
  29653. }
  29654. if (this._defines.UV2) {
  29655. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29656. }
  29657. if (this._defines.VERTEXCOLOR) {
  29658. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29659. }
  29660. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29661. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29662. var shaderName = "default";
  29663. var join = this._defines.toString();
  29664. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29665. "vFogInfos", "vFogColor", "pointSize",
  29666. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29667. "mBones",
  29668. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29669. "depthValues",
  29670. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29671. "logarithmicDepthConstant"
  29672. ];
  29673. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29674. if (this._defines.CAMERACOLORCURVES) {
  29675. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29676. }
  29677. if (this._defines.CAMERACOLORGRADING) {
  29678. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29679. }
  29680. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  29681. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  29682. }
  29683. if (!this._effect.isReady()) {
  29684. return false;
  29685. }
  29686. this._renderId = scene.getRenderId();
  29687. this._wasPreviouslyReady = true;
  29688. if (mesh) {
  29689. if (!mesh._materialDefines) {
  29690. mesh._materialDefines = new StandardMaterialDefines();
  29691. }
  29692. this._defines.cloneTo(mesh._materialDefines);
  29693. }
  29694. return true;
  29695. };
  29696. StandardMaterial.prototype.unbind = function () {
  29697. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29698. this._effect.setTexture("reflection2DSampler", null);
  29699. }
  29700. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29701. this._effect.setTexture("refraction2DSampler", null);
  29702. }
  29703. _super.prototype.unbind.call(this);
  29704. };
  29705. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29706. this._effect.setMatrix("world", world);
  29707. };
  29708. StandardMaterial.prototype.bind = function (world, mesh) {
  29709. var scene = this.getScene();
  29710. // Matrices
  29711. this.bindOnlyWorldMatrix(world);
  29712. // Bones
  29713. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29714. if (scene.getCachedMaterial() !== this) {
  29715. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29716. if (StandardMaterial.FresnelEnabled) {
  29717. // Fresnel
  29718. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29719. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29720. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29721. }
  29722. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29723. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29724. }
  29725. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29726. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29727. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29728. }
  29729. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29730. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29731. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29732. }
  29733. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29734. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29735. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29736. }
  29737. }
  29738. // Textures
  29739. if (scene.texturesEnabled) {
  29740. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29741. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  29742. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  29743. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  29744. }
  29745. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29746. this._effect.setTexture("ambientSampler", this.ambientTexture);
  29747. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  29748. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29749. }
  29750. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29751. this._effect.setTexture("opacitySampler", this.opacityTexture);
  29752. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29753. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29754. }
  29755. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29756. if (this.reflectionTexture.isCube) {
  29757. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29758. }
  29759. else {
  29760. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  29761. }
  29762. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29763. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  29764. }
  29765. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29766. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  29767. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29768. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29769. }
  29770. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29771. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  29772. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29773. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29774. }
  29775. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29776. this._effect.setTexture("specularSampler", this.specularTexture);
  29777. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  29778. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  29779. }
  29780. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29781. this._effect.setTexture("bumpSampler", this.bumpTexture);
  29782. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29783. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29784. }
  29785. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29786. var depth = 1.0;
  29787. if (this.refractionTexture.isCube) {
  29788. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  29789. }
  29790. else {
  29791. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  29792. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29793. if (this.refractionTexture.depth) {
  29794. depth = this.refractionTexture.depth;
  29795. }
  29796. }
  29797. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29798. }
  29799. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29800. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29801. }
  29802. }
  29803. // Clip plane
  29804. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  29805. // Point size
  29806. if (this.pointsCloud) {
  29807. this._effect.setFloat("pointSize", this.pointSize);
  29808. }
  29809. // Colors
  29810. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29811. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29812. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29813. if (this._defines.SPECULARTERM) {
  29814. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  29815. }
  29816. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  29817. }
  29818. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  29819. // Diffuse
  29820. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29821. // Lights
  29822. if (scene.lightsEnabled && !this.disableLighting) {
  29823. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  29824. }
  29825. // View
  29826. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  29827. this._effect.setMatrix("view", scene.getViewMatrix());
  29828. }
  29829. // Fog
  29830. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  29831. // Log. depth
  29832. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  29833. // Color Curves
  29834. if (this.cameraColorCurves) {
  29835. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29836. }
  29837. }
  29838. _super.prototype.bind.call(this, world, mesh);
  29839. };
  29840. StandardMaterial.prototype.getAnimatables = function () {
  29841. var results = [];
  29842. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  29843. results.push(this.diffuseTexture);
  29844. }
  29845. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29846. results.push(this.ambientTexture);
  29847. }
  29848. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29849. results.push(this.opacityTexture);
  29850. }
  29851. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29852. results.push(this.reflectionTexture);
  29853. }
  29854. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29855. results.push(this.emissiveTexture);
  29856. }
  29857. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  29858. results.push(this.specularTexture);
  29859. }
  29860. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29861. results.push(this.bumpTexture);
  29862. }
  29863. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29864. results.push(this.lightmapTexture);
  29865. }
  29866. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29867. results.push(this.refractionTexture);
  29868. }
  29869. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29870. results.push(this.cameraColorGradingTexture);
  29871. }
  29872. return results;
  29873. };
  29874. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29875. if (forceDisposeTextures) {
  29876. if (this.diffuseTexture) {
  29877. this.diffuseTexture.dispose();
  29878. }
  29879. if (this.ambientTexture) {
  29880. this.ambientTexture.dispose();
  29881. }
  29882. if (this.opacityTexture) {
  29883. this.opacityTexture.dispose();
  29884. }
  29885. if (this.reflectionTexture) {
  29886. this.reflectionTexture.dispose();
  29887. }
  29888. if (this.emissiveTexture) {
  29889. this.emissiveTexture.dispose();
  29890. }
  29891. if (this.specularTexture) {
  29892. this.specularTexture.dispose();
  29893. }
  29894. if (this.bumpTexture) {
  29895. this.bumpTexture.dispose();
  29896. }
  29897. if (this.lightmapTexture) {
  29898. this.lightmapTexture.dispose();
  29899. }
  29900. if (this.refractionTexture) {
  29901. this.refractionTexture.dispose();
  29902. }
  29903. if (this.cameraColorGradingTexture) {
  29904. this.cameraColorGradingTexture.dispose();
  29905. }
  29906. }
  29907. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29908. };
  29909. StandardMaterial.prototype.clone = function (name) {
  29910. var _this = this;
  29911. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29912. };
  29913. StandardMaterial.prototype.serialize = function () {
  29914. return BABYLON.SerializationHelper.Serialize(this);
  29915. };
  29916. // Statics
  29917. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29918. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29919. };
  29920. return StandardMaterial;
  29921. }(BABYLON.Material));
  29922. // Flags used to enable or disable a type of texture for all Standard Materials
  29923. StandardMaterial.DiffuseTextureEnabled = true;
  29924. StandardMaterial.AmbientTextureEnabled = true;
  29925. StandardMaterial.OpacityTextureEnabled = true;
  29926. StandardMaterial.ReflectionTextureEnabled = true;
  29927. StandardMaterial.EmissiveTextureEnabled = true;
  29928. StandardMaterial.SpecularTextureEnabled = true;
  29929. StandardMaterial.BumpTextureEnabled = true;
  29930. StandardMaterial.FresnelEnabled = true;
  29931. StandardMaterial.LightmapTextureEnabled = true;
  29932. StandardMaterial.RefractionTextureEnabled = true;
  29933. StandardMaterial.ColorGradingTextureEnabled = true;
  29934. __decorate([
  29935. BABYLON.serializeAsTexture()
  29936. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29937. __decorate([
  29938. BABYLON.serializeAsTexture()
  29939. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29940. __decorate([
  29941. BABYLON.serializeAsTexture()
  29942. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29943. __decorate([
  29944. BABYLON.serializeAsTexture()
  29945. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29946. __decorate([
  29947. BABYLON.serializeAsTexture()
  29948. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29949. __decorate([
  29950. BABYLON.serializeAsTexture()
  29951. ], StandardMaterial.prototype, "specularTexture", void 0);
  29952. __decorate([
  29953. BABYLON.serializeAsTexture()
  29954. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29955. __decorate([
  29956. BABYLON.serializeAsTexture()
  29957. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29958. __decorate([
  29959. BABYLON.serializeAsTexture()
  29960. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29961. __decorate([
  29962. BABYLON.serializeAsColor3("ambient")
  29963. ], StandardMaterial.prototype, "ambientColor", void 0);
  29964. __decorate([
  29965. BABYLON.serializeAsColor3("diffuse")
  29966. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29967. __decorate([
  29968. BABYLON.serializeAsColor3("specular")
  29969. ], StandardMaterial.prototype, "specularColor", void 0);
  29970. __decorate([
  29971. BABYLON.serializeAsColor3("emissive")
  29972. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29973. __decorate([
  29974. BABYLON.serialize()
  29975. ], StandardMaterial.prototype, "specularPower", void 0);
  29976. __decorate([
  29977. BABYLON.serialize()
  29978. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29979. __decorate([
  29980. BABYLON.serialize()
  29981. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29982. __decorate([
  29983. BABYLON.serialize()
  29984. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29985. __decorate([
  29986. BABYLON.serialize()
  29987. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29988. __decorate([
  29989. BABYLON.serialize()
  29990. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29991. __decorate([
  29992. BABYLON.serialize()
  29993. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29994. __decorate([
  29995. BABYLON.serialize()
  29996. ], StandardMaterial.prototype, "disableLighting", void 0);
  29997. __decorate([
  29998. BABYLON.serialize()
  29999. ], StandardMaterial.prototype, "useParallax", void 0);
  30000. __decorate([
  30001. BABYLON.serialize()
  30002. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30003. __decorate([
  30004. BABYLON.serialize()
  30005. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30006. __decorate([
  30007. BABYLON.serialize()
  30008. ], StandardMaterial.prototype, "roughness", void 0);
  30009. __decorate([
  30010. BABYLON.serialize()
  30011. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30012. __decorate([
  30013. BABYLON.serialize()
  30014. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30015. __decorate([
  30016. BABYLON.serialize()
  30017. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30018. __decorate([
  30019. BABYLON.serializeAsFresnelParameters()
  30020. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30021. __decorate([
  30022. BABYLON.serializeAsFresnelParameters()
  30023. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30024. __decorate([
  30025. BABYLON.serializeAsFresnelParameters()
  30026. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30027. __decorate([
  30028. BABYLON.serializeAsFresnelParameters()
  30029. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30030. __decorate([
  30031. BABYLON.serializeAsFresnelParameters()
  30032. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30033. __decorate([
  30034. BABYLON.serialize()
  30035. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30036. __decorate([
  30037. BABYLON.serialize()
  30038. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30039. __decorate([
  30040. BABYLON.serialize()
  30041. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30042. __decorate([
  30043. BABYLON.serialize()
  30044. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30045. __decorate([
  30046. BABYLON.serializeAsTexture()
  30047. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30048. __decorate([
  30049. BABYLON.serializeAsColorCurves()
  30050. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30051. __decorate([
  30052. BABYLON.serialize()
  30053. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30054. BABYLON.StandardMaterial = StandardMaterial;
  30055. })(BABYLON || (BABYLON = {}));
  30056. //# sourceMappingURL=babylon.standardMaterial.js.map
  30057. var BABYLON;
  30058. (function (BABYLON) {
  30059. var MultiMaterial = (function (_super) {
  30060. __extends(MultiMaterial, _super);
  30061. function MultiMaterial(name, scene) {
  30062. var _this = _super.call(this, name, scene, true) || this;
  30063. _this.subMaterials = new Array();
  30064. scene.multiMaterials.push(_this);
  30065. return _this;
  30066. }
  30067. // Properties
  30068. MultiMaterial.prototype.getSubMaterial = function (index) {
  30069. if (index < 0 || index >= this.subMaterials.length) {
  30070. return this.getScene().defaultMaterial;
  30071. }
  30072. return this.subMaterials[index];
  30073. };
  30074. // Methods
  30075. MultiMaterial.prototype.getClassName = function () {
  30076. return "MultiMaterial";
  30077. };
  30078. MultiMaterial.prototype.isReady = function (mesh) {
  30079. for (var index = 0; index < this.subMaterials.length; index++) {
  30080. var subMaterial = this.subMaterials[index];
  30081. if (subMaterial) {
  30082. if (!this.subMaterials[index].isReady(mesh)) {
  30083. return false;
  30084. }
  30085. }
  30086. }
  30087. return true;
  30088. };
  30089. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30090. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30091. for (var index = 0; index < this.subMaterials.length; index++) {
  30092. var subMaterial = null;
  30093. if (cloneChildren) {
  30094. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30095. }
  30096. else {
  30097. subMaterial = this.subMaterials[index];
  30098. }
  30099. newMultiMaterial.subMaterials.push(subMaterial);
  30100. }
  30101. return newMultiMaterial;
  30102. };
  30103. MultiMaterial.prototype.serialize = function () {
  30104. var serializationObject = {};
  30105. serializationObject.name = this.name;
  30106. serializationObject.id = this.id;
  30107. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30108. serializationObject.materials = [];
  30109. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30110. var subMat = this.subMaterials[matIndex];
  30111. if (subMat) {
  30112. serializationObject.materials.push(subMat.id);
  30113. }
  30114. else {
  30115. serializationObject.materials.push(null);
  30116. }
  30117. }
  30118. return serializationObject;
  30119. };
  30120. return MultiMaterial;
  30121. }(BABYLON.Material));
  30122. BABYLON.MultiMaterial = MultiMaterial;
  30123. })(BABYLON || (BABYLON = {}));
  30124. //# sourceMappingURL=babylon.multiMaterial.js.map
  30125. var BABYLON;
  30126. (function (BABYLON) {
  30127. var SceneLoader = (function () {
  30128. function SceneLoader() {
  30129. }
  30130. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30131. get: function () {
  30132. return 0;
  30133. },
  30134. enumerable: true,
  30135. configurable: true
  30136. });
  30137. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30138. get: function () {
  30139. return 1;
  30140. },
  30141. enumerable: true,
  30142. configurable: true
  30143. });
  30144. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30145. get: function () {
  30146. return 2;
  30147. },
  30148. enumerable: true,
  30149. configurable: true
  30150. });
  30151. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30152. get: function () {
  30153. return 3;
  30154. },
  30155. enumerable: true,
  30156. configurable: true
  30157. });
  30158. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30159. get: function () {
  30160. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30161. },
  30162. set: function (value) {
  30163. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30164. },
  30165. enumerable: true,
  30166. configurable: true
  30167. });
  30168. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30169. get: function () {
  30170. return SceneLoader._ShowLoadingScreen;
  30171. },
  30172. set: function (value) {
  30173. SceneLoader._ShowLoadingScreen = value;
  30174. },
  30175. enumerable: true,
  30176. configurable: true
  30177. });
  30178. Object.defineProperty(SceneLoader, "loggingLevel", {
  30179. get: function () {
  30180. return SceneLoader._loggingLevel;
  30181. },
  30182. set: function (value) {
  30183. SceneLoader._loggingLevel = value;
  30184. },
  30185. enumerable: true,
  30186. configurable: true
  30187. });
  30188. SceneLoader._getDefaultPlugin = function () {
  30189. return SceneLoader._registeredPlugins[".babylon"];
  30190. };
  30191. SceneLoader._getPluginForExtension = function (extension) {
  30192. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30193. if (registeredPlugin) {
  30194. return registeredPlugin;
  30195. }
  30196. return SceneLoader._getDefaultPlugin();
  30197. };
  30198. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30199. if (sceneFilename.name) {
  30200. sceneFilename = sceneFilename.name;
  30201. }
  30202. var dotPosition = sceneFilename.lastIndexOf(".");
  30203. var queryStringPosition = sceneFilename.indexOf("?");
  30204. if (queryStringPosition === -1) {
  30205. queryStringPosition = sceneFilename.length;
  30206. }
  30207. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30208. return SceneLoader._getPluginForExtension(extension);
  30209. };
  30210. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30211. SceneLoader._getDirectLoad = function (sceneFilename) {
  30212. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30213. return sceneFilename.substr(5);
  30214. }
  30215. return null;
  30216. };
  30217. // Public functions
  30218. SceneLoader.GetPluginForExtension = function (extension) {
  30219. return SceneLoader._getPluginForExtension(extension).plugin;
  30220. };
  30221. SceneLoader.RegisterPlugin = function (plugin) {
  30222. if (typeof plugin.extensions === "string") {
  30223. var extension = plugin.extensions;
  30224. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30225. plugin: plugin,
  30226. isBinary: false
  30227. };
  30228. }
  30229. else {
  30230. var extensions = plugin.extensions;
  30231. Object.keys(extensions).forEach(function (extension) {
  30232. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30233. plugin: plugin,
  30234. isBinary: extensions[extension].isBinary
  30235. };
  30236. });
  30237. }
  30238. };
  30239. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30240. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30241. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30242. return;
  30243. }
  30244. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30245. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30246. return;
  30247. }
  30248. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30249. var loadingToken = {};
  30250. scene._addPendingData(loadingToken);
  30251. var manifestChecked = function (success) {
  30252. scene.database = database;
  30253. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30254. var plugin = registeredPlugin.plugin;
  30255. var useArrayBuffer = registeredPlugin.isBinary;
  30256. var importMeshFromData = function (data) {
  30257. var meshes = [];
  30258. var particleSystems = [];
  30259. var skeletons = [];
  30260. try {
  30261. if (plugin.importMesh) {
  30262. var syncedPlugin = plugin;
  30263. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  30264. if (onerror) {
  30265. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30266. }
  30267. scene._removePendingData(loadingToken);
  30268. return;
  30269. }
  30270. if (onsuccess) {
  30271. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30272. onsuccess(meshes, particleSystems, skeletons);
  30273. scene._removePendingData(loadingToken);
  30274. }
  30275. }
  30276. else {
  30277. var asyncedPlugin = plugin;
  30278. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  30279. if (onsuccess) {
  30280. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30281. onsuccess(meshes, particleSystems, skeletons);
  30282. scene._removePendingData(loadingToken);
  30283. }
  30284. }, function () {
  30285. if (onerror) {
  30286. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30287. }
  30288. scene._removePendingData(loadingToken);
  30289. });
  30290. }
  30291. }
  30292. catch (e) {
  30293. if (onerror) {
  30294. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  30295. }
  30296. scene._removePendingData(loadingToken);
  30297. }
  30298. };
  30299. if (directLoad) {
  30300. importMeshFromData(directLoad);
  30301. return;
  30302. }
  30303. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  30304. importMeshFromData(data);
  30305. }, progressCallBack, database, useArrayBuffer);
  30306. };
  30307. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  30308. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30309. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30310. }
  30311. else {
  30312. // If the scene is a data stream or offline support is not enabled, it's a direct load
  30313. manifestChecked(true);
  30314. }
  30315. };
  30316. /**
  30317. * Load a scene
  30318. * @param rootUrl a string that defines the root url for scene and resources
  30319. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30320. * @param engine is the instance of BABYLON.Engine to use to create the scene
  30321. */
  30322. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  30323. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  30324. };
  30325. /**
  30326. * Append a scene
  30327. * @param rootUrl a string that defines the root url for scene and resources
  30328. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30329. * @param scene is the instance of BABYLON.Scene to append to
  30330. */
  30331. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30332. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30333. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30334. return;
  30335. }
  30336. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30337. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30338. var plugin = registeredPlugin.plugin;
  30339. var useArrayBuffer = registeredPlugin.isBinary;
  30340. var database;
  30341. var loadingToken = {};
  30342. scene._addPendingData(loadingToken);
  30343. if (SceneLoader.ShowLoadingScreen) {
  30344. scene.getEngine().displayLoadingUI();
  30345. }
  30346. var loadSceneFromData = function (data) {
  30347. scene.database = database;
  30348. if (plugin.load) {
  30349. var syncedPlugin = plugin;
  30350. if (!syncedPlugin.load(scene, data, rootUrl)) {
  30351. if (onerror) {
  30352. onerror(scene);
  30353. }
  30354. scene._removePendingData(loadingToken);
  30355. scene.getEngine().hideLoadingUI();
  30356. return;
  30357. }
  30358. if (onsuccess) {
  30359. onsuccess(scene);
  30360. }
  30361. scene._removePendingData(loadingToken);
  30362. }
  30363. else {
  30364. var asyncedPlugin = plugin;
  30365. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  30366. if (onsuccess) {
  30367. onsuccess(scene);
  30368. }
  30369. scene._removePendingData(loadingToken);
  30370. }, function () {
  30371. if (onerror) {
  30372. onerror(scene);
  30373. }
  30374. scene._removePendingData(loadingToken);
  30375. scene.getEngine().hideLoadingUI();
  30376. });
  30377. }
  30378. if (SceneLoader.ShowLoadingScreen) {
  30379. scene.executeWhenReady(function () {
  30380. scene.getEngine().hideLoadingUI();
  30381. });
  30382. }
  30383. };
  30384. var manifestChecked = function (success) {
  30385. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  30386. };
  30387. if (directLoad) {
  30388. loadSceneFromData(directLoad);
  30389. return;
  30390. }
  30391. if (rootUrl.indexOf("file:") === -1) {
  30392. if (scene.getEngine().enableOfflineSupport) {
  30393. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30394. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30395. }
  30396. else {
  30397. manifestChecked(true);
  30398. }
  30399. }
  30400. else {
  30401. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  30402. }
  30403. };
  30404. return SceneLoader;
  30405. }());
  30406. // Flags
  30407. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  30408. SceneLoader._ShowLoadingScreen = true;
  30409. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  30410. // Members
  30411. SceneLoader._registeredPlugins = {};
  30412. BABYLON.SceneLoader = SceneLoader;
  30413. ;
  30414. })(BABYLON || (BABYLON = {}));
  30415. //# sourceMappingURL=babylon.sceneLoader.js.map
  30416. var BABYLON;
  30417. (function (BABYLON) {
  30418. var Internals;
  30419. (function (Internals) {
  30420. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  30421. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30422. var parsedMaterial = parsedData.materials[index];
  30423. if (parsedMaterial.id === id) {
  30424. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30425. }
  30426. }
  30427. return null;
  30428. };
  30429. var isDescendantOf = function (mesh, names, hierarchyIds) {
  30430. names = (names instanceof Array) ? names : [names];
  30431. for (var i in names) {
  30432. if (mesh.name === names[i]) {
  30433. hierarchyIds.push(mesh.id);
  30434. return true;
  30435. }
  30436. }
  30437. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  30438. hierarchyIds.push(mesh.id);
  30439. return true;
  30440. }
  30441. return false;
  30442. };
  30443. var logOperation = function (operation, producer) {
  30444. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  30445. };
  30446. BABYLON.SceneLoader.RegisterPlugin({
  30447. extensions: ".babylon",
  30448. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  30449. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30450. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30451. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30452. // and avoid problems with multiple concurrent .babylon loads.
  30453. var log = "importMesh has failed JSON parse";
  30454. try {
  30455. var parsedData = JSON.parse(data);
  30456. log = "";
  30457. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30458. var loadedSkeletonsIds = [];
  30459. var loadedMaterialsIds = [];
  30460. var hierarchyIds = [];
  30461. var index;
  30462. var cache;
  30463. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30464. var parsedMesh = parsedData.meshes[index];
  30465. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  30466. if (meshesNames instanceof Array) {
  30467. // Remove found mesh name from list.
  30468. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  30469. }
  30470. //Geometry?
  30471. if (parsedMesh.geometryId) {
  30472. //does the file contain geometries?
  30473. if (parsedData.geometries) {
  30474. //find the correct geometry and add it to the scene
  30475. var found = false;
  30476. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  30477. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  30478. return;
  30479. }
  30480. else {
  30481. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  30482. if (parsedGeometryData.id === parsedMesh.geometryId) {
  30483. switch (geometryType) {
  30484. case "boxes":
  30485. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  30486. break;
  30487. case "spheres":
  30488. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  30489. break;
  30490. case "cylinders":
  30491. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  30492. break;
  30493. case "toruses":
  30494. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  30495. break;
  30496. case "grounds":
  30497. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  30498. break;
  30499. case "planes":
  30500. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  30501. break;
  30502. case "torusKnots":
  30503. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  30504. break;
  30505. case "vertexData":
  30506. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  30507. break;
  30508. }
  30509. found = true;
  30510. }
  30511. });
  30512. }
  30513. });
  30514. if (!found) {
  30515. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  30516. }
  30517. }
  30518. }
  30519. // Material ?
  30520. if (parsedMesh.materialId) {
  30521. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  30522. if (!materialFound && parsedData.multiMaterials) {
  30523. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  30524. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  30525. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  30526. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  30527. var subMatId = parsedMultiMaterial.materials[matIndex];
  30528. loadedMaterialsIds.push(subMatId);
  30529. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  30530. log += "\n\tMaterial " + mat.toString(fullDetails);
  30531. }
  30532. loadedMaterialsIds.push(parsedMultiMaterial.id);
  30533. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30534. materialFound = true;
  30535. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  30536. break;
  30537. }
  30538. }
  30539. }
  30540. if (!materialFound) {
  30541. loadedMaterialsIds.push(parsedMesh.materialId);
  30542. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  30543. if (!mat) {
  30544. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  30545. }
  30546. else {
  30547. log += "\n\tMaterial " + mat.toString(fullDetails);
  30548. }
  30549. }
  30550. }
  30551. // Skeleton ?
  30552. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  30553. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  30554. if (!skeletonAlreadyLoaded) {
  30555. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  30556. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  30557. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  30558. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30559. skeletons.push(skeleton);
  30560. loadedSkeletonsIds.push(parsedSkeleton.id);
  30561. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  30562. }
  30563. }
  30564. }
  30565. }
  30566. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30567. meshes.push(mesh);
  30568. log += "\n\tMesh " + mesh.toString(fullDetails);
  30569. }
  30570. }
  30571. // Connecting parents
  30572. var currentMesh;
  30573. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30574. currentMesh = scene.meshes[index];
  30575. if (currentMesh._waitingParentId) {
  30576. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  30577. currentMesh._waitingParentId = undefined;
  30578. }
  30579. }
  30580. // freeze and compute world matrix application
  30581. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30582. currentMesh = scene.meshes[index];
  30583. if (currentMesh._waitingFreezeWorldMatrix) {
  30584. currentMesh.freezeWorldMatrix();
  30585. currentMesh._waitingFreezeWorldMatrix = undefined;
  30586. }
  30587. else {
  30588. currentMesh.computeWorldMatrix(true);
  30589. }
  30590. }
  30591. // Particles
  30592. if (parsedData.particleSystems) {
  30593. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30594. var parsedParticleSystem = parsedData.particleSystems[index];
  30595. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  30596. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  30597. }
  30598. }
  30599. }
  30600. return true;
  30601. }
  30602. catch (err) {
  30603. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  30604. log = null;
  30605. throw err;
  30606. }
  30607. finally {
  30608. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30609. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30610. }
  30611. }
  30612. },
  30613. load: function (scene, data, rootUrl) {
  30614. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30615. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30616. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30617. // and avoid problems with multiple concurrent .babylon loads.
  30618. var log = "importScene has failed JSON parse";
  30619. try {
  30620. var parsedData = JSON.parse(data);
  30621. log = "";
  30622. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30623. // Scene
  30624. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  30625. scene.autoClear = parsedData.autoClear;
  30626. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  30627. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  30628. if (parsedData.gravity) {
  30629. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  30630. }
  30631. // Fog
  30632. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  30633. scene.fogMode = parsedData.fogMode;
  30634. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  30635. scene.fogStart = parsedData.fogStart;
  30636. scene.fogEnd = parsedData.fogEnd;
  30637. scene.fogDensity = parsedData.fogDensity;
  30638. log += "\tFog mode for scene: ";
  30639. switch (scene.fogMode) {
  30640. // getters not compiling, so using hardcoded
  30641. case 1:
  30642. log += "exp\n";
  30643. break;
  30644. case 2:
  30645. log += "exp2\n";
  30646. break;
  30647. case 3:
  30648. log += "linear\n";
  30649. break;
  30650. }
  30651. }
  30652. //Physics
  30653. if (parsedData.physicsEnabled) {
  30654. var physicsPlugin;
  30655. if (parsedData.physicsEngine === "cannon") {
  30656. physicsPlugin = new BABYLON.CannonJSPlugin();
  30657. }
  30658. else if (parsedData.physicsEngine === "oimo") {
  30659. physicsPlugin = new BABYLON.OimoJSPlugin();
  30660. }
  30661. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  30662. //else - default engine, which is currently oimo
  30663. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  30664. scene.enablePhysics(physicsGravity, physicsPlugin);
  30665. }
  30666. // Metadata
  30667. if (parsedData.metadata !== undefined) {
  30668. scene.metadata = parsedData.metadata;
  30669. }
  30670. //collisions, if defined. otherwise, default is true
  30671. if (parsedData.collisionsEnabled != undefined) {
  30672. scene.collisionsEnabled = parsedData.collisionsEnabled;
  30673. }
  30674. scene.workerCollisions = !!parsedData.workerCollisions;
  30675. var index;
  30676. var cache;
  30677. // Lights
  30678. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  30679. var parsedLight = parsedData.lights[index];
  30680. var light = BABYLON.Light.Parse(parsedLight, scene);
  30681. log += (index === 0 ? "\n\tLights:" : "");
  30682. log += "\n\t\t" + light.toString(fullDetails);
  30683. }
  30684. // Animations
  30685. if (parsedData.animations) {
  30686. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  30687. var parsedAnimation = parsedData.animations[index];
  30688. var animation = BABYLON.Animation.Parse(parsedAnimation);
  30689. scene.animations.push(animation);
  30690. log += (index === 0 ? "\n\tAnimations:" : "");
  30691. log += "\n\t\t" + animation.toString(fullDetails);
  30692. }
  30693. }
  30694. if (parsedData.autoAnimate) {
  30695. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  30696. }
  30697. // Materials
  30698. if (parsedData.materials) {
  30699. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30700. var parsedMaterial = parsedData.materials[index];
  30701. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30702. log += (index === 0 ? "\n\tMaterials:" : "");
  30703. log += "\n\t\t" + mat.toString(fullDetails);
  30704. }
  30705. }
  30706. if (parsedData.multiMaterials) {
  30707. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  30708. var parsedMultiMaterial = parsedData.multiMaterials[index];
  30709. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30710. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  30711. log += "\n\t\t" + mmat.toString(fullDetails);
  30712. }
  30713. }
  30714. // Skeletons
  30715. if (parsedData.skeletons) {
  30716. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  30717. var parsedSkeleton = parsedData.skeletons[index];
  30718. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30719. log += (index === 0 ? "\n\tSkeletons:" : "");
  30720. log += "\n\t\t" + skeleton.toString(fullDetails);
  30721. }
  30722. }
  30723. // Geometries
  30724. var geometries = parsedData.geometries;
  30725. if (geometries) {
  30726. // Boxes
  30727. var boxes = geometries.boxes;
  30728. if (boxes) {
  30729. for (index = 0, cache = boxes.length; index < cache; index++) {
  30730. var parsedBox = boxes[index];
  30731. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  30732. }
  30733. }
  30734. // Spheres
  30735. var spheres = geometries.spheres;
  30736. if (spheres) {
  30737. for (index = 0, cache = spheres.length; index < cache; index++) {
  30738. var parsedSphere = spheres[index];
  30739. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  30740. }
  30741. }
  30742. // Cylinders
  30743. var cylinders = geometries.cylinders;
  30744. if (cylinders) {
  30745. for (index = 0, cache = cylinders.length; index < cache; index++) {
  30746. var parsedCylinder = cylinders[index];
  30747. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  30748. }
  30749. }
  30750. // Toruses
  30751. var toruses = geometries.toruses;
  30752. if (toruses) {
  30753. for (index = 0, cache = toruses.length; index < cache; index++) {
  30754. var parsedTorus = toruses[index];
  30755. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  30756. }
  30757. }
  30758. // Grounds
  30759. var grounds = geometries.grounds;
  30760. if (grounds) {
  30761. for (index = 0, cache = grounds.length; index < cache; index++) {
  30762. var parsedGround = grounds[index];
  30763. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  30764. }
  30765. }
  30766. // Planes
  30767. var planes = geometries.planes;
  30768. if (planes) {
  30769. for (index = 0, cache = planes.length; index < cache; index++) {
  30770. var parsedPlane = planes[index];
  30771. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  30772. }
  30773. }
  30774. // TorusKnots
  30775. var torusKnots = geometries.torusKnots;
  30776. if (torusKnots) {
  30777. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  30778. var parsedTorusKnot = torusKnots[index];
  30779. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  30780. }
  30781. }
  30782. // VertexData
  30783. var vertexData = geometries.vertexData;
  30784. if (vertexData) {
  30785. for (index = 0, cache = vertexData.length; index < cache; index++) {
  30786. var parsedVertexData = vertexData[index];
  30787. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  30788. }
  30789. }
  30790. }
  30791. // Meshes
  30792. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30793. var parsedMesh = parsedData.meshes[index];
  30794. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30795. log += (index === 0 ? "\n\tMeshes:" : "");
  30796. log += "\n\t\t" + mesh.toString(fullDetails);
  30797. }
  30798. // Cameras
  30799. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  30800. var parsedCamera = parsedData.cameras[index];
  30801. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  30802. log += (index === 0 ? "\n\tCameras:" : "");
  30803. log += "\n\t\t" + camera.toString(fullDetails);
  30804. }
  30805. if (parsedData.activeCameraID) {
  30806. scene.setActiveCameraByID(parsedData.activeCameraID);
  30807. }
  30808. // Browsing all the graph to connect the dots
  30809. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  30810. var camera = scene.cameras[index];
  30811. if (camera._waitingParentId) {
  30812. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  30813. camera._waitingParentId = undefined;
  30814. }
  30815. }
  30816. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  30817. var light = scene.lights[index];
  30818. if (light._waitingParentId) {
  30819. light.parent = scene.getLastEntryByID(light._waitingParentId);
  30820. light._waitingParentId = undefined;
  30821. }
  30822. }
  30823. // Sounds
  30824. var loadedSounds = [];
  30825. var loadedSound;
  30826. if (BABYLON.AudioEngine && parsedData.sounds) {
  30827. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  30828. var parsedSound = parsedData.sounds[index];
  30829. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30830. if (!parsedSound.url)
  30831. parsedSound.url = parsedSound.name;
  30832. if (!loadedSounds[parsedSound.url]) {
  30833. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  30834. loadedSounds[parsedSound.url] = loadedSound;
  30835. }
  30836. else {
  30837. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  30838. }
  30839. }
  30840. else {
  30841. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  30842. }
  30843. }
  30844. }
  30845. loadedSounds = [];
  30846. // Connect parents & children and parse actions
  30847. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30848. var mesh = scene.meshes[index];
  30849. if (mesh._waitingParentId) {
  30850. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  30851. mesh._waitingParentId = undefined;
  30852. }
  30853. if (mesh._waitingActions) {
  30854. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  30855. mesh._waitingActions = undefined;
  30856. }
  30857. }
  30858. // freeze world matrix application
  30859. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30860. var currentMesh = scene.meshes[index];
  30861. if (currentMesh._waitingFreezeWorldMatrix) {
  30862. currentMesh.freezeWorldMatrix();
  30863. currentMesh._waitingFreezeWorldMatrix = undefined;
  30864. }
  30865. else {
  30866. currentMesh.computeWorldMatrix(true);
  30867. }
  30868. }
  30869. // Particles Systems
  30870. if (parsedData.particleSystems) {
  30871. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30872. var parsedParticleSystem = parsedData.particleSystems[index];
  30873. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  30874. }
  30875. }
  30876. // Lens flares
  30877. if (parsedData.lensFlareSystems) {
  30878. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  30879. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  30880. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  30881. }
  30882. }
  30883. // Shadows
  30884. if (parsedData.shadowGenerators) {
  30885. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  30886. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  30887. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  30888. }
  30889. }
  30890. // Actions (scene)
  30891. if (parsedData.actions) {
  30892. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  30893. }
  30894. // Finish
  30895. return true;
  30896. }
  30897. catch (err) {
  30898. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  30899. log = null;
  30900. throw err;
  30901. }
  30902. finally {
  30903. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30904. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30905. }
  30906. }
  30907. }
  30908. });
  30909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30910. })(BABYLON || (BABYLON = {}));
  30911. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  30912. var BABYLON;
  30913. (function (BABYLON) {
  30914. var SpriteManager = (function () {
  30915. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  30916. if (epsilon === void 0) { epsilon = 0.01; }
  30917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30918. this.name = name;
  30919. this.sprites = new Array();
  30920. this.renderingGroupId = 0;
  30921. this.layerMask = 0x0FFFFFFF;
  30922. this.fogEnabled = true;
  30923. this.isPickable = false;
  30924. /**
  30925. * An event triggered when the manager is disposed.
  30926. * @type {BABYLON.Observable}
  30927. */
  30928. this.onDisposeObservable = new BABYLON.Observable();
  30929. this._vertexBuffers = {};
  30930. this._capacity = capacity;
  30931. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  30932. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30933. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30934. if (cellSize.width && cellSize.height) {
  30935. this.cellWidth = cellSize.width;
  30936. this.cellHeight = cellSize.height;
  30937. }
  30938. else if (cellSize !== undefined) {
  30939. this.cellWidth = cellSize;
  30940. this.cellHeight = cellSize;
  30941. }
  30942. else {
  30943. return;
  30944. }
  30945. this._epsilon = epsilon;
  30946. this._scene = scene;
  30947. this._scene.spriteManagers.push(this);
  30948. var indices = [];
  30949. var index = 0;
  30950. for (var count = 0; count < capacity; count++) {
  30951. indices.push(index);
  30952. indices.push(index + 1);
  30953. indices.push(index + 2);
  30954. indices.push(index);
  30955. indices.push(index + 2);
  30956. indices.push(index + 3);
  30957. index += 4;
  30958. }
  30959. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  30960. // VBO
  30961. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  30962. this._vertexData = new Float32Array(capacity * 16 * 4);
  30963. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  30964. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  30965. var options = this._buffer.createVertexBuffer("options", 4, 4);
  30966. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  30967. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  30968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  30969. this._vertexBuffers["options"] = options;
  30970. this._vertexBuffers["cellInfo"] = cellInfo;
  30971. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  30972. // Effects
  30973. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  30974. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  30975. }
  30976. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  30977. set: function (callback) {
  30978. if (this._onDisposeObserver) {
  30979. this.onDisposeObservable.remove(this._onDisposeObserver);
  30980. }
  30981. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30982. },
  30983. enumerable: true,
  30984. configurable: true
  30985. });
  30986. Object.defineProperty(SpriteManager.prototype, "texture", {
  30987. get: function () {
  30988. return this._spriteTexture;
  30989. },
  30990. set: function (value) {
  30991. this._spriteTexture = value;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  30997. var arrayOffset = index * 16;
  30998. if (offsetX === 0)
  30999. offsetX = this._epsilon;
  31000. else if (offsetX === 1)
  31001. offsetX = 1 - this._epsilon;
  31002. if (offsetY === 0)
  31003. offsetY = this._epsilon;
  31004. else if (offsetY === 1)
  31005. offsetY = 1 - this._epsilon;
  31006. this._vertexData[arrayOffset] = sprite.position.x;
  31007. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31008. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31009. this._vertexData[arrayOffset + 3] = sprite.angle;
  31010. this._vertexData[arrayOffset + 4] = sprite.width;
  31011. this._vertexData[arrayOffset + 5] = sprite.height;
  31012. this._vertexData[arrayOffset + 6] = offsetX;
  31013. this._vertexData[arrayOffset + 7] = offsetY;
  31014. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31015. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31016. var offset = (sprite.cellIndex / rowSize) >> 0;
  31017. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31018. this._vertexData[arrayOffset + 11] = offset;
  31019. // Color
  31020. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31021. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31022. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31023. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31024. };
  31025. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31026. var count = Math.min(this._capacity, this.sprites.length);
  31027. var min = BABYLON.Vector3.Zero();
  31028. var max = BABYLON.Vector3.Zero();
  31029. var distance = Number.MAX_VALUE;
  31030. var currentSprite;
  31031. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31032. var cameraView = camera.getViewMatrix();
  31033. for (var index = 0; index < count; index++) {
  31034. var sprite = this.sprites[index];
  31035. if (!sprite) {
  31036. continue;
  31037. }
  31038. if (predicate) {
  31039. if (!predicate(sprite)) {
  31040. continue;
  31041. }
  31042. }
  31043. else if (!sprite.isPickable) {
  31044. continue;
  31045. }
  31046. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31047. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31048. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31049. if (ray.intersectsBoxMinMax(min, max)) {
  31050. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31051. if (distance > currentDistance) {
  31052. distance = currentDistance;
  31053. currentSprite = sprite;
  31054. if (fastCheck) {
  31055. break;
  31056. }
  31057. }
  31058. }
  31059. }
  31060. if (currentSprite) {
  31061. var result = new BABYLON.PickingInfo();
  31062. result.hit = true;
  31063. result.pickedSprite = currentSprite;
  31064. result.distance = distance;
  31065. return result;
  31066. }
  31067. return null;
  31068. };
  31069. SpriteManager.prototype.render = function () {
  31070. // Check
  31071. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31072. return;
  31073. var engine = this._scene.getEngine();
  31074. var baseSize = this._spriteTexture.getBaseSize();
  31075. // Sprites
  31076. var deltaTime = engine.getDeltaTime();
  31077. var max = Math.min(this._capacity, this.sprites.length);
  31078. var rowSize = baseSize.width / this.cellWidth;
  31079. var offset = 0;
  31080. for (var index = 0; index < max; index++) {
  31081. var sprite = this.sprites[index];
  31082. if (!sprite) {
  31083. continue;
  31084. }
  31085. sprite._animate(deltaTime);
  31086. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31087. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31088. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31089. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31090. }
  31091. this._buffer.update(this._vertexData);
  31092. // Render
  31093. var effect = this._effectBase;
  31094. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31095. effect = this._effectFog;
  31096. }
  31097. engine.enableEffect(effect);
  31098. var viewMatrix = this._scene.getViewMatrix();
  31099. effect.setTexture("diffuseSampler", this._spriteTexture);
  31100. effect.setMatrix("view", viewMatrix);
  31101. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31102. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31103. // Fog
  31104. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31105. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31106. effect.setColor3("vFogColor", this._scene.fogColor);
  31107. }
  31108. // VBOs
  31109. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31110. // Draw order
  31111. engine.setDepthFunctionToLessOrEqual();
  31112. effect.setBool("alphaTest", true);
  31113. engine.setColorWrite(false);
  31114. engine.draw(true, 0, max * 6);
  31115. engine.setColorWrite(true);
  31116. effect.setBool("alphaTest", false);
  31117. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31118. engine.draw(true, 0, max * 6);
  31119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31120. };
  31121. SpriteManager.prototype.dispose = function () {
  31122. if (this._buffer) {
  31123. this._buffer.dispose();
  31124. this._buffer = null;
  31125. }
  31126. if (this._indexBuffer) {
  31127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31128. this._indexBuffer = null;
  31129. }
  31130. if (this._spriteTexture) {
  31131. this._spriteTexture.dispose();
  31132. this._spriteTexture = null;
  31133. }
  31134. // Remove from scene
  31135. var index = this._scene.spriteManagers.indexOf(this);
  31136. this._scene.spriteManagers.splice(index, 1);
  31137. // Callback
  31138. this.onDisposeObservable.notifyObservers(this);
  31139. this.onDisposeObservable.clear();
  31140. };
  31141. return SpriteManager;
  31142. }());
  31143. BABYLON.SpriteManager = SpriteManager;
  31144. })(BABYLON || (BABYLON = {}));
  31145. //# sourceMappingURL=babylon.spriteManager.js.map
  31146. var BABYLON;
  31147. (function (BABYLON) {
  31148. var Sprite = (function () {
  31149. function Sprite(name, manager) {
  31150. this.name = name;
  31151. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31152. this.width = 1.0;
  31153. this.height = 1.0;
  31154. this.angle = 0;
  31155. this.cellIndex = 0;
  31156. this.invertU = 0;
  31157. this.invertV = 0;
  31158. this.animations = new Array();
  31159. this.isPickable = false;
  31160. this._animationStarted = false;
  31161. this._loopAnimation = false;
  31162. this._fromIndex = 0;
  31163. this._toIndex = 0;
  31164. this._delay = 0;
  31165. this._direction = 1;
  31166. this._frameCount = 0;
  31167. this._time = 0;
  31168. this._manager = manager;
  31169. this._manager.sprites.push(this);
  31170. this.position = BABYLON.Vector3.Zero();
  31171. }
  31172. Object.defineProperty(Sprite.prototype, "size", {
  31173. get: function () {
  31174. return this.width;
  31175. },
  31176. set: function (value) {
  31177. this.width = value;
  31178. this.height = value;
  31179. },
  31180. enumerable: true,
  31181. configurable: true
  31182. });
  31183. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31184. this._fromIndex = from;
  31185. this._toIndex = to;
  31186. this._loopAnimation = loop;
  31187. this._delay = delay;
  31188. this._animationStarted = true;
  31189. this._direction = from < to ? 1 : -1;
  31190. this.cellIndex = from;
  31191. this._time = 0;
  31192. this._onAnimationEnd = onAnimationEnd;
  31193. };
  31194. Sprite.prototype.stopAnimation = function () {
  31195. this._animationStarted = false;
  31196. };
  31197. Sprite.prototype._animate = function (deltaTime) {
  31198. if (!this._animationStarted)
  31199. return;
  31200. this._time += deltaTime;
  31201. if (this._time > this._delay) {
  31202. this._time = this._time % this._delay;
  31203. this.cellIndex += this._direction;
  31204. if (this.cellIndex === this._toIndex) {
  31205. if (this._loopAnimation) {
  31206. this.cellIndex = this._fromIndex;
  31207. }
  31208. else {
  31209. this._animationStarted = false;
  31210. if (this._onAnimationEnd) {
  31211. this._onAnimationEnd();
  31212. }
  31213. if (this.disposeWhenFinishedAnimating) {
  31214. this.dispose();
  31215. }
  31216. }
  31217. }
  31218. }
  31219. };
  31220. Sprite.prototype.dispose = function () {
  31221. for (var i = 0; i < this._manager.sprites.length; i++) {
  31222. if (this._manager.sprites[i] == this) {
  31223. this._manager.sprites.splice(i, 1);
  31224. }
  31225. }
  31226. };
  31227. return Sprite;
  31228. }());
  31229. BABYLON.Sprite = Sprite;
  31230. })(BABYLON || (BABYLON = {}));
  31231. //# sourceMappingURL=babylon.sprite.js.map
  31232. var BABYLON;
  31233. (function (BABYLON) {
  31234. var Layer = (function () {
  31235. function Layer(name, imgUrl, scene, isBackground, color) {
  31236. this.name = name;
  31237. this.scale = new BABYLON.Vector2(1, 1);
  31238. this.offset = new BABYLON.Vector2(0, 0);
  31239. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31240. this._vertexBuffers = {};
  31241. // Events
  31242. /**
  31243. * An event triggered when the layer is disposed.
  31244. * @type {BABYLON.Observable}
  31245. */
  31246. this.onDisposeObservable = new BABYLON.Observable();
  31247. /**
  31248. * An event triggered before rendering the scene
  31249. * @type {BABYLON.Observable}
  31250. */
  31251. this.onBeforeRenderObservable = new BABYLON.Observable();
  31252. /**
  31253. * An event triggered after rendering the scene
  31254. * @type {BABYLON.Observable}
  31255. */
  31256. this.onAfterRenderObservable = new BABYLON.Observable();
  31257. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  31258. this.isBackground = isBackground === undefined ? true : isBackground;
  31259. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  31260. this._scene = scene;
  31261. this._scene.layers.push(this);
  31262. var engine = scene.getEngine();
  31263. // VBO
  31264. var vertices = [];
  31265. vertices.push(1, 1);
  31266. vertices.push(-1, 1);
  31267. vertices.push(-1, -1);
  31268. vertices.push(1, -1);
  31269. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  31271. // Indices
  31272. var indices = [];
  31273. indices.push(0);
  31274. indices.push(1);
  31275. indices.push(2);
  31276. indices.push(0);
  31277. indices.push(2);
  31278. indices.push(3);
  31279. this._indexBuffer = engine.createIndexBuffer(indices);
  31280. // Effects
  31281. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  31282. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  31283. }
  31284. Object.defineProperty(Layer.prototype, "onDispose", {
  31285. set: function (callback) {
  31286. if (this._onDisposeObserver) {
  31287. this.onDisposeObservable.remove(this._onDisposeObserver);
  31288. }
  31289. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  31295. set: function (callback) {
  31296. if (this._onBeforeRenderObserver) {
  31297. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31298. }
  31299. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31300. },
  31301. enumerable: true,
  31302. configurable: true
  31303. });
  31304. Object.defineProperty(Layer.prototype, "onAfterRender", {
  31305. set: function (callback) {
  31306. if (this._onAfterRenderObserver) {
  31307. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31308. }
  31309. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Layer.prototype.render = function () {
  31315. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  31316. // Check
  31317. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  31318. return;
  31319. var engine = this._scene.getEngine();
  31320. this.onBeforeRenderObservable.notifyObservers(this);
  31321. // Render
  31322. engine.enableEffect(currentEffect);
  31323. engine.setState(false);
  31324. // Texture
  31325. currentEffect.setTexture("textureSampler", this.texture);
  31326. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  31327. // Color
  31328. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  31329. // Scale / offset
  31330. currentEffect.setVector2("offset", this.offset);
  31331. currentEffect.setVector2("scale", this.scale);
  31332. // VBOs
  31333. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  31334. // Draw order
  31335. if (!this.alphaTest) {
  31336. engine.setAlphaMode(this.alphaBlendingMode);
  31337. engine.draw(true, 0, 6);
  31338. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31339. }
  31340. else {
  31341. engine.draw(true, 0, 6);
  31342. }
  31343. this.onAfterRenderObservable.notifyObservers(this);
  31344. };
  31345. Layer.prototype.dispose = function () {
  31346. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31347. if (vertexBuffer) {
  31348. vertexBuffer.dispose();
  31349. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31350. }
  31351. if (this._indexBuffer) {
  31352. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31353. this._indexBuffer = null;
  31354. }
  31355. if (this.texture) {
  31356. this.texture.dispose();
  31357. this.texture = null;
  31358. }
  31359. // Remove from scene
  31360. var index = this._scene.layers.indexOf(this);
  31361. this._scene.layers.splice(index, 1);
  31362. // Callback
  31363. this.onDisposeObservable.notifyObservers(this);
  31364. this.onDisposeObservable.clear();
  31365. this.onAfterRenderObservable.clear();
  31366. this.onBeforeRenderObservable.clear();
  31367. };
  31368. return Layer;
  31369. }());
  31370. BABYLON.Layer = Layer;
  31371. })(BABYLON || (BABYLON = {}));
  31372. //# sourceMappingURL=babylon.layer.js.map
  31373. var BABYLON;
  31374. (function (BABYLON) {
  31375. var Particle = (function () {
  31376. function Particle() {
  31377. this.position = BABYLON.Vector3.Zero();
  31378. this.direction = BABYLON.Vector3.Zero();
  31379. this.color = new BABYLON.Color4(0, 0, 0, 0);
  31380. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  31381. this.lifeTime = 1.0;
  31382. this.age = 0;
  31383. this.size = 0;
  31384. this.angle = 0;
  31385. this.angularSpeed = 0;
  31386. }
  31387. Particle.prototype.copyTo = function (other) {
  31388. other.position.copyFrom(this.position);
  31389. other.direction.copyFrom(this.direction);
  31390. other.color.copyFrom(this.color);
  31391. other.colorStep.copyFrom(this.colorStep);
  31392. other.lifeTime = this.lifeTime;
  31393. other.age = this.age;
  31394. other.size = this.size;
  31395. other.angle = this.angle;
  31396. other.angularSpeed = this.angularSpeed;
  31397. };
  31398. return Particle;
  31399. }());
  31400. BABYLON.Particle = Particle;
  31401. })(BABYLON || (BABYLON = {}));
  31402. //# sourceMappingURL=babylon.particle.js.map
  31403. var BABYLON;
  31404. (function (BABYLON) {
  31405. var randomNumber = function (min, max) {
  31406. if (min === max) {
  31407. return (min);
  31408. }
  31409. var random = Math.random();
  31410. return ((random * (max - min)) + min);
  31411. };
  31412. var ParticleSystem = (function () {
  31413. function ParticleSystem(name, capacity, scene, customEffect) {
  31414. var _this = this;
  31415. this.name = name;
  31416. // Members
  31417. this.animations = [];
  31418. this.renderingGroupId = 0;
  31419. this.emitter = null;
  31420. this.emitRate = 10;
  31421. this.manualEmitCount = -1;
  31422. this.updateSpeed = 0.01;
  31423. this.targetStopDuration = 0;
  31424. this.disposeOnStop = false;
  31425. this.minEmitPower = 1;
  31426. this.maxEmitPower = 1;
  31427. this.minLifeTime = 1;
  31428. this.maxLifeTime = 1;
  31429. this.minSize = 1;
  31430. this.maxSize = 1;
  31431. this.minAngularSpeed = 0;
  31432. this.maxAngularSpeed = 0;
  31433. this.layerMask = 0x0FFFFFFF;
  31434. this.customShader = null;
  31435. this.preventAutoStart = false;
  31436. /**
  31437. * An event triggered when the system is disposed.
  31438. * @type {BABYLON.Observable}
  31439. */
  31440. this.onDisposeObservable = new BABYLON.Observable();
  31441. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  31442. this.forceDepthWrite = false;
  31443. this.gravity = BABYLON.Vector3.Zero();
  31444. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  31445. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  31446. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  31447. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31448. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31449. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31450. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  31451. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31452. this.particles = new Array();
  31453. this._stockParticles = new Array();
  31454. this._newPartsExcess = 0;
  31455. this._vertexBuffers = {};
  31456. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  31457. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  31458. this._scaledDirection = BABYLON.Vector3.Zero();
  31459. this._scaledGravity = BABYLON.Vector3.Zero();
  31460. this._currentRenderId = -1;
  31461. this._started = false;
  31462. this._stopped = false;
  31463. this._actualFrame = 0;
  31464. this.id = name;
  31465. this._capacity = capacity;
  31466. this._scene = scene;
  31467. this._customEffect = customEffect;
  31468. scene.particleSystems.push(this);
  31469. var indices = [];
  31470. var index = 0;
  31471. for (var count = 0; count < capacity; count++) {
  31472. indices.push(index);
  31473. indices.push(index + 1);
  31474. indices.push(index + 2);
  31475. indices.push(index);
  31476. indices.push(index + 2);
  31477. indices.push(index + 3);
  31478. index += 4;
  31479. }
  31480. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31481. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  31482. this._vertexData = new Float32Array(capacity * 11 * 4);
  31483. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  31484. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  31485. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  31486. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  31487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31488. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31489. this._vertexBuffers["options"] = options;
  31490. // Default behaviors
  31491. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  31492. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  31493. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  31494. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  31495. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  31496. };
  31497. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  31498. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  31499. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  31500. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  31501. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  31502. };
  31503. this.updateFunction = function (particles) {
  31504. for (var index = 0; index < particles.length; index++) {
  31505. var particle = particles[index];
  31506. particle.age += _this._scaledUpdateSpeed;
  31507. if (particle.age >= particle.lifeTime) {
  31508. _this.recycleParticle(particle);
  31509. index--;
  31510. continue;
  31511. }
  31512. else {
  31513. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  31514. particle.color.addInPlace(_this._scaledColorStep);
  31515. if (particle.color.a < 0)
  31516. particle.color.a = 0;
  31517. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  31518. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  31519. particle.position.addInPlace(_this._scaledDirection);
  31520. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  31521. particle.direction.addInPlace(_this._scaledGravity);
  31522. }
  31523. }
  31524. };
  31525. }
  31526. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  31527. set: function (callback) {
  31528. if (this._onDisposeObserver) {
  31529. this.onDisposeObservable.remove(this._onDisposeObserver);
  31530. }
  31531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. ParticleSystem.prototype.recycleParticle = function (particle) {
  31537. var lastParticle = this.particles.pop();
  31538. if (lastParticle !== particle) {
  31539. lastParticle.copyTo(particle);
  31540. this._stockParticles.push(lastParticle);
  31541. }
  31542. };
  31543. ParticleSystem.prototype.getCapacity = function () {
  31544. return this._capacity;
  31545. };
  31546. ParticleSystem.prototype.isAlive = function () {
  31547. return this._alive;
  31548. };
  31549. ParticleSystem.prototype.isStarted = function () {
  31550. return this._started;
  31551. };
  31552. ParticleSystem.prototype.start = function () {
  31553. this._started = true;
  31554. this._stopped = false;
  31555. this._actualFrame = 0;
  31556. };
  31557. ParticleSystem.prototype.stop = function () {
  31558. this._stopped = true;
  31559. };
  31560. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  31561. var offset = index * 11;
  31562. this._vertexData[offset] = particle.position.x;
  31563. this._vertexData[offset + 1] = particle.position.y;
  31564. this._vertexData[offset + 2] = particle.position.z;
  31565. this._vertexData[offset + 3] = particle.color.r;
  31566. this._vertexData[offset + 4] = particle.color.g;
  31567. this._vertexData[offset + 5] = particle.color.b;
  31568. this._vertexData[offset + 6] = particle.color.a;
  31569. this._vertexData[offset + 7] = particle.angle;
  31570. this._vertexData[offset + 8] = particle.size;
  31571. this._vertexData[offset + 9] = offsetX;
  31572. this._vertexData[offset + 10] = offsetY;
  31573. };
  31574. ParticleSystem.prototype._update = function (newParticles) {
  31575. // Update current
  31576. this._alive = this.particles.length > 0;
  31577. this.updateFunction(this.particles);
  31578. // Add new ones
  31579. var worldMatrix;
  31580. if (this.emitter.position) {
  31581. worldMatrix = this.emitter.getWorldMatrix();
  31582. }
  31583. else {
  31584. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  31585. }
  31586. var particle;
  31587. for (var index = 0; index < newParticles; index++) {
  31588. if (this.particles.length === this._capacity) {
  31589. break;
  31590. }
  31591. if (this._stockParticles.length !== 0) {
  31592. particle = this._stockParticles.pop();
  31593. particle.age = 0;
  31594. }
  31595. else {
  31596. particle = new BABYLON.Particle();
  31597. }
  31598. this.particles.push(particle);
  31599. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  31600. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  31601. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  31602. particle.size = randomNumber(this.minSize, this.maxSize);
  31603. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  31604. this.startPositionFunction(worldMatrix, particle.position, particle);
  31605. var step = randomNumber(0, 1.0);
  31606. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  31607. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  31608. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  31609. }
  31610. };
  31611. ParticleSystem.prototype._getEffect = function () {
  31612. if (this._customEffect) {
  31613. return this._customEffect;
  31614. }
  31615. ;
  31616. var defines = [];
  31617. if (this._scene.clipPlane) {
  31618. defines.push("#define CLIPPLANE");
  31619. }
  31620. // Effect
  31621. var join = defines.join("\n");
  31622. if (this._cachedDefines !== join) {
  31623. this._cachedDefines = join;
  31624. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  31625. }
  31626. return this._effect;
  31627. };
  31628. ParticleSystem.prototype.animate = function () {
  31629. if (!this._started)
  31630. return;
  31631. var effect = this._getEffect();
  31632. // Check
  31633. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  31634. return;
  31635. if (this._currentRenderId === this._scene.getRenderId()) {
  31636. return;
  31637. }
  31638. this._currentRenderId = this._scene.getRenderId();
  31639. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  31640. // determine the number of particles we need to create
  31641. var newParticles;
  31642. if (this.manualEmitCount > -1) {
  31643. newParticles = this.manualEmitCount;
  31644. this._newPartsExcess = 0;
  31645. this.manualEmitCount = 0;
  31646. }
  31647. else {
  31648. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  31649. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  31650. }
  31651. if (this._newPartsExcess > 1.0) {
  31652. newParticles += this._newPartsExcess >> 0;
  31653. this._newPartsExcess -= this._newPartsExcess >> 0;
  31654. }
  31655. this._alive = false;
  31656. if (!this._stopped) {
  31657. this._actualFrame += this._scaledUpdateSpeed;
  31658. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  31659. this.stop();
  31660. }
  31661. else {
  31662. newParticles = 0;
  31663. }
  31664. this._update(newParticles);
  31665. // Stopped?
  31666. if (this._stopped) {
  31667. if (!this._alive) {
  31668. this._started = false;
  31669. if (this.disposeOnStop) {
  31670. this._scene._toBeDisposed.push(this);
  31671. }
  31672. }
  31673. }
  31674. // Update VBO
  31675. var offset = 0;
  31676. for (var index = 0; index < this.particles.length; index++) {
  31677. var particle = this.particles[index];
  31678. this._appendParticleVertex(offset++, particle, 0, 0);
  31679. this._appendParticleVertex(offset++, particle, 1, 0);
  31680. this._appendParticleVertex(offset++, particle, 1, 1);
  31681. this._appendParticleVertex(offset++, particle, 0, 1);
  31682. }
  31683. this._vertexBuffer.update(this._vertexData);
  31684. };
  31685. ParticleSystem.prototype.render = function () {
  31686. var effect = this._getEffect();
  31687. // Check
  31688. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  31689. return 0;
  31690. var engine = this._scene.getEngine();
  31691. // Render
  31692. engine.enableEffect(effect);
  31693. engine.setState(false);
  31694. var viewMatrix = this._scene.getViewMatrix();
  31695. effect.setTexture("diffuseSampler", this.particleTexture);
  31696. effect.setMatrix("view", viewMatrix);
  31697. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31698. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  31699. if (this._scene.clipPlane) {
  31700. var clipPlane = this._scene.clipPlane;
  31701. var invView = viewMatrix.clone();
  31702. invView.invert();
  31703. effect.setMatrix("invView", invView);
  31704. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  31705. }
  31706. // VBOs
  31707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31708. // Draw order
  31709. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  31710. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  31711. }
  31712. else {
  31713. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31714. }
  31715. if (this.forceDepthWrite) {
  31716. engine.setDepthWrite(true);
  31717. }
  31718. engine.draw(true, 0, this.particles.length * 6);
  31719. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31720. return this.particles.length;
  31721. };
  31722. ParticleSystem.prototype.dispose = function () {
  31723. if (this._vertexBuffer) {
  31724. this._vertexBuffer.dispose();
  31725. this._vertexBuffer = null;
  31726. }
  31727. if (this._indexBuffer) {
  31728. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31729. this._indexBuffer = null;
  31730. }
  31731. if (this.particleTexture) {
  31732. this.particleTexture.dispose();
  31733. this.particleTexture = null;
  31734. }
  31735. // Remove from scene
  31736. var index = this._scene.particleSystems.indexOf(this);
  31737. this._scene.particleSystems.splice(index, 1);
  31738. // Callback
  31739. this.onDisposeObservable.notifyObservers(this);
  31740. this.onDisposeObservable.clear();
  31741. };
  31742. // Clone
  31743. ParticleSystem.prototype.clone = function (name, newEmitter) {
  31744. var custom = null;
  31745. var program = null;
  31746. if (this.customShader != null) {
  31747. program = this.customShader;
  31748. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31749. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31750. }
  31751. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  31752. result.customShader = program;
  31753. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  31754. if (newEmitter === undefined) {
  31755. newEmitter = this.emitter;
  31756. }
  31757. result.emitter = newEmitter;
  31758. if (this.particleTexture) {
  31759. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  31760. }
  31761. if (!this.preventAutoStart) {
  31762. result.start();
  31763. }
  31764. return result;
  31765. };
  31766. ParticleSystem.prototype.serialize = function () {
  31767. var serializationObject = {};
  31768. serializationObject.name = this.name;
  31769. serializationObject.id = this.id;
  31770. // Emitter
  31771. if (this.emitter.position) {
  31772. serializationObject.emitterId = this.emitter.id;
  31773. }
  31774. else {
  31775. serializationObject.emitter = this.emitter.asArray();
  31776. }
  31777. serializationObject.capacity = this.getCapacity();
  31778. if (this.particleTexture) {
  31779. serializationObject.textureName = this.particleTexture.name;
  31780. }
  31781. // Animations
  31782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31783. // Particle system
  31784. serializationObject.minAngularSpeed = this.minAngularSpeed;
  31785. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  31786. serializationObject.minSize = this.minSize;
  31787. serializationObject.maxSize = this.maxSize;
  31788. serializationObject.minEmitPower = this.minEmitPower;
  31789. serializationObject.maxEmitPower = this.maxEmitPower;
  31790. serializationObject.minLifeTime = this.minLifeTime;
  31791. serializationObject.maxLifeTime = this.maxLifeTime;
  31792. serializationObject.emitRate = this.emitRate;
  31793. serializationObject.minEmitBox = this.minEmitBox.asArray();
  31794. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  31795. serializationObject.gravity = this.gravity.asArray();
  31796. serializationObject.direction1 = this.direction1.asArray();
  31797. serializationObject.direction2 = this.direction2.asArray();
  31798. serializationObject.color1 = this.color1.asArray();
  31799. serializationObject.color2 = this.color2.asArray();
  31800. serializationObject.colorDead = this.colorDead.asArray();
  31801. serializationObject.updateSpeed = this.updateSpeed;
  31802. serializationObject.targetStopDuration = this.targetStopDuration;
  31803. serializationObject.textureMask = this.textureMask.asArray();
  31804. serializationObject.blendMode = this.blendMode;
  31805. serializationObject.customShader = this.customShader;
  31806. serializationObject.preventAutoStart = this.preventAutoStart;
  31807. return serializationObject;
  31808. };
  31809. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  31810. var name = parsedParticleSystem.name;
  31811. var custom = null;
  31812. var program = null;
  31813. if (parsedParticleSystem.customShader) {
  31814. program = parsedParticleSystem.customShader;
  31815. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31816. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31817. }
  31818. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  31819. particleSystem.customShader = program;
  31820. if (parsedParticleSystem.id) {
  31821. particleSystem.id = parsedParticleSystem.id;
  31822. }
  31823. // Auto start
  31824. if (parsedParticleSystem.preventAutoStart) {
  31825. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  31826. }
  31827. // Texture
  31828. if (parsedParticleSystem.textureName) {
  31829. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  31830. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  31831. }
  31832. // Emitter
  31833. if (parsedParticleSystem.emitterId) {
  31834. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  31835. }
  31836. else {
  31837. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  31838. }
  31839. // Animations
  31840. if (parsedParticleSystem.animations) {
  31841. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  31842. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  31843. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31844. }
  31845. }
  31846. if (parsedParticleSystem.autoAnimate) {
  31847. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  31848. }
  31849. // Particle system
  31850. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  31851. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  31852. particleSystem.minSize = parsedParticleSystem.minSize;
  31853. particleSystem.maxSize = parsedParticleSystem.maxSize;
  31854. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  31855. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  31856. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  31857. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  31858. particleSystem.emitRate = parsedParticleSystem.emitRate;
  31859. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  31860. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  31861. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  31862. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  31863. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  31864. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  31865. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  31866. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  31867. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  31868. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  31869. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  31870. particleSystem.blendMode = parsedParticleSystem.blendMode;
  31871. if (!particleSystem.preventAutoStart) {
  31872. particleSystem.start();
  31873. }
  31874. return particleSystem;
  31875. };
  31876. return ParticleSystem;
  31877. }());
  31878. // Statics
  31879. ParticleSystem.BLENDMODE_ONEONE = 0;
  31880. ParticleSystem.BLENDMODE_STANDARD = 1;
  31881. BABYLON.ParticleSystem = ParticleSystem;
  31882. })(BABYLON || (BABYLON = {}));
  31883. //# sourceMappingURL=babylon.particleSystem.js.map
  31884. var BABYLON;
  31885. (function (BABYLON) {
  31886. var AnimationRange = (function () {
  31887. function AnimationRange(name, from, to) {
  31888. this.name = name;
  31889. this.from = from;
  31890. this.to = to;
  31891. }
  31892. AnimationRange.prototype.clone = function () {
  31893. return new AnimationRange(this.name, this.from, this.to);
  31894. };
  31895. return AnimationRange;
  31896. }());
  31897. BABYLON.AnimationRange = AnimationRange;
  31898. /**
  31899. * Composed of a frame, and an action function
  31900. */
  31901. var AnimationEvent = (function () {
  31902. function AnimationEvent(frame, action, onlyOnce) {
  31903. this.frame = frame;
  31904. this.action = action;
  31905. this.onlyOnce = onlyOnce;
  31906. this.isDone = false;
  31907. }
  31908. return AnimationEvent;
  31909. }());
  31910. BABYLON.AnimationEvent = AnimationEvent;
  31911. var PathCursor = (function () {
  31912. function PathCursor(path) {
  31913. this.path = path;
  31914. this._onchange = new Array();
  31915. this.value = 0;
  31916. this.animations = new Array();
  31917. }
  31918. PathCursor.prototype.getPoint = function () {
  31919. var point = this.path.getPointAtLengthPosition(this.value);
  31920. return new BABYLON.Vector3(point.x, 0, point.y);
  31921. };
  31922. PathCursor.prototype.moveAhead = function (step) {
  31923. if (step === void 0) { step = 0.002; }
  31924. this.move(step);
  31925. return this;
  31926. };
  31927. PathCursor.prototype.moveBack = function (step) {
  31928. if (step === void 0) { step = 0.002; }
  31929. this.move(-step);
  31930. return this;
  31931. };
  31932. PathCursor.prototype.move = function (step) {
  31933. if (Math.abs(step) > 1) {
  31934. throw "step size should be less than 1.";
  31935. }
  31936. this.value += step;
  31937. this.ensureLimits();
  31938. this.raiseOnChange();
  31939. return this;
  31940. };
  31941. PathCursor.prototype.ensureLimits = function () {
  31942. while (this.value > 1) {
  31943. this.value -= 1;
  31944. }
  31945. while (this.value < 0) {
  31946. this.value += 1;
  31947. }
  31948. return this;
  31949. };
  31950. // used by animation engine
  31951. PathCursor.prototype.markAsDirty = function (propertyName) {
  31952. this.ensureLimits();
  31953. this.raiseOnChange();
  31954. return this;
  31955. };
  31956. PathCursor.prototype.raiseOnChange = function () {
  31957. var _this = this;
  31958. this._onchange.forEach(function (f) { return f(_this); });
  31959. return this;
  31960. };
  31961. PathCursor.prototype.onchange = function (f) {
  31962. this._onchange.push(f);
  31963. return this;
  31964. };
  31965. return PathCursor;
  31966. }());
  31967. BABYLON.PathCursor = PathCursor;
  31968. var Animation = (function () {
  31969. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  31970. this.name = name;
  31971. this.targetProperty = targetProperty;
  31972. this.framePerSecond = framePerSecond;
  31973. this.dataType = dataType;
  31974. this.loopMode = loopMode;
  31975. this.enableBlending = enableBlending;
  31976. this._offsetsCache = {};
  31977. this._highLimitsCache = {};
  31978. this._stopped = false;
  31979. this._blendingFactor = 0;
  31980. // The set of event that will be linked to this animation
  31981. this._events = new Array();
  31982. this.allowMatricesInterpolation = false;
  31983. this.blendingSpeed = 0.01;
  31984. this._ranges = {};
  31985. this.targetPropertyPath = targetProperty.split(".");
  31986. this.dataType = dataType;
  31987. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  31988. }
  31989. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  31990. var dataType = undefined;
  31991. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  31992. dataType = Animation.ANIMATIONTYPE_FLOAT;
  31993. }
  31994. else if (from instanceof BABYLON.Quaternion) {
  31995. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  31996. }
  31997. else if (from instanceof BABYLON.Vector3) {
  31998. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  31999. }
  32000. else if (from instanceof BABYLON.Vector2) {
  32001. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32002. }
  32003. else if (from instanceof BABYLON.Color3) {
  32004. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32005. }
  32006. else if (from instanceof BABYLON.Size) {
  32007. dataType = Animation.ANIMATIONTYPE_SIZE;
  32008. }
  32009. if (dataType == undefined) {
  32010. return null;
  32011. }
  32012. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32013. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32014. animation.setKeys(keys);
  32015. if (easingFunction !== undefined) {
  32016. animation.setEasingFunction(easingFunction);
  32017. }
  32018. return animation;
  32019. };
  32020. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32021. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32022. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32023. };
  32024. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32025. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32026. node.animations.push(animation);
  32027. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32028. };
  32029. // Methods
  32030. /**
  32031. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32032. */
  32033. Animation.prototype.toString = function (fullDetails) {
  32034. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32035. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32036. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32037. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32038. if (fullDetails) {
  32039. ret += ", Ranges: {";
  32040. var first = true;
  32041. for (var name in this._ranges) {
  32042. if (first) {
  32043. ret += ", ";
  32044. first = false;
  32045. }
  32046. ret += name;
  32047. }
  32048. ret += "}";
  32049. }
  32050. return ret;
  32051. };
  32052. /**
  32053. * Add an event to this animation.
  32054. */
  32055. Animation.prototype.addEvent = function (event) {
  32056. this._events.push(event);
  32057. };
  32058. /**
  32059. * Remove all events found at the given frame
  32060. * @param frame
  32061. */
  32062. Animation.prototype.removeEvents = function (frame) {
  32063. for (var index = 0; index < this._events.length; index++) {
  32064. if (this._events[index].frame === frame) {
  32065. this._events.splice(index, 1);
  32066. index--;
  32067. }
  32068. }
  32069. };
  32070. Animation.prototype.createRange = function (name, from, to) {
  32071. // check name not already in use; could happen for bones after serialized
  32072. if (!this._ranges[name]) {
  32073. this._ranges[name] = new AnimationRange(name, from, to);
  32074. }
  32075. };
  32076. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32077. if (deleteFrames === void 0) { deleteFrames = true; }
  32078. if (this._ranges[name]) {
  32079. if (deleteFrames) {
  32080. var from = this._ranges[name].from;
  32081. var to = this._ranges[name].to;
  32082. // this loop MUST go high to low for multiple splices to work
  32083. for (var key = this._keys.length - 1; key >= 0; key--) {
  32084. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32085. this._keys.splice(key, 1);
  32086. }
  32087. }
  32088. }
  32089. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32090. }
  32091. };
  32092. Animation.prototype.getRange = function (name) {
  32093. return this._ranges[name];
  32094. };
  32095. Animation.prototype.reset = function () {
  32096. this._offsetsCache = {};
  32097. this._highLimitsCache = {};
  32098. this.currentFrame = 0;
  32099. this._blendingFactor = 0;
  32100. this._originalBlendValue = null;
  32101. };
  32102. Animation.prototype.isStopped = function () {
  32103. return this._stopped;
  32104. };
  32105. Animation.prototype.getKeys = function () {
  32106. return this._keys;
  32107. };
  32108. Animation.prototype.getHighestFrame = function () {
  32109. var ret = 0;
  32110. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32111. if (ret < this._keys[key].frame) {
  32112. ret = this._keys[key].frame;
  32113. }
  32114. }
  32115. return ret;
  32116. };
  32117. Animation.prototype.getEasingFunction = function () {
  32118. return this._easingFunction;
  32119. };
  32120. Animation.prototype.setEasingFunction = function (easingFunction) {
  32121. this._easingFunction = easingFunction;
  32122. };
  32123. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32124. return startValue + (endValue - startValue) * gradient;
  32125. };
  32126. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32127. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32128. };
  32129. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32130. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32131. };
  32132. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32133. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32134. };
  32135. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32136. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32137. };
  32138. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32139. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32140. };
  32141. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32142. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32143. };
  32144. Animation.prototype.clone = function () {
  32145. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32146. clone.enableBlending = this.enableBlending;
  32147. clone.blendingSpeed = this.blendingSpeed;
  32148. if (this._keys) {
  32149. clone.setKeys(this._keys);
  32150. }
  32151. if (this._ranges) {
  32152. clone._ranges = {};
  32153. for (var name in this._ranges) {
  32154. clone._ranges[name] = this._ranges[name].clone();
  32155. }
  32156. }
  32157. return clone;
  32158. };
  32159. Animation.prototype.setKeys = function (values) {
  32160. this._keys = values.slice(0);
  32161. this._offsetsCache = {};
  32162. this._highLimitsCache = {};
  32163. };
  32164. Animation.prototype._getKeyValue = function (value) {
  32165. if (typeof value === "function") {
  32166. return value();
  32167. }
  32168. return value;
  32169. };
  32170. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32171. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32172. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32173. }
  32174. this.currentFrame = currentFrame;
  32175. // Try to get a hash to find the right key
  32176. 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));
  32177. if (this._keys[startKey].frame >= currentFrame) {
  32178. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32179. startKey--;
  32180. }
  32181. }
  32182. for (var key = startKey; key < this._keys.length; key++) {
  32183. if (this._keys[key + 1].frame >= currentFrame) {
  32184. var startValue = this._getKeyValue(this._keys[key].value);
  32185. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32186. // gradient : percent of currentFrame between the frame inf and the frame sup
  32187. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32188. // check for easingFunction and correction of gradient
  32189. if (this._easingFunction != null) {
  32190. gradient = this._easingFunction.ease(gradient);
  32191. }
  32192. switch (this.dataType) {
  32193. // Float
  32194. case Animation.ANIMATIONTYPE_FLOAT:
  32195. switch (loopMode) {
  32196. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32197. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32198. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32199. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32200. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32201. }
  32202. break;
  32203. // Quaternion
  32204. case Animation.ANIMATIONTYPE_QUATERNION:
  32205. var quaternion = null;
  32206. switch (loopMode) {
  32207. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32208. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32209. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32210. break;
  32211. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32212. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32213. break;
  32214. }
  32215. return quaternion;
  32216. // Vector3
  32217. case Animation.ANIMATIONTYPE_VECTOR3:
  32218. switch (loopMode) {
  32219. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32220. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32221. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32222. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32223. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32224. }
  32225. // Vector2
  32226. case Animation.ANIMATIONTYPE_VECTOR2:
  32227. switch (loopMode) {
  32228. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32229. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32230. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32231. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32232. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32233. }
  32234. // Size
  32235. case Animation.ANIMATIONTYPE_SIZE:
  32236. switch (loopMode) {
  32237. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32238. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32239. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32240. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32241. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32242. }
  32243. // Color3
  32244. case Animation.ANIMATIONTYPE_COLOR3:
  32245. switch (loopMode) {
  32246. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32247. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32248. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32249. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32250. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32251. }
  32252. // Matrix
  32253. case Animation.ANIMATIONTYPE_MATRIX:
  32254. switch (loopMode) {
  32255. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32256. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32257. if (this.allowMatricesInterpolation) {
  32258. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32259. }
  32260. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32261. return startValue;
  32262. }
  32263. default:
  32264. break;
  32265. }
  32266. break;
  32267. }
  32268. }
  32269. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32270. };
  32271. Animation.prototype.setValue = function (currentValue, blend) {
  32272. if (blend === void 0) { blend = false; }
  32273. // Set value
  32274. var path;
  32275. var destination;
  32276. if (this.targetPropertyPath.length > 1) {
  32277. var property = this._target[this.targetPropertyPath[0]];
  32278. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32279. property = property[this.targetPropertyPath[index]];
  32280. }
  32281. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32282. destination = property;
  32283. }
  32284. else {
  32285. path = this.targetPropertyPath[0];
  32286. destination = this._target;
  32287. }
  32288. // Blending
  32289. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32290. if (!this._originalBlendValue) {
  32291. if (destination[path].clone) {
  32292. this._originalBlendValue = destination[path].clone();
  32293. }
  32294. else {
  32295. this._originalBlendValue = destination[path];
  32296. }
  32297. }
  32298. if (this._originalBlendValue.prototype) {
  32299. if (this._originalBlendValue.prototype.Lerp) {
  32300. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32301. }
  32302. else {
  32303. destination[path] = currentValue;
  32304. }
  32305. }
  32306. else if (this._originalBlendValue.m) {
  32307. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32308. }
  32309. else {
  32310. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32311. }
  32312. this._blendingFactor += this.blendingSpeed;
  32313. }
  32314. else {
  32315. destination[path] = currentValue;
  32316. }
  32317. if (this._target.markAsDirty) {
  32318. this._target.markAsDirty(this.targetProperty);
  32319. }
  32320. };
  32321. Animation.prototype.goToFrame = function (frame) {
  32322. if (frame < this._keys[0].frame) {
  32323. frame = this._keys[0].frame;
  32324. }
  32325. else if (frame > this._keys[this._keys.length - 1].frame) {
  32326. frame = this._keys[this._keys.length - 1].frame;
  32327. }
  32328. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32329. this.setValue(currentValue);
  32330. };
  32331. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32332. if (blend === void 0) { blend = false; }
  32333. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32334. this._stopped = true;
  32335. return false;
  32336. }
  32337. var returnValue = true;
  32338. // Adding a start key at frame 0 if missing
  32339. if (this._keys[0].frame !== 0) {
  32340. var newKey = { frame: 0, value: this._keys[0].value };
  32341. this._keys.splice(0, 0, newKey);
  32342. }
  32343. // Check limits
  32344. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32345. from = this._keys[0].frame;
  32346. }
  32347. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32348. to = this._keys[this._keys.length - 1].frame;
  32349. }
  32350. //to and from cannot be the same key
  32351. if (from === to) {
  32352. from++;
  32353. }
  32354. // Compute ratio
  32355. var range = to - from;
  32356. var offsetValue;
  32357. // ratio represents the frame delta between from and to
  32358. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32359. var highLimitValue = 0;
  32360. if (ratio > range && !loop) {
  32361. returnValue = false;
  32362. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32363. }
  32364. else {
  32365. // Get max value if required
  32366. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32367. var keyOffset = to.toString() + from.toString();
  32368. if (!this._offsetsCache[keyOffset]) {
  32369. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32370. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32371. switch (this.dataType) {
  32372. // Float
  32373. case Animation.ANIMATIONTYPE_FLOAT:
  32374. this._offsetsCache[keyOffset] = toValue - fromValue;
  32375. break;
  32376. // Quaternion
  32377. case Animation.ANIMATIONTYPE_QUATERNION:
  32378. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32379. break;
  32380. // Vector3
  32381. case Animation.ANIMATIONTYPE_VECTOR3:
  32382. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32383. // Vector2
  32384. case Animation.ANIMATIONTYPE_VECTOR2:
  32385. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32386. // Size
  32387. case Animation.ANIMATIONTYPE_SIZE:
  32388. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32389. // Color3
  32390. case Animation.ANIMATIONTYPE_COLOR3:
  32391. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32392. default:
  32393. break;
  32394. }
  32395. this._highLimitsCache[keyOffset] = toValue;
  32396. }
  32397. highLimitValue = this._highLimitsCache[keyOffset];
  32398. offsetValue = this._offsetsCache[keyOffset];
  32399. }
  32400. }
  32401. if (offsetValue === undefined) {
  32402. switch (this.dataType) {
  32403. // Float
  32404. case Animation.ANIMATIONTYPE_FLOAT:
  32405. offsetValue = 0;
  32406. break;
  32407. // Quaternion
  32408. case Animation.ANIMATIONTYPE_QUATERNION:
  32409. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32410. break;
  32411. // Vector3
  32412. case Animation.ANIMATIONTYPE_VECTOR3:
  32413. offsetValue = BABYLON.Vector3.Zero();
  32414. break;
  32415. // Vector2
  32416. case Animation.ANIMATIONTYPE_VECTOR2:
  32417. offsetValue = BABYLON.Vector2.Zero();
  32418. break;
  32419. // Size
  32420. case Animation.ANIMATIONTYPE_SIZE:
  32421. offsetValue = BABYLON.Size.Zero();
  32422. break;
  32423. // Color3
  32424. case Animation.ANIMATIONTYPE_COLOR3:
  32425. offsetValue = BABYLON.Color3.Black();
  32426. }
  32427. }
  32428. // Compute value
  32429. var repeatCount = (ratio / range) >> 0;
  32430. var currentFrame = returnValue ? from + ratio % range : to;
  32431. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32432. // Set value
  32433. this.setValue(currentValue);
  32434. // Check events
  32435. for (var index = 0; index < this._events.length; index++) {
  32436. if (currentFrame >= this._events[index].frame) {
  32437. var event = this._events[index];
  32438. if (!event.isDone) {
  32439. // If event should be done only once, remove it.
  32440. if (event.onlyOnce) {
  32441. this._events.splice(index, 1);
  32442. index--;
  32443. }
  32444. event.isDone = true;
  32445. event.action();
  32446. } // Don't do anything if the event has already be done.
  32447. }
  32448. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32449. // reset event, the animation is looping
  32450. this._events[index].isDone = false;
  32451. }
  32452. }
  32453. if (!returnValue) {
  32454. this._stopped = true;
  32455. }
  32456. return returnValue;
  32457. };
  32458. Animation.prototype.serialize = function () {
  32459. var serializationObject = {};
  32460. serializationObject.name = this.name;
  32461. serializationObject.property = this.targetProperty;
  32462. serializationObject.framePerSecond = this.framePerSecond;
  32463. serializationObject.dataType = this.dataType;
  32464. serializationObject.loopBehavior = this.loopMode;
  32465. serializationObject.enableBlending = this.enableBlending;
  32466. serializationObject.blendingSpeed = this.blendingSpeed;
  32467. var dataType = this.dataType;
  32468. serializationObject.keys = [];
  32469. var keys = this.getKeys();
  32470. for (var index = 0; index < keys.length; index++) {
  32471. var animationKey = keys[index];
  32472. var key = {};
  32473. key.frame = animationKey.frame;
  32474. switch (dataType) {
  32475. case Animation.ANIMATIONTYPE_FLOAT:
  32476. key.values = [animationKey.value];
  32477. break;
  32478. case Animation.ANIMATIONTYPE_QUATERNION:
  32479. case Animation.ANIMATIONTYPE_MATRIX:
  32480. case Animation.ANIMATIONTYPE_VECTOR3:
  32481. case Animation.ANIMATIONTYPE_COLOR3:
  32482. key.values = animationKey.value.asArray();
  32483. break;
  32484. }
  32485. serializationObject.keys.push(key);
  32486. }
  32487. serializationObject.ranges = [];
  32488. for (var name in this._ranges) {
  32489. var range = {};
  32490. range.name = name;
  32491. range.from = this._ranges[name].from;
  32492. range.to = this._ranges[name].to;
  32493. serializationObject.ranges.push(range);
  32494. }
  32495. return serializationObject;
  32496. };
  32497. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32498. get: function () {
  32499. return Animation._ANIMATIONTYPE_FLOAT;
  32500. },
  32501. enumerable: true,
  32502. configurable: true
  32503. });
  32504. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32505. get: function () {
  32506. return Animation._ANIMATIONTYPE_VECTOR3;
  32507. },
  32508. enumerable: true,
  32509. configurable: true
  32510. });
  32511. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32512. get: function () {
  32513. return Animation._ANIMATIONTYPE_VECTOR2;
  32514. },
  32515. enumerable: true,
  32516. configurable: true
  32517. });
  32518. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32519. get: function () {
  32520. return Animation._ANIMATIONTYPE_SIZE;
  32521. },
  32522. enumerable: true,
  32523. configurable: true
  32524. });
  32525. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32526. get: function () {
  32527. return Animation._ANIMATIONTYPE_QUATERNION;
  32528. },
  32529. enumerable: true,
  32530. configurable: true
  32531. });
  32532. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32533. get: function () {
  32534. return Animation._ANIMATIONTYPE_MATRIX;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32540. get: function () {
  32541. return Animation._ANIMATIONTYPE_COLOR3;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32547. get: function () {
  32548. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32554. get: function () {
  32555. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32556. },
  32557. enumerable: true,
  32558. configurable: true
  32559. });
  32560. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32561. get: function () {
  32562. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32563. },
  32564. enumerable: true,
  32565. configurable: true
  32566. });
  32567. Animation.Parse = function (parsedAnimation) {
  32568. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32569. var dataType = parsedAnimation.dataType;
  32570. var keys = [];
  32571. var data;
  32572. var index;
  32573. if (parsedAnimation.enableBlending) {
  32574. animation.enableBlending = parsedAnimation.enableBlending;
  32575. }
  32576. if (parsedAnimation.blendingSpeed) {
  32577. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32578. }
  32579. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32580. var key = parsedAnimation.keys[index];
  32581. switch (dataType) {
  32582. case Animation.ANIMATIONTYPE_FLOAT:
  32583. data = key.values[0];
  32584. break;
  32585. case Animation.ANIMATIONTYPE_QUATERNION:
  32586. data = BABYLON.Quaternion.FromArray(key.values);
  32587. break;
  32588. case Animation.ANIMATIONTYPE_MATRIX:
  32589. data = BABYLON.Matrix.FromArray(key.values);
  32590. break;
  32591. case Animation.ANIMATIONTYPE_COLOR3:
  32592. data = BABYLON.Color3.FromArray(key.values);
  32593. break;
  32594. case Animation.ANIMATIONTYPE_VECTOR3:
  32595. default:
  32596. data = BABYLON.Vector3.FromArray(key.values);
  32597. break;
  32598. }
  32599. keys.push({
  32600. frame: key.frame,
  32601. value: data
  32602. });
  32603. }
  32604. animation.setKeys(keys);
  32605. if (parsedAnimation.ranges) {
  32606. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32607. data = parsedAnimation.ranges[index];
  32608. animation.createRange(data.name, data.from, data.to);
  32609. }
  32610. }
  32611. return animation;
  32612. };
  32613. Animation.AppendSerializedAnimations = function (source, destination) {
  32614. if (source.animations) {
  32615. destination.animations = [];
  32616. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32617. var animation = source.animations[animationIndex];
  32618. destination.animations.push(animation.serialize());
  32619. }
  32620. }
  32621. };
  32622. return Animation;
  32623. }());
  32624. // Statics
  32625. Animation._ANIMATIONTYPE_FLOAT = 0;
  32626. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32627. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32628. Animation._ANIMATIONTYPE_MATRIX = 3;
  32629. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32630. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32631. Animation._ANIMATIONTYPE_SIZE = 6;
  32632. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32633. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32634. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32635. BABYLON.Animation = Animation;
  32636. })(BABYLON || (BABYLON = {}));
  32637. //# sourceMappingURL=babylon.animation.js.map
  32638. var BABYLON;
  32639. (function (BABYLON) {
  32640. var Animatable = (function () {
  32641. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32642. if (fromFrame === void 0) { fromFrame = 0; }
  32643. if (toFrame === void 0) { toFrame = 100; }
  32644. if (loopAnimation === void 0) { loopAnimation = false; }
  32645. if (speedRatio === void 0) { speedRatio = 1.0; }
  32646. this.target = target;
  32647. this.fromFrame = fromFrame;
  32648. this.toFrame = toFrame;
  32649. this.loopAnimation = loopAnimation;
  32650. this.speedRatio = speedRatio;
  32651. this.onAnimationEnd = onAnimationEnd;
  32652. this._animations = new Array();
  32653. this._paused = false;
  32654. this.animationStarted = false;
  32655. if (animations) {
  32656. this.appendAnimations(target, animations);
  32657. }
  32658. this._scene = scene;
  32659. scene._activeAnimatables.push(this);
  32660. }
  32661. // Methods
  32662. Animatable.prototype.getAnimations = function () {
  32663. return this._animations;
  32664. };
  32665. Animatable.prototype.appendAnimations = function (target, animations) {
  32666. for (var index = 0; index < animations.length; index++) {
  32667. var animation = animations[index];
  32668. animation._target = target;
  32669. this._animations.push(animation);
  32670. }
  32671. };
  32672. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32673. var animations = this._animations;
  32674. for (var index = 0; index < animations.length; index++) {
  32675. if (animations[index].targetProperty === property) {
  32676. return animations[index];
  32677. }
  32678. }
  32679. return null;
  32680. };
  32681. Animatable.prototype.reset = function () {
  32682. var animations = this._animations;
  32683. for (var index = 0; index < animations.length; index++) {
  32684. animations[index].reset();
  32685. }
  32686. this._localDelayOffset = null;
  32687. this._pausedDelay = null;
  32688. };
  32689. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32690. var animations = this._animations;
  32691. for (var index = 0; index < animations.length; index++) {
  32692. animations[index].enableBlending = true;
  32693. animations[index].blendingSpeed = blendingSpeed;
  32694. }
  32695. };
  32696. Animatable.prototype.disableBlending = function () {
  32697. var animations = this._animations;
  32698. for (var index = 0; index < animations.length; index++) {
  32699. animations[index].enableBlending = false;
  32700. }
  32701. };
  32702. Animatable.prototype.goToFrame = function (frame) {
  32703. var animations = this._animations;
  32704. if (animations[0]) {
  32705. var fps = animations[0].framePerSecond;
  32706. var currentFrame = animations[0].currentFrame;
  32707. var adjustTime = frame - currentFrame;
  32708. var delay = adjustTime * 1000 / fps;
  32709. this._localDelayOffset -= delay;
  32710. }
  32711. for (var index = 0; index < animations.length; index++) {
  32712. animations[index].goToFrame(frame);
  32713. }
  32714. };
  32715. Animatable.prototype.pause = function () {
  32716. if (this._paused) {
  32717. return;
  32718. }
  32719. this._paused = true;
  32720. };
  32721. Animatable.prototype.restart = function () {
  32722. this._paused = false;
  32723. };
  32724. Animatable.prototype.stop = function (animationName) {
  32725. if (animationName) {
  32726. var idx = this._scene._activeAnimatables.indexOf(this);
  32727. if (idx > -1) {
  32728. var animations = this._animations;
  32729. for (var index = animations.length - 1; index >= 0; index--) {
  32730. if (typeof animationName === "string" && animations[index].name != animationName) {
  32731. continue;
  32732. }
  32733. animations[index].reset();
  32734. animations.splice(index, 1);
  32735. }
  32736. if (animations.length == 0) {
  32737. this._scene._activeAnimatables.splice(idx, 1);
  32738. if (this.onAnimationEnd) {
  32739. this.onAnimationEnd();
  32740. }
  32741. }
  32742. }
  32743. }
  32744. else {
  32745. var index = this._scene._activeAnimatables.indexOf(this);
  32746. if (index > -1) {
  32747. this._scene._activeAnimatables.splice(index, 1);
  32748. var animations = this._animations;
  32749. for (var index = 0; index < animations.length; index++) {
  32750. animations[index].reset();
  32751. }
  32752. if (this.onAnimationEnd) {
  32753. this.onAnimationEnd();
  32754. }
  32755. }
  32756. }
  32757. };
  32758. Animatable.prototype._animate = function (delay) {
  32759. if (this._paused) {
  32760. this.animationStarted = false;
  32761. if (!this._pausedDelay) {
  32762. this._pausedDelay = delay;
  32763. }
  32764. return true;
  32765. }
  32766. if (!this._localDelayOffset) {
  32767. this._localDelayOffset = delay;
  32768. }
  32769. else if (this._pausedDelay) {
  32770. this._localDelayOffset += delay - this._pausedDelay;
  32771. this._pausedDelay = null;
  32772. }
  32773. // Animating
  32774. var running = false;
  32775. var animations = this._animations;
  32776. var index;
  32777. for (index = 0; index < animations.length; index++) {
  32778. var animation = animations[index];
  32779. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  32780. running = running || isRunning;
  32781. }
  32782. this.animationStarted = running;
  32783. if (!running) {
  32784. // Remove from active animatables
  32785. index = this._scene._activeAnimatables.indexOf(this);
  32786. this._scene._activeAnimatables.splice(index, 1);
  32787. }
  32788. if (!running && this.onAnimationEnd) {
  32789. this.onAnimationEnd();
  32790. this.onAnimationEnd = null;
  32791. }
  32792. return running;
  32793. };
  32794. return Animatable;
  32795. }());
  32796. BABYLON.Animatable = Animatable;
  32797. })(BABYLON || (BABYLON = {}));
  32798. //# sourceMappingURL=babylon.animatable.js.map
  32799. var BABYLON;
  32800. (function (BABYLON) {
  32801. var EasingFunction = (function () {
  32802. function EasingFunction() {
  32803. // Properties
  32804. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  32805. }
  32806. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  32807. get: function () {
  32808. return EasingFunction._EASINGMODE_EASEIN;
  32809. },
  32810. enumerable: true,
  32811. configurable: true
  32812. });
  32813. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  32814. get: function () {
  32815. return EasingFunction._EASINGMODE_EASEOUT;
  32816. },
  32817. enumerable: true,
  32818. configurable: true
  32819. });
  32820. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  32821. get: function () {
  32822. return EasingFunction._EASINGMODE_EASEINOUT;
  32823. },
  32824. enumerable: true,
  32825. configurable: true
  32826. });
  32827. EasingFunction.prototype.setEasingMode = function (easingMode) {
  32828. var n = Math.min(Math.max(easingMode, 0), 2);
  32829. this._easingMode = n;
  32830. };
  32831. EasingFunction.prototype.getEasingMode = function () {
  32832. return this._easingMode;
  32833. };
  32834. EasingFunction.prototype.easeInCore = function (gradient) {
  32835. throw new Error('You must implement this method');
  32836. };
  32837. EasingFunction.prototype.ease = function (gradient) {
  32838. switch (this._easingMode) {
  32839. case EasingFunction.EASINGMODE_EASEIN:
  32840. return this.easeInCore(gradient);
  32841. case EasingFunction.EASINGMODE_EASEOUT:
  32842. return (1 - this.easeInCore(1 - gradient));
  32843. }
  32844. if (gradient >= 0.5) {
  32845. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  32846. }
  32847. return (this.easeInCore(gradient * 2) * 0.5);
  32848. };
  32849. return EasingFunction;
  32850. }());
  32851. //Statics
  32852. EasingFunction._EASINGMODE_EASEIN = 0;
  32853. EasingFunction._EASINGMODE_EASEOUT = 1;
  32854. EasingFunction._EASINGMODE_EASEINOUT = 2;
  32855. BABYLON.EasingFunction = EasingFunction;
  32856. var CircleEase = (function (_super) {
  32857. __extends(CircleEase, _super);
  32858. function CircleEase() {
  32859. return _super.apply(this, arguments) || this;
  32860. }
  32861. CircleEase.prototype.easeInCore = function (gradient) {
  32862. gradient = Math.max(0, Math.min(1, gradient));
  32863. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  32864. };
  32865. return CircleEase;
  32866. }(EasingFunction));
  32867. BABYLON.CircleEase = CircleEase;
  32868. var BackEase = (function (_super) {
  32869. __extends(BackEase, _super);
  32870. function BackEase(amplitude) {
  32871. if (amplitude === void 0) { amplitude = 1; }
  32872. var _this = _super.call(this) || this;
  32873. _this.amplitude = amplitude;
  32874. return _this;
  32875. }
  32876. BackEase.prototype.easeInCore = function (gradient) {
  32877. var num = Math.max(0, this.amplitude);
  32878. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  32879. };
  32880. return BackEase;
  32881. }(EasingFunction));
  32882. BABYLON.BackEase = BackEase;
  32883. var BounceEase = (function (_super) {
  32884. __extends(BounceEase, _super);
  32885. function BounceEase(bounces, bounciness) {
  32886. if (bounces === void 0) { bounces = 3; }
  32887. if (bounciness === void 0) { bounciness = 2; }
  32888. var _this = _super.call(this) || this;
  32889. _this.bounces = bounces;
  32890. _this.bounciness = bounciness;
  32891. return _this;
  32892. }
  32893. BounceEase.prototype.easeInCore = function (gradient) {
  32894. var y = Math.max(0.0, this.bounces);
  32895. var bounciness = this.bounciness;
  32896. if (bounciness <= 1.0) {
  32897. bounciness = 1.001;
  32898. }
  32899. var num9 = Math.pow(bounciness, y);
  32900. var num5 = 1.0 - bounciness;
  32901. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  32902. var num15 = gradient * num4;
  32903. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  32904. var num3 = Math.floor(num65);
  32905. var num13 = num3 + 1.0;
  32906. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  32907. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  32908. var num7 = (num8 + num12) * 0.5;
  32909. var num6 = gradient - num7;
  32910. var num2 = num7 - num8;
  32911. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  32912. };
  32913. return BounceEase;
  32914. }(EasingFunction));
  32915. BABYLON.BounceEase = BounceEase;
  32916. var CubicEase = (function (_super) {
  32917. __extends(CubicEase, _super);
  32918. function CubicEase() {
  32919. return _super.apply(this, arguments) || this;
  32920. }
  32921. CubicEase.prototype.easeInCore = function (gradient) {
  32922. return (gradient * gradient * gradient);
  32923. };
  32924. return CubicEase;
  32925. }(EasingFunction));
  32926. BABYLON.CubicEase = CubicEase;
  32927. var ElasticEase = (function (_super) {
  32928. __extends(ElasticEase, _super);
  32929. function ElasticEase(oscillations, springiness) {
  32930. if (oscillations === void 0) { oscillations = 3; }
  32931. if (springiness === void 0) { springiness = 3; }
  32932. var _this = _super.call(this) || this;
  32933. _this.oscillations = oscillations;
  32934. _this.springiness = springiness;
  32935. return _this;
  32936. }
  32937. ElasticEase.prototype.easeInCore = function (gradient) {
  32938. var num2;
  32939. var num3 = Math.max(0.0, this.oscillations);
  32940. var num = Math.max(0.0, this.springiness);
  32941. if (num == 0) {
  32942. num2 = gradient;
  32943. }
  32944. else {
  32945. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  32946. }
  32947. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  32948. };
  32949. return ElasticEase;
  32950. }(EasingFunction));
  32951. BABYLON.ElasticEase = ElasticEase;
  32952. var ExponentialEase = (function (_super) {
  32953. __extends(ExponentialEase, _super);
  32954. function ExponentialEase(exponent) {
  32955. if (exponent === void 0) { exponent = 2; }
  32956. var _this = _super.call(this) || this;
  32957. _this.exponent = exponent;
  32958. return _this;
  32959. }
  32960. ExponentialEase.prototype.easeInCore = function (gradient) {
  32961. if (this.exponent <= 0) {
  32962. return gradient;
  32963. }
  32964. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  32965. };
  32966. return ExponentialEase;
  32967. }(EasingFunction));
  32968. BABYLON.ExponentialEase = ExponentialEase;
  32969. var PowerEase = (function (_super) {
  32970. __extends(PowerEase, _super);
  32971. function PowerEase(power) {
  32972. if (power === void 0) { power = 2; }
  32973. var _this = _super.call(this) || this;
  32974. _this.power = power;
  32975. return _this;
  32976. }
  32977. PowerEase.prototype.easeInCore = function (gradient) {
  32978. var y = Math.max(0.0, this.power);
  32979. return Math.pow(gradient, y);
  32980. };
  32981. return PowerEase;
  32982. }(EasingFunction));
  32983. BABYLON.PowerEase = PowerEase;
  32984. var QuadraticEase = (function (_super) {
  32985. __extends(QuadraticEase, _super);
  32986. function QuadraticEase() {
  32987. return _super.apply(this, arguments) || this;
  32988. }
  32989. QuadraticEase.prototype.easeInCore = function (gradient) {
  32990. return (gradient * gradient);
  32991. };
  32992. return QuadraticEase;
  32993. }(EasingFunction));
  32994. BABYLON.QuadraticEase = QuadraticEase;
  32995. var QuarticEase = (function (_super) {
  32996. __extends(QuarticEase, _super);
  32997. function QuarticEase() {
  32998. return _super.apply(this, arguments) || this;
  32999. }
  33000. QuarticEase.prototype.easeInCore = function (gradient) {
  33001. return (gradient * gradient * gradient * gradient);
  33002. };
  33003. return QuarticEase;
  33004. }(EasingFunction));
  33005. BABYLON.QuarticEase = QuarticEase;
  33006. var QuinticEase = (function (_super) {
  33007. __extends(QuinticEase, _super);
  33008. function QuinticEase() {
  33009. return _super.apply(this, arguments) || this;
  33010. }
  33011. QuinticEase.prototype.easeInCore = function (gradient) {
  33012. return (gradient * gradient * gradient * gradient * gradient);
  33013. };
  33014. return QuinticEase;
  33015. }(EasingFunction));
  33016. BABYLON.QuinticEase = QuinticEase;
  33017. var SineEase = (function (_super) {
  33018. __extends(SineEase, _super);
  33019. function SineEase() {
  33020. return _super.apply(this, arguments) || this;
  33021. }
  33022. SineEase.prototype.easeInCore = function (gradient) {
  33023. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33024. };
  33025. return SineEase;
  33026. }(EasingFunction));
  33027. BABYLON.SineEase = SineEase;
  33028. var BezierCurveEase = (function (_super) {
  33029. __extends(BezierCurveEase, _super);
  33030. function BezierCurveEase(x1, y1, x2, y2) {
  33031. if (x1 === void 0) { x1 = 0; }
  33032. if (y1 === void 0) { y1 = 0; }
  33033. if (x2 === void 0) { x2 = 1; }
  33034. if (y2 === void 0) { y2 = 1; }
  33035. var _this = _super.call(this) || this;
  33036. _this.x1 = x1;
  33037. _this.y1 = y1;
  33038. _this.x2 = x2;
  33039. _this.y2 = y2;
  33040. return _this;
  33041. }
  33042. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33043. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33044. };
  33045. return BezierCurveEase;
  33046. }(EasingFunction));
  33047. BABYLON.BezierCurveEase = BezierCurveEase;
  33048. })(BABYLON || (BABYLON = {}));
  33049. //# sourceMappingURL=babylon.easing.js.map
  33050. /// <reference path="..\babylon.node.ts" />
  33051. var BABYLON;
  33052. (function (BABYLON) {
  33053. var Bone = (function (_super) {
  33054. __extends(Bone, _super);
  33055. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33056. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33057. _this.name = name;
  33058. _this.children = new Array();
  33059. _this.animations = new Array();
  33060. _this._worldTransform = new BABYLON.Matrix();
  33061. _this._absoluteTransform = new BABYLON.Matrix();
  33062. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33063. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33064. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33065. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33066. _this._scalingDeterminant = 1;
  33067. _this._skeleton = skeleton;
  33068. _this._localMatrix = matrix;
  33069. _this._baseMatrix = matrix.clone();
  33070. _this._restPose = restPose ? restPose : matrix.clone();
  33071. skeleton.bones.push(_this);
  33072. if (parentBone) {
  33073. _this._parent = parentBone;
  33074. parentBone.children.push(_this);
  33075. }
  33076. else {
  33077. _this._parent = null;
  33078. }
  33079. _this._updateDifferenceMatrix();
  33080. if (_this.getAbsoluteTransform().determinant() < 0) {
  33081. _this._scalingDeterminant *= -1;
  33082. }
  33083. return _this;
  33084. }
  33085. Object.defineProperty(Bone.prototype, "_matrix", {
  33086. get: function () {
  33087. return this._localMatrix;
  33088. },
  33089. set: function (val) {
  33090. if (this._localMatrix) {
  33091. this._localMatrix.copyFrom(val);
  33092. }
  33093. else {
  33094. this._localMatrix = val;
  33095. }
  33096. },
  33097. enumerable: true,
  33098. configurable: true
  33099. });
  33100. // Members
  33101. Bone.prototype.getParent = function () {
  33102. return this._parent;
  33103. };
  33104. Bone.prototype.getLocalMatrix = function () {
  33105. return this._localMatrix;
  33106. };
  33107. Bone.prototype.getBaseMatrix = function () {
  33108. return this._baseMatrix;
  33109. };
  33110. Bone.prototype.getRestPose = function () {
  33111. return this._restPose;
  33112. };
  33113. Bone.prototype.returnToRest = function () {
  33114. this.updateMatrix(this._restPose.clone());
  33115. };
  33116. Bone.prototype.getWorldMatrix = function () {
  33117. return this._worldTransform;
  33118. };
  33119. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33120. return this._invertedAbsoluteTransform;
  33121. };
  33122. Bone.prototype.getAbsoluteTransform = function () {
  33123. return this._absoluteTransform;
  33124. };
  33125. // Methods
  33126. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33127. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33128. this._baseMatrix = matrix.clone();
  33129. this._localMatrix = matrix.clone();
  33130. this._skeleton._markAsDirty();
  33131. if (updateDifferenceMatrix) {
  33132. this._updateDifferenceMatrix();
  33133. }
  33134. };
  33135. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33136. if (!rootMatrix) {
  33137. rootMatrix = this._baseMatrix;
  33138. }
  33139. if (this._parent) {
  33140. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33141. }
  33142. else {
  33143. this._absoluteTransform.copyFrom(rootMatrix);
  33144. }
  33145. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33146. for (var index = 0; index < this.children.length; index++) {
  33147. this.children[index]._updateDifferenceMatrix();
  33148. }
  33149. };
  33150. Bone.prototype.markAsDirty = function () {
  33151. this._currentRenderId++;
  33152. this._skeleton._markAsDirty();
  33153. };
  33154. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33155. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33156. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33157. // all animation may be coming from a library skeleton, so may need to create animation
  33158. if (this.animations.length === 0) {
  33159. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33160. this.animations[0].setKeys([]);
  33161. }
  33162. // get animation info / verify there is such a range from the source bone
  33163. var sourceRange = source.animations[0].getRange(rangeName);
  33164. if (!sourceRange) {
  33165. return false;
  33166. }
  33167. var from = sourceRange.from;
  33168. var to = sourceRange.to;
  33169. var sourceKeys = source.animations[0].getKeys();
  33170. // rescaling prep
  33171. var sourceBoneLength = source.length;
  33172. var sourceParent = source.getParent();
  33173. var parent = this.getParent();
  33174. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33175. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33176. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33177. var destKeys = this.animations[0].getKeys();
  33178. // loop vars declaration
  33179. var orig;
  33180. var origTranslation;
  33181. var mat;
  33182. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33183. orig = sourceKeys[key];
  33184. if (orig.frame >= from && orig.frame <= to) {
  33185. if (rescaleAsRequired) {
  33186. mat = orig.value.clone();
  33187. // scale based on parent ratio, when bone has parent
  33188. if (parentScalingReqd) {
  33189. origTranslation = mat.getTranslation();
  33190. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33191. }
  33192. else if (dimensionsScalingReqd) {
  33193. origTranslation = mat.getTranslation();
  33194. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33195. }
  33196. else {
  33197. mat = orig.value;
  33198. }
  33199. }
  33200. else {
  33201. mat = orig.value;
  33202. }
  33203. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33204. }
  33205. }
  33206. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33207. return true;
  33208. };
  33209. /**
  33210. * Translate the bone in local or world space.
  33211. * @param vec The amount to translate the bone.
  33212. * @param space The space that the translation is in.
  33213. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33214. */
  33215. Bone.prototype.translate = function (vec, space, mesh) {
  33216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33217. var lm = this.getLocalMatrix();
  33218. if (space == BABYLON.Space.LOCAL) {
  33219. lm.m[12] += vec.x;
  33220. lm.m[13] += vec.y;
  33221. lm.m[14] += vec.z;
  33222. }
  33223. else {
  33224. this._skeleton.computeAbsoluteTransforms();
  33225. var tmat = BABYLON.Tmp.Matrix[0];
  33226. var tvec = BABYLON.Tmp.Vector3[0];
  33227. if (mesh) {
  33228. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33229. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33230. }
  33231. else {
  33232. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33233. }
  33234. tmat.m[12] = 0;
  33235. tmat.m[13] = 0;
  33236. tmat.m[14] = 0;
  33237. tmat.invert();
  33238. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33239. lm.m[12] += tvec.x;
  33240. lm.m[13] += tvec.y;
  33241. lm.m[14] += tvec.z;
  33242. }
  33243. this.markAsDirty();
  33244. };
  33245. /**
  33246. * Set the postion of the bone in local or world space.
  33247. * @param position The position to set the bone.
  33248. * @param space The space that the position is in.
  33249. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33250. */
  33251. Bone.prototype.setPosition = function (position, space, mesh) {
  33252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33253. var lm = this.getLocalMatrix();
  33254. if (space == BABYLON.Space.LOCAL) {
  33255. lm.m[12] = position.x;
  33256. lm.m[13] = position.y;
  33257. lm.m[14] = position.z;
  33258. }
  33259. else {
  33260. this._skeleton.computeAbsoluteTransforms();
  33261. var tmat = BABYLON.Tmp.Matrix[0];
  33262. var vec = BABYLON.Tmp.Vector3[0];
  33263. if (mesh) {
  33264. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33265. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33266. }
  33267. else {
  33268. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33269. }
  33270. tmat.invert();
  33271. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  33272. lm.m[12] = vec.x;
  33273. lm.m[13] = vec.y;
  33274. lm.m[14] = vec.z;
  33275. }
  33276. this.markAsDirty();
  33277. };
  33278. /**
  33279. * Set the absolute postion of the bone (world space).
  33280. * @param position The position to set the bone.
  33281. * @param mesh The mesh that this bone is attached to.
  33282. */
  33283. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  33284. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  33285. };
  33286. /**
  33287. * Set the scale of the bone on the x, y and z axes.
  33288. * @param x The scale of the bone on the x axis.
  33289. * @param x The scale of the bone on the y axis.
  33290. * @param z The scale of the bone on the z axis.
  33291. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33292. */
  33293. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  33294. if (scaleChildren === void 0) { scaleChildren = false; }
  33295. if (this.animations[0] && !this.animations[0].isStopped()) {
  33296. if (!scaleChildren) {
  33297. this._negateScaleChildren.x = 1 / x;
  33298. this._negateScaleChildren.y = 1 / y;
  33299. this._negateScaleChildren.z = 1 / z;
  33300. }
  33301. this._syncScaleVector();
  33302. }
  33303. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  33304. };
  33305. /**
  33306. * Scale the bone on the x, y and z axes.
  33307. * @param x The amount to scale the bone on the x axis.
  33308. * @param x The amount to scale the bone on the y axis.
  33309. * @param z The amount to scale the bone on the z axis.
  33310. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33311. */
  33312. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  33313. if (scaleChildren === void 0) { scaleChildren = false; }
  33314. var locMat = this.getLocalMatrix();
  33315. var origLocMat = BABYLON.Tmp.Matrix[0];
  33316. origLocMat.copyFrom(locMat);
  33317. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  33318. origLocMatInv.copyFrom(origLocMat);
  33319. origLocMatInv.invert();
  33320. var scaleMat = BABYLON.Tmp.Matrix[2];
  33321. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  33322. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  33323. this._scaleVector.x *= x;
  33324. this._scaleVector.y *= y;
  33325. this._scaleVector.z *= z;
  33326. locMat.multiplyToRef(origLocMatInv, locMat);
  33327. locMat.multiplyToRef(scaleMat, locMat);
  33328. locMat.multiplyToRef(origLocMat, locMat);
  33329. var parent = this.getParent();
  33330. if (parent) {
  33331. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  33332. }
  33333. else {
  33334. this.getAbsoluteTransform().copyFrom(locMat);
  33335. }
  33336. var len = this.children.length;
  33337. scaleMat.invert();
  33338. for (var i = 0; i < len; i++) {
  33339. var child = this.children[i];
  33340. var cm = child.getLocalMatrix();
  33341. cm.multiplyToRef(scaleMat, cm);
  33342. var lm = child.getLocalMatrix();
  33343. lm.m[12] *= x;
  33344. lm.m[13] *= y;
  33345. lm.m[14] *= z;
  33346. }
  33347. this.computeAbsoluteTransforms();
  33348. if (scaleChildren) {
  33349. for (var i = 0; i < len; i++) {
  33350. this.children[i].scale(x, y, z, scaleChildren);
  33351. }
  33352. }
  33353. this.markAsDirty();
  33354. };
  33355. /**
  33356. * Set the yaw, pitch, and roll of the bone in local or world space.
  33357. * @param yaw The rotation of the bone on the y axis.
  33358. * @param pitch The rotation of the bone on the x axis.
  33359. * @param roll The rotation of the bone on the z axis.
  33360. * @param space The space that the axes of rotation are in.
  33361. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33362. */
  33363. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  33364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33365. var rotMat = BABYLON.Tmp.Matrix[0];
  33366. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  33367. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33368. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33369. rotMatInv.multiplyToRef(rotMat, rotMat);
  33370. this._rotateWithMatrix(rotMat, space, mesh);
  33371. };
  33372. /**
  33373. * Rotate the bone on an axis in local or world space.
  33374. * @param axis The axis to rotate the bone on.
  33375. * @param amount The amount to rotate the bone.
  33376. * @param space The space that the axis is in.
  33377. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33378. */
  33379. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  33380. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33381. var rmat = BABYLON.Tmp.Matrix[0];
  33382. rmat.m[12] = 0;
  33383. rmat.m[13] = 0;
  33384. rmat.m[14] = 0;
  33385. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  33386. this._rotateWithMatrix(rmat, space, mesh);
  33387. };
  33388. /**
  33389. * Set the rotation of the bone to a particular axis angle in local or world space.
  33390. * @param axis The axis to rotate the bone on.
  33391. * @param angle The angle that the bone should be rotated to.
  33392. * @param space The space that the axis is in.
  33393. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33394. */
  33395. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  33396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33397. var rotMat = BABYLON.Tmp.Matrix[0];
  33398. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  33399. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33400. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33401. rotMatInv.multiplyToRef(rotMat, rotMat);
  33402. this._rotateWithMatrix(rotMat, space, mesh);
  33403. };
  33404. /**
  33405. * Set the euler rotation of the bone in local of world space.
  33406. * @param rotation The euler rotation that the bone should be set to.
  33407. * @param space The space that the rotation is in.
  33408. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33409. */
  33410. Bone.prototype.setRotation = function (rotation, space, mesh) {
  33411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33412. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  33413. };
  33414. /**
  33415. * Set the quaternion rotation of the bone in local of world space.
  33416. * @param quat The quaternion rotation that the bone should be set to.
  33417. * @param space The space that the rotation is in.
  33418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33419. */
  33420. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  33421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33422. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33423. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33424. var rotMat = BABYLON.Tmp.Matrix[1];
  33425. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  33426. rotMatInv.multiplyToRef(rotMat, rotMat);
  33427. this._rotateWithMatrix(rotMat, space, mesh);
  33428. };
  33429. /**
  33430. * Set the rotation matrix of the bone in local of world space.
  33431. * @param rotMat The rotation matrix that the bone should be set to.
  33432. * @param space The space that the rotation is in.
  33433. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33434. */
  33435. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  33436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33437. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33438. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33439. var rotMat2 = BABYLON.Tmp.Matrix[1];
  33440. rotMat2.copyFrom(rotMat);
  33441. rotMatInv.multiplyToRef(rotMat, rotMat2);
  33442. this._rotateWithMatrix(rotMat2, space, mesh);
  33443. };
  33444. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  33445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33446. var lmat = this.getLocalMatrix();
  33447. var lx = lmat.m[12];
  33448. var ly = lmat.m[13];
  33449. var lz = lmat.m[14];
  33450. var parent = this.getParent();
  33451. var parentScale = BABYLON.Tmp.Matrix[3];
  33452. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  33453. if (parent) {
  33454. if (space == BABYLON.Space.WORLD) {
  33455. if (mesh) {
  33456. parentScale.copyFrom(mesh.getWorldMatrix());
  33457. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  33458. }
  33459. else {
  33460. parentScale.copyFrom(parent.getAbsoluteTransform());
  33461. }
  33462. }
  33463. else {
  33464. parentScale = parent._scaleMatrix;
  33465. }
  33466. parentScaleInv.copyFrom(parentScale);
  33467. parentScaleInv.invert();
  33468. lmat.multiplyToRef(parentScale, lmat);
  33469. lmat.multiplyToRef(rmat, lmat);
  33470. lmat.multiplyToRef(parentScaleInv, lmat);
  33471. }
  33472. else {
  33473. if (space == BABYLON.Space.WORLD && mesh) {
  33474. parentScale.copyFrom(mesh.getWorldMatrix());
  33475. parentScaleInv.copyFrom(parentScale);
  33476. parentScaleInv.invert();
  33477. lmat.multiplyToRef(parentScale, lmat);
  33478. lmat.multiplyToRef(rmat, lmat);
  33479. lmat.multiplyToRef(parentScaleInv, lmat);
  33480. }
  33481. else {
  33482. lmat.multiplyToRef(rmat, lmat);
  33483. }
  33484. }
  33485. lmat.m[12] = lx;
  33486. lmat.m[13] = ly;
  33487. lmat.m[14] = lz;
  33488. this.computeAbsoluteTransforms();
  33489. this.markAsDirty();
  33490. };
  33491. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  33492. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33493. if (space == BABYLON.Space.WORLD) {
  33494. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33495. scaleMatrix.copyFrom(this._scaleMatrix);
  33496. rotMatInv.copyFrom(this.getAbsoluteTransform());
  33497. if (mesh) {
  33498. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  33499. var meshScale = BABYLON.Tmp.Matrix[3];
  33500. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  33501. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  33502. }
  33503. rotMatInv.invert();
  33504. scaleMatrix.m[0] *= this._scalingDeterminant;
  33505. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33506. }
  33507. else {
  33508. rotMatInv.copyFrom(this.getLocalMatrix());
  33509. rotMatInv.invert();
  33510. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33511. scaleMatrix.copyFrom(this._scaleMatrix);
  33512. if (this._parent) {
  33513. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  33514. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  33515. pscaleMatrix.invert();
  33516. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  33517. }
  33518. else {
  33519. scaleMatrix.m[0] *= this._scalingDeterminant;
  33520. }
  33521. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33522. }
  33523. };
  33524. /**
  33525. * Get the scale of the bone
  33526. * @returns the scale of the bone
  33527. */
  33528. Bone.prototype.getScale = function () {
  33529. return this._scaleVector.clone();
  33530. };
  33531. /**
  33532. * Copy the scale of the bone to a vector3.
  33533. * @param result The vector3 to copy the scale to
  33534. */
  33535. Bone.prototype.getScaleToRef = function (result) {
  33536. result.copyFrom(this._scaleVector);
  33537. };
  33538. /**
  33539. * Get the position of the bone in local or world space.
  33540. * @param space The space that the returned position is in.
  33541. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33542. * @returns The position of the bone
  33543. */
  33544. Bone.prototype.getPosition = function (space, mesh) {
  33545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33546. var pos = BABYLON.Vector3.Zero();
  33547. this.getPositionToRef(space, mesh, pos);
  33548. return pos;
  33549. };
  33550. /**
  33551. * Copy the position of the bone to a vector3 in local or world space.
  33552. * @param space The space that the returned position is in.
  33553. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33554. * @param result The vector3 to copy the position to.
  33555. */
  33556. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  33557. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33558. if (space == BABYLON.Space.LOCAL) {
  33559. var lm = this.getLocalMatrix();
  33560. result.x = lm.m[12];
  33561. result.y = lm.m[13];
  33562. result.z = lm.m[14];
  33563. }
  33564. else {
  33565. this._skeleton.computeAbsoluteTransforms();
  33566. var tmat = BABYLON.Tmp.Matrix[0];
  33567. if (mesh) {
  33568. tmat.copyFrom(this.getAbsoluteTransform());
  33569. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33570. }
  33571. else {
  33572. tmat = this.getAbsoluteTransform();
  33573. }
  33574. result.x = tmat.m[12];
  33575. result.y = tmat.m[13];
  33576. result.z = tmat.m[14];
  33577. }
  33578. };
  33579. /**
  33580. * Get the absolute position of the bone (world space).
  33581. * @param mesh The mesh that this bone is attached to.
  33582. * @returns The absolute position of the bone
  33583. */
  33584. Bone.prototype.getAbsolutePosition = function (mesh) {
  33585. var pos = BABYLON.Vector3.Zero();
  33586. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  33587. return pos;
  33588. };
  33589. /**
  33590. * Copy the absolute position of the bone (world space) to the result param.
  33591. * @param mesh The mesh that this bone is attached to.
  33592. * @param result The vector3 to copy the absolute position to.
  33593. */
  33594. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  33595. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  33596. };
  33597. /**
  33598. * Compute the absolute transforms of this bone and its children.
  33599. */
  33600. Bone.prototype.computeAbsoluteTransforms = function () {
  33601. if (this._parent) {
  33602. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33603. }
  33604. else {
  33605. this._absoluteTransform.copyFrom(this._localMatrix);
  33606. var poseMatrix = this._skeleton.getPoseMatrix();
  33607. if (poseMatrix) {
  33608. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  33609. }
  33610. }
  33611. var children = this.children;
  33612. var len = children.length;
  33613. for (var i = 0; i < len; i++) {
  33614. children[i].computeAbsoluteTransforms();
  33615. }
  33616. };
  33617. Bone.prototype._syncScaleVector = function () {
  33618. var lm = this.getLocalMatrix();
  33619. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  33620. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  33621. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  33622. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  33623. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  33624. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  33625. this._scaleVector.x = xs * Math.sqrt(xsq);
  33626. this._scaleVector.y = ys * Math.sqrt(ysq);
  33627. this._scaleVector.z = zs * Math.sqrt(zsq);
  33628. if (this._parent) {
  33629. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  33630. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  33631. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  33632. }
  33633. 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);
  33634. };
  33635. /**
  33636. * Get the world direction from an axis that is in the local space of the bone.
  33637. * @param localAxis The local direction that is used to compute the world direction.
  33638. * @param mesh The mesh that this bone is attached to.
  33639. * @returns The world direction
  33640. */
  33641. Bone.prototype.getDirection = function (localAxis, mesh) {
  33642. var result = BABYLON.Vector3.Zero();
  33643. this.getDirectionToRef(localAxis, mesh, result);
  33644. return result;
  33645. };
  33646. /**
  33647. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  33648. * @param localAxis The local direction that is used to compute the world direction.
  33649. * @param mesh The mesh that this bone is attached to.
  33650. * @param result The vector3 that the world direction will be copied to.
  33651. */
  33652. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  33653. this._skeleton.computeAbsoluteTransforms();
  33654. var mat = BABYLON.Tmp.Matrix[0];
  33655. mat.copyFrom(this.getAbsoluteTransform());
  33656. if (mesh) {
  33657. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33658. }
  33659. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  33660. result.normalize();
  33661. };
  33662. /**
  33663. * Get the euler rotation of the bone in local or world space.
  33664. * @param space The space that the rotation should be in.
  33665. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33666. * @returns The euler rotation
  33667. */
  33668. Bone.prototype.getRotation = function (space, mesh) {
  33669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33670. var result = BABYLON.Vector3.Zero();
  33671. this.getRotationToRef(space, mesh, result);
  33672. return result;
  33673. };
  33674. /**
  33675. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  33676. * @param space The space that the rotation should be in.
  33677. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33678. * @param result The vector3 that the rotation should be copied to.
  33679. */
  33680. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  33681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33682. var quat = BABYLON.Tmp.Quaternion[0];
  33683. this.getRotationQuaternionToRef(space, mesh, quat);
  33684. quat.toEulerAnglesToRef(result);
  33685. };
  33686. /**
  33687. * Get the quaternion rotation of the bone in either local or world space.
  33688. * @param space The space that the rotation should be in.
  33689. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33690. * @returns The quaternion rotation
  33691. */
  33692. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  33693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33694. var result = BABYLON.Quaternion.Identity();
  33695. this.getRotationQuaternionToRef(space, mesh, result);
  33696. return result;
  33697. };
  33698. /**
  33699. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  33700. * @param space The space that the rotation should be in.
  33701. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33702. * @param result The quaternion that the rotation should be copied to.
  33703. */
  33704. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  33705. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33706. if (space == BABYLON.Space.LOCAL) {
  33707. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33708. }
  33709. else {
  33710. var mat = BABYLON.Tmp.Matrix[0];
  33711. var amat = this.getAbsoluteTransform();
  33712. if (mesh) {
  33713. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33714. }
  33715. else {
  33716. mat.copyFrom(amat);
  33717. }
  33718. mat.m[0] *= this._scalingDeterminant;
  33719. mat.m[1] *= this._scalingDeterminant;
  33720. mat.m[2] *= this._scalingDeterminant;
  33721. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33722. }
  33723. };
  33724. /**
  33725. * Get the rotation matrix of the bone in local or world space.
  33726. * @param space The space that the rotation should be in.
  33727. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33728. * @returns The rotation matrix
  33729. */
  33730. Bone.prototype.getRotationMatrix = function (space, mesh) {
  33731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33732. var result = BABYLON.Matrix.Identity();
  33733. this.getRotationMatrixToRef(space, mesh, result);
  33734. return result;
  33735. };
  33736. /**
  33737. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  33738. * @param space The space that the rotation should be in.
  33739. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33740. * @param result The quaternion that the rotation should be copied to.
  33741. */
  33742. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  33743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33744. if (space == BABYLON.Space.LOCAL) {
  33745. this.getLocalMatrix().getRotationMatrixToRef(result);
  33746. }
  33747. else {
  33748. var mat = BABYLON.Tmp.Matrix[0];
  33749. var amat = this.getAbsoluteTransform();
  33750. if (mesh) {
  33751. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33752. }
  33753. else {
  33754. mat.copyFrom(amat);
  33755. }
  33756. mat.m[0] *= this._scalingDeterminant;
  33757. mat.m[1] *= this._scalingDeterminant;
  33758. mat.m[2] *= this._scalingDeterminant;
  33759. mat.getRotationMatrixToRef(result);
  33760. }
  33761. };
  33762. /**
  33763. * Get the world position of a point that is in the local space of the bone.
  33764. * @param position The local position
  33765. * @param mesh The mesh that this bone is attached to.
  33766. * @returns The world position
  33767. */
  33768. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  33769. var result = BABYLON.Vector3.Zero();
  33770. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  33771. return result;
  33772. };
  33773. /**
  33774. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  33775. * @param position The local position
  33776. * @param mesh The mesh that this bone is attached to.
  33777. * @param result The vector3 that the world position should be copied to.
  33778. */
  33779. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  33780. this._skeleton.computeAbsoluteTransforms();
  33781. var tmat = BABYLON.Tmp.Matrix[0];
  33782. if (mesh) {
  33783. tmat.copyFrom(this.getAbsoluteTransform());
  33784. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33785. }
  33786. else {
  33787. tmat = this.getAbsoluteTransform();
  33788. }
  33789. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33790. };
  33791. /**
  33792. * Get the local position of a point that is in world space.
  33793. * @param position The world position
  33794. * @param mesh The mesh that this bone is attached to.
  33795. * @returns The local position
  33796. */
  33797. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  33798. var result = BABYLON.Vector3.Zero();
  33799. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  33800. return result;
  33801. };
  33802. /**
  33803. * Get the local position of a point that is in world space and copy it to the result param.
  33804. * @param position The world position
  33805. * @param mesh The mesh that this bone is attached to.
  33806. * @param result The vector3 that the local position should be copied to.
  33807. */
  33808. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  33809. this._skeleton.computeAbsoluteTransforms();
  33810. var tmat = BABYLON.Tmp.Matrix[0];
  33811. tmat.copyFrom(this.getAbsoluteTransform());
  33812. if (mesh) {
  33813. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33814. }
  33815. tmat.invert();
  33816. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33817. };
  33818. return Bone;
  33819. }(BABYLON.Node));
  33820. BABYLON.Bone = Bone;
  33821. })(BABYLON || (BABYLON = {}));
  33822. //# sourceMappingURL=babylon.bone.js.map
  33823. var BABYLON;
  33824. (function (BABYLON) {
  33825. var BoneIKController = (function () {
  33826. function BoneIKController(mesh, bone, options) {
  33827. this.targetPosition = BABYLON.Vector3.Zero();
  33828. this.poleTargetPosition = BABYLON.Vector3.Zero();
  33829. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  33830. this.poleAngle = 0;
  33831. this.slerpAmount = 1;
  33832. this._bone1Quat = BABYLON.Quaternion.Identity();
  33833. this._bone1Mat = BABYLON.Matrix.Identity();
  33834. this._bone2Ang = Math.PI;
  33835. this._maxAngle = Math.PI;
  33836. this._tmpVec1 = BABYLON.Vector3.Zero();
  33837. this._tmpVec2 = BABYLON.Vector3.Zero();
  33838. this._tmpVec3 = BABYLON.Vector3.Zero();
  33839. this._tmpVec4 = BABYLON.Vector3.Zero();
  33840. this._tmpVec5 = BABYLON.Vector3.Zero();
  33841. this._tmpMat1 = BABYLON.Matrix.Identity();
  33842. this._tmpMat2 = BABYLON.Matrix.Identity();
  33843. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  33844. this._rightHandedSystem = false;
  33845. this._bendAxis = BABYLON.Vector3.Right();
  33846. this._slerping = false;
  33847. this._adjustRoll = 0;
  33848. this._bone2 = bone;
  33849. this._bone1 = bone.getParent();
  33850. this.mesh = mesh;
  33851. var bonePos = bone.getPosition();
  33852. if (bone.getAbsoluteTransform().determinant() > 0) {
  33853. this._rightHandedSystem = true;
  33854. this._bendAxis.x = 0;
  33855. this._bendAxis.y = 0;
  33856. this._bendAxis.z = -1;
  33857. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  33858. this._adjustRoll = Math.PI * .5;
  33859. this._bendAxis.z = 1;
  33860. }
  33861. }
  33862. if (this._bone1.length) {
  33863. var boneScale1 = this._bone1.getScale();
  33864. var boneScale2 = this._bone2.getScale();
  33865. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  33866. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  33867. }
  33868. else if (this._bone1.children[0]) {
  33869. mesh.computeWorldMatrix(true);
  33870. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  33871. var pos2 = this._bone2.getAbsolutePosition(mesh);
  33872. var pos3 = this._bone1.getAbsolutePosition(mesh);
  33873. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  33874. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  33875. }
  33876. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  33877. this.maxAngle = Math.PI;
  33878. if (options) {
  33879. if (options.targetMesh) {
  33880. this.targetMesh = options.targetMesh;
  33881. this.targetMesh.computeWorldMatrix(true);
  33882. }
  33883. if (options.poleTargetMesh) {
  33884. this.poleTargetMesh = options.poleTargetMesh;
  33885. this.poleTargetMesh.computeWorldMatrix(true);
  33886. }
  33887. else if (options.poleTargetBone) {
  33888. this.poleTargetBone = options.poleTargetBone;
  33889. }
  33890. else if (this._bone1.getParent()) {
  33891. this.poleTargetBone = this._bone1.getParent();
  33892. }
  33893. if (options.poleTargetLocalOffset) {
  33894. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  33895. }
  33896. if (options.poleAngle) {
  33897. this.poleAngle = options.poleAngle;
  33898. }
  33899. if (options.bendAxis) {
  33900. this._bendAxis.copyFrom(options.bendAxis);
  33901. }
  33902. if (options.maxAngle) {
  33903. this.maxAngle = options.maxAngle;
  33904. }
  33905. if (options.slerpAmount) {
  33906. this.slerpAmount = options.slerpAmount;
  33907. }
  33908. }
  33909. }
  33910. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  33911. get: function () {
  33912. return this._maxAngle;
  33913. },
  33914. set: function (value) {
  33915. this._setMaxAngle(value);
  33916. },
  33917. enumerable: true,
  33918. configurable: true
  33919. });
  33920. BoneIKController.prototype._setMaxAngle = function (ang) {
  33921. if (ang < 0) {
  33922. ang = 0;
  33923. }
  33924. if (ang > Math.PI || ang == undefined) {
  33925. ang = Math.PI;
  33926. }
  33927. this._maxAngle = ang;
  33928. var a = this._bone1Length;
  33929. var b = this._bone2Length;
  33930. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  33931. };
  33932. BoneIKController.prototype.update = function () {
  33933. var bone1 = this._bone1;
  33934. var target = this.targetPosition;
  33935. var poleTarget = this.poleTargetPosition;
  33936. var mat1 = this._tmpMat1;
  33937. var mat2 = this._tmpMat2;
  33938. if (this.targetMesh) {
  33939. target.copyFrom(this.targetMesh.getAbsolutePosition());
  33940. }
  33941. if (this.poleTargetBone) {
  33942. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  33943. }
  33944. else if (this.poleTargetMesh) {
  33945. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  33946. }
  33947. var bonePos = this._tmpVec1;
  33948. var zaxis = this._tmpVec2;
  33949. var xaxis = this._tmpVec3;
  33950. var yaxis = this._tmpVec4;
  33951. var upAxis = this._tmpVec5;
  33952. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  33953. poleTarget.subtractToRef(bonePos, upAxis);
  33954. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  33955. upAxis.y = 1;
  33956. }
  33957. else {
  33958. upAxis.normalize();
  33959. }
  33960. target.subtractToRef(bonePos, yaxis);
  33961. yaxis.normalize();
  33962. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  33963. zaxis.normalize();
  33964. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  33965. xaxis.normalize();
  33966. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  33967. var a = this._bone1Length;
  33968. var b = this._bone2Length;
  33969. var c = BABYLON.Vector3.Distance(bonePos, target);
  33970. if (this._maxReach > 0) {
  33971. c = Math.min(this._maxReach, c);
  33972. }
  33973. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  33974. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  33975. if (acosa > 1) {
  33976. acosa = 1;
  33977. }
  33978. if (acosb > 1) {
  33979. acosb = 1;
  33980. }
  33981. if (acosa < -1) {
  33982. acosa = -1;
  33983. }
  33984. if (acosb < -1) {
  33985. acosb = -1;
  33986. }
  33987. var angA = Math.acos(acosa);
  33988. var angB = Math.acos(acosb);
  33989. var angC = -angA - angB;
  33990. if (this._rightHandedSystem) {
  33991. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  33992. mat2.multiplyToRef(mat1, mat1);
  33993. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  33994. mat2.multiplyToRef(mat1, mat1);
  33995. }
  33996. else {
  33997. this._tmpVec1.copyFrom(this._bendAxis);
  33998. this._tmpVec1.x *= -1;
  33999. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  34000. mat2.multiplyToRef(mat1, mat1);
  34001. }
  34002. if (this.poleAngle) {
  34003. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34004. mat1.multiplyToRef(mat2, mat1);
  34005. }
  34006. if (this.slerpAmount < 1) {
  34007. if (!this._slerping) {
  34008. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34009. }
  34010. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  34011. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  34012. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34013. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34014. this._slerping = true;
  34015. }
  34016. else {
  34017. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34018. this._bone1Mat.copyFrom(mat1);
  34019. this._slerping = false;
  34020. }
  34021. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34022. this._bone2Ang = angC;
  34023. };
  34024. return BoneIKController;
  34025. }());
  34026. BABYLON.BoneIKController = BoneIKController;
  34027. })(BABYLON || (BABYLON = {}));
  34028. //# sourceMappingURL=babylon.boneIKController.js.map
  34029. var BABYLON;
  34030. (function (BABYLON) {
  34031. var BoneLookController = (function () {
  34032. function BoneLookController(mesh, bone, target, options) {
  34033. this.upAxis = BABYLON.Vector3.Up();
  34034. this.adjustYaw = 0;
  34035. this.adjustPitch = 0;
  34036. this.adjustRoll = 0;
  34037. this._tmpVec1 = BABYLON.Vector3.Zero();
  34038. this._tmpVec2 = BABYLON.Vector3.Zero();
  34039. this._tmpVec3 = BABYLON.Vector3.Zero();
  34040. this._tmpVec4 = BABYLON.Vector3.Zero();
  34041. this._tmpMat1 = BABYLON.Matrix.Identity();
  34042. this._tmpMat2 = BABYLON.Matrix.Identity();
  34043. this.mesh = mesh;
  34044. this.bone = bone;
  34045. this.target = target;
  34046. if (options) {
  34047. if (options.adjustYaw) {
  34048. this.adjustYaw = options.adjustYaw;
  34049. }
  34050. if (options.adjustPitch) {
  34051. this.adjustPitch = options.adjustPitch;
  34052. }
  34053. if (options.adjustRoll) {
  34054. this.adjustRoll = options.adjustRoll;
  34055. }
  34056. }
  34057. }
  34058. BoneLookController.prototype.update = function () {
  34059. var bone = this.bone;
  34060. var target = this.target;
  34061. var bonePos = this._tmpVec1;
  34062. var zaxis = this._tmpVec2;
  34063. var xaxis = this._tmpVec3;
  34064. var yaxis = this._tmpVec4;
  34065. var mat1 = this._tmpMat1;
  34066. var mat2 = this._tmpMat2;
  34067. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34068. target.subtractToRef(bonePos, zaxis);
  34069. zaxis.normalize();
  34070. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  34071. xaxis.normalize();
  34072. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  34073. yaxis.normalize();
  34074. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34075. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  34076. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  34077. mat2.multiplyToRef(mat1, mat1);
  34078. }
  34079. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34080. };
  34081. return BoneLookController;
  34082. }());
  34083. BABYLON.BoneLookController = BoneLookController;
  34084. })(BABYLON || (BABYLON = {}));
  34085. //# sourceMappingURL=babylon.boneLookController.js.map
  34086. var BABYLON;
  34087. (function (BABYLON) {
  34088. var Skeleton = (function () {
  34089. function Skeleton(name, id, scene) {
  34090. this.name = name;
  34091. this.id = id;
  34092. this.bones = new Array();
  34093. this.needInitialSkinMatrix = false;
  34094. this._isDirty = true;
  34095. this._meshesWithPoseMatrix = new Array();
  34096. this._identity = BABYLON.Matrix.Identity();
  34097. this._ranges = {};
  34098. this._lastAbsoluteTransformsUpdateId = -1;
  34099. // Events
  34100. /**
  34101. * An event triggered before computing the skeleton's matrices
  34102. * @type {BABYLON.Observable}
  34103. */
  34104. this.onBeforeComputeObservable = new BABYLON.Observable();
  34105. this.bones = [];
  34106. this._scene = scene;
  34107. scene.skeletons.push(this);
  34108. //make sure it will recalculate the matrix next time prepare is called.
  34109. this._isDirty = true;
  34110. }
  34111. // Members
  34112. Skeleton.prototype.getTransformMatrices = function (mesh) {
  34113. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  34114. return mesh._bonesTransformMatrices;
  34115. }
  34116. if (!this._transformMatrices) {
  34117. this.prepare();
  34118. }
  34119. return this._transformMatrices;
  34120. };
  34121. Skeleton.prototype.getScene = function () {
  34122. return this._scene;
  34123. };
  34124. // Methods
  34125. /**
  34126. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34127. */
  34128. Skeleton.prototype.toString = function (fullDetails) {
  34129. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  34130. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34131. if (fullDetails) {
  34132. ret += ", Ranges: {";
  34133. var first = true;
  34134. for (var name_1 in this._ranges) {
  34135. if (first) {
  34136. ret += ", ";
  34137. first = false;
  34138. }
  34139. ret += name_1;
  34140. }
  34141. ret += "}";
  34142. }
  34143. return ret;
  34144. };
  34145. /**
  34146. * Get bone's index searching by name
  34147. * @param {string} name is bone's name to search for
  34148. * @return {number} Indice of the bone. Returns -1 if not found
  34149. */
  34150. Skeleton.prototype.getBoneIndexByName = function (name) {
  34151. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  34152. if (this.bones[boneIndex].name === name) {
  34153. return boneIndex;
  34154. }
  34155. }
  34156. return -1;
  34157. };
  34158. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  34159. // check name not already in use
  34160. if (!this._ranges[name]) {
  34161. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  34162. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34163. if (this.bones[i].animations[0]) {
  34164. this.bones[i].animations[0].createRange(name, from, to);
  34165. }
  34166. }
  34167. }
  34168. };
  34169. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  34170. if (deleteFrames === void 0) { deleteFrames = true; }
  34171. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34172. if (this.bones[i].animations[0]) {
  34173. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  34174. }
  34175. }
  34176. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34177. };
  34178. Skeleton.prototype.getAnimationRange = function (name) {
  34179. return this._ranges[name];
  34180. };
  34181. /**
  34182. * Returns as an Array, all AnimationRanges defined on this skeleton
  34183. */
  34184. Skeleton.prototype.getAnimationRanges = function () {
  34185. var animationRanges = [];
  34186. var name;
  34187. var i = 0;
  34188. for (name in this._ranges) {
  34189. animationRanges[i] = this._ranges[name];
  34190. i++;
  34191. }
  34192. return animationRanges;
  34193. };
  34194. /**
  34195. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  34196. */
  34197. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  34198. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  34199. if (this._ranges[name] || !source.getAnimationRange(name)) {
  34200. return false;
  34201. }
  34202. var ret = true;
  34203. var frameOffset = this._getHighestAnimationFrame() + 1;
  34204. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  34205. var boneDict = {};
  34206. var sourceBones = source.bones;
  34207. var nBones;
  34208. var i;
  34209. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  34210. boneDict[sourceBones[i].name] = sourceBones[i];
  34211. }
  34212. if (this.bones.length !== sourceBones.length) {
  34213. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  34214. ret = false;
  34215. }
  34216. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  34217. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  34218. var boneName = this.bones[i].name;
  34219. var sourceBone = boneDict[boneName];
  34220. if (sourceBone) {
  34221. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  34222. }
  34223. else {
  34224. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  34225. ret = false;
  34226. }
  34227. }
  34228. // do not call createAnimationRange(), since it also is done to bones, which was already done
  34229. var range = source.getAnimationRange(name);
  34230. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  34231. return ret;
  34232. };
  34233. Skeleton.prototype.returnToRest = function () {
  34234. for (var index = 0; index < this.bones.length; index++) {
  34235. this.bones[index].returnToRest();
  34236. }
  34237. };
  34238. Skeleton.prototype._getHighestAnimationFrame = function () {
  34239. var ret = 0;
  34240. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34241. if (this.bones[i].animations[0]) {
  34242. var highest = this.bones[i].animations[0].getHighestFrame();
  34243. if (ret < highest) {
  34244. ret = highest;
  34245. }
  34246. }
  34247. }
  34248. return ret;
  34249. };
  34250. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  34251. var range = this.getAnimationRange(name);
  34252. if (!range) {
  34253. return null;
  34254. }
  34255. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  34256. };
  34257. Skeleton.prototype._markAsDirty = function () {
  34258. this._isDirty = true;
  34259. };
  34260. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  34261. this._meshesWithPoseMatrix.push(mesh);
  34262. };
  34263. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  34264. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  34265. if (index > -1) {
  34266. this._meshesWithPoseMatrix.splice(index, 1);
  34267. }
  34268. };
  34269. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  34270. this.onBeforeComputeObservable.notifyObservers(this);
  34271. for (var index = 0; index < this.bones.length; index++) {
  34272. var bone = this.bones[index];
  34273. var parentBone = bone.getParent();
  34274. if (parentBone) {
  34275. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  34276. }
  34277. else {
  34278. if (initialSkinMatrix) {
  34279. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  34280. }
  34281. else {
  34282. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  34283. }
  34284. }
  34285. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  34286. }
  34287. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  34288. };
  34289. Skeleton.prototype.prepare = function () {
  34290. if (!this._isDirty) {
  34291. return;
  34292. }
  34293. if (this.needInitialSkinMatrix) {
  34294. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  34295. var mesh = this._meshesWithPoseMatrix[index];
  34296. var poseMatrix = mesh.getPoseMatrix();
  34297. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  34298. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34299. }
  34300. if (this._synchronizedWithMesh !== mesh) {
  34301. this._synchronizedWithMesh = mesh;
  34302. // Prepare bones
  34303. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  34304. var bone = this.bones[boneIndex];
  34305. if (!bone.getParent()) {
  34306. var matrix = bone.getBaseMatrix();
  34307. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  34308. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  34309. }
  34310. }
  34311. }
  34312. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  34313. }
  34314. }
  34315. else {
  34316. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  34317. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34318. }
  34319. this._computeTransformMatrices(this._transformMatrices, null);
  34320. }
  34321. this._isDirty = false;
  34322. this._scene._activeBones.addCount(this.bones.length, false);
  34323. };
  34324. Skeleton.prototype.getAnimatables = function () {
  34325. if (!this._animatables || this._animatables.length !== this.bones.length) {
  34326. this._animatables = [];
  34327. for (var index = 0; index < this.bones.length; index++) {
  34328. this._animatables.push(this.bones[index]);
  34329. }
  34330. }
  34331. return this._animatables;
  34332. };
  34333. Skeleton.prototype.clone = function (name, id) {
  34334. var result = new Skeleton(name, id || name, this._scene);
  34335. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34336. for (var index = 0; index < this.bones.length; index++) {
  34337. var source = this.bones[index];
  34338. var parentBone = null;
  34339. if (source.getParent()) {
  34340. var parentIndex = this.bones.indexOf(source.getParent());
  34341. parentBone = result.bones[parentIndex];
  34342. }
  34343. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  34344. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  34345. }
  34346. if (this._ranges) {
  34347. result._ranges = {};
  34348. for (var rangeName in this._ranges) {
  34349. result._ranges[rangeName] = this._ranges[rangeName].clone();
  34350. }
  34351. }
  34352. this._isDirty = true;
  34353. return result;
  34354. };
  34355. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  34356. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  34357. this.bones.forEach(function (bone) {
  34358. bone.animations.forEach(function (animation) {
  34359. animation.enableBlending = true;
  34360. animation.blendingSpeed = blendingSpeed;
  34361. });
  34362. });
  34363. };
  34364. Skeleton.prototype.dispose = function () {
  34365. this._meshesWithPoseMatrix = [];
  34366. // Animations
  34367. this.getScene().stopAnimation(this);
  34368. // Remove from scene
  34369. this.getScene().removeSkeleton(this);
  34370. };
  34371. Skeleton.prototype.serialize = function () {
  34372. var serializationObject = {};
  34373. serializationObject.name = this.name;
  34374. serializationObject.id = this.id;
  34375. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  34376. serializationObject.bones = [];
  34377. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34378. for (var index = 0; index < this.bones.length; index++) {
  34379. var bone = this.bones[index];
  34380. var serializedBone = {
  34381. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  34382. name: bone.name,
  34383. matrix: bone.getLocalMatrix().toArray(),
  34384. rest: bone.getRestPose().toArray()
  34385. };
  34386. serializationObject.bones.push(serializedBone);
  34387. if (bone.length) {
  34388. serializedBone.length = bone.length;
  34389. }
  34390. if (bone.animations && bone.animations.length > 0) {
  34391. serializedBone.animation = bone.animations[0].serialize();
  34392. }
  34393. serializationObject.ranges = [];
  34394. for (var name in this._ranges) {
  34395. var range = {};
  34396. range.name = name;
  34397. range.from = this._ranges[name].from;
  34398. range.to = this._ranges[name].to;
  34399. serializationObject.ranges.push(range);
  34400. }
  34401. }
  34402. return serializationObject;
  34403. };
  34404. Skeleton.Parse = function (parsedSkeleton, scene) {
  34405. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  34406. if (parsedSkeleton.dimensionsAtRest) {
  34407. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  34408. }
  34409. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  34410. var index;
  34411. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  34412. var parsedBone = parsedSkeleton.bones[index];
  34413. var parentBone = null;
  34414. if (parsedBone.parentBoneIndex > -1) {
  34415. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  34416. }
  34417. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  34418. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  34419. if (parsedBone.length) {
  34420. bone.length = parsedBone.length;
  34421. }
  34422. if (parsedBone.animation) {
  34423. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  34424. }
  34425. }
  34426. // placed after bones, so createAnimationRange can cascade down
  34427. if (parsedSkeleton.ranges) {
  34428. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  34429. var data = parsedSkeleton.ranges[index];
  34430. skeleton.createAnimationRange(data.name, data.from, data.to);
  34431. }
  34432. }
  34433. return skeleton;
  34434. };
  34435. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  34436. if (forceUpdate === void 0) { forceUpdate = false; }
  34437. var renderId = this._scene.getRenderId();
  34438. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  34439. this.bones[0].computeAbsoluteTransforms();
  34440. this._lastAbsoluteTransformsUpdateId = renderId;
  34441. }
  34442. };
  34443. Skeleton.prototype.getPoseMatrix = function () {
  34444. var poseMatrix;
  34445. if (this._meshesWithPoseMatrix.length > 0) {
  34446. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  34447. }
  34448. return poseMatrix;
  34449. };
  34450. return Skeleton;
  34451. }());
  34452. BABYLON.Skeleton = Skeleton;
  34453. })(BABYLON || (BABYLON = {}));
  34454. //# sourceMappingURL=babylon.skeleton.js.map
  34455. var BABYLON;
  34456. (function (BABYLON) {
  34457. var PostProcess = (function () {
  34458. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  34459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34460. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34461. this.name = name;
  34462. this.width = -1;
  34463. this.height = -1;
  34464. /*
  34465. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34466. Can only be used on a single postprocess or on the last one of a chain.
  34467. */
  34468. this.enablePixelPerfectMode = false;
  34469. this._reusable = false;
  34470. this._textures = new BABYLON.SmartArray(2);
  34471. this._currentRenderTextureInd = 0;
  34472. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34473. // Events
  34474. /**
  34475. * An event triggered when the postprocess is activated.
  34476. * @type {BABYLON.Observable}
  34477. */
  34478. this.onActivateObservable = new BABYLON.Observable();
  34479. /**
  34480. * An event triggered when the postprocess changes its size.
  34481. * @type {BABYLON.Observable}
  34482. */
  34483. this.onSizeChangedObservable = new BABYLON.Observable();
  34484. /**
  34485. * An event triggered when the postprocess applies its effect.
  34486. * @type {BABYLON.Observable}
  34487. */
  34488. this.onApplyObservable = new BABYLON.Observable();
  34489. /**
  34490. * An event triggered before rendering the postprocess
  34491. * @type {BABYLON.Observable}
  34492. */
  34493. this.onBeforeRenderObservable = new BABYLON.Observable();
  34494. /**
  34495. * An event triggered after rendering the postprocess
  34496. * @type {BABYLON.Observable}
  34497. */
  34498. this.onAfterRenderObservable = new BABYLON.Observable();
  34499. if (camera != null) {
  34500. this._camera = camera;
  34501. this._scene = camera.getScene();
  34502. camera.attachPostProcess(this);
  34503. this._engine = this._scene.getEngine();
  34504. }
  34505. else {
  34506. this._engine = engine;
  34507. }
  34508. this._options = options;
  34509. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34510. this._reusable = reusable || false;
  34511. this._textureType = textureType;
  34512. this._samplers = samplers || [];
  34513. this._samplers.push("textureSampler");
  34514. this._fragmentUrl = fragmentUrl;
  34515. this._parameters = parameters || [];
  34516. this._parameters.push("scale");
  34517. this.updateEffect(defines);
  34518. }
  34519. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34520. set: function (callback) {
  34521. if (this._onActivateObserver) {
  34522. this.onActivateObservable.remove(this._onActivateObserver);
  34523. }
  34524. this._onActivateObserver = this.onActivateObservable.add(callback);
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34530. set: function (callback) {
  34531. if (this._onSizeChangedObserver) {
  34532. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34533. }
  34534. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34535. },
  34536. enumerable: true,
  34537. configurable: true
  34538. });
  34539. Object.defineProperty(PostProcess.prototype, "onApply", {
  34540. set: function (callback) {
  34541. if (this._onApplyObserver) {
  34542. this.onApplyObservable.remove(this._onApplyObserver);
  34543. }
  34544. this._onApplyObserver = this.onApplyObservable.add(callback);
  34545. },
  34546. enumerable: true,
  34547. configurable: true
  34548. });
  34549. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34550. set: function (callback) {
  34551. if (this._onBeforeRenderObserver) {
  34552. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34553. }
  34554. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34560. set: function (callback) {
  34561. if (this._onAfterRenderObserver) {
  34562. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34563. }
  34564. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34565. },
  34566. enumerable: true,
  34567. configurable: true
  34568. });
  34569. PostProcess.prototype.updateEffect = function (defines) {
  34570. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  34571. };
  34572. PostProcess.prototype.isReusable = function () {
  34573. return this._reusable;
  34574. };
  34575. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34576. PostProcess.prototype.markTextureDirty = function () {
  34577. this.width = -1;
  34578. };
  34579. PostProcess.prototype.activate = function (camera, sourceTexture) {
  34580. camera = camera || this._camera;
  34581. var scene = camera.getScene();
  34582. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  34583. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34584. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34585. var desiredWidth = this._options.width || requiredWidth;
  34586. var desiredHeight = this._options.height || requiredHeight;
  34587. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  34588. if (!this._options.width) {
  34589. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  34590. }
  34591. if (!this._options.height) {
  34592. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  34593. }
  34594. }
  34595. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34596. if (this._textures.length > 0) {
  34597. for (var i = 0; i < this._textures.length; i++) {
  34598. this._engine._releaseTexture(this._textures.data[i]);
  34599. }
  34600. this._textures.reset();
  34601. }
  34602. this.width = desiredWidth;
  34603. this.height = desiredHeight;
  34604. var textureSize = { width: this.width, height: this.height };
  34605. var textureOptions = {
  34606. generateMipMaps: false,
  34607. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  34608. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  34609. samplingMode: this.renderTargetSamplingMode,
  34610. type: this._textureType
  34611. };
  34612. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34613. if (this._reusable) {
  34614. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34615. }
  34616. this.onSizeChangedObservable.notifyObservers(this);
  34617. }
  34618. if (this.enablePixelPerfectMode) {
  34619. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  34620. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  34621. }
  34622. else {
  34623. this._scaleRatio.copyFromFloats(1, 1);
  34624. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  34625. }
  34626. this.onActivateObservable.notifyObservers(camera);
  34627. // Clear
  34628. if (this.clearColor) {
  34629. this._engine.clear(this.clearColor, true, true, true);
  34630. }
  34631. else {
  34632. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  34633. }
  34634. if (this._reusable) {
  34635. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  34636. }
  34637. };
  34638. Object.defineProperty(PostProcess.prototype, "isSupported", {
  34639. get: function () {
  34640. return this._effect.isSupported;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. PostProcess.prototype.apply = function () {
  34646. // Check
  34647. if (!this._effect.isReady())
  34648. return null;
  34649. // States
  34650. this._engine.enableEffect(this._effect);
  34651. this._engine.setState(false);
  34652. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34653. this._engine.setDepthBuffer(false);
  34654. this._engine.setDepthWrite(false);
  34655. // Texture
  34656. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  34657. // Parameters
  34658. this._effect.setVector2("scale", this._scaleRatio);
  34659. this.onApplyObservable.notifyObservers(this._effect);
  34660. return this._effect;
  34661. };
  34662. PostProcess.prototype.dispose = function (camera) {
  34663. camera = camera || this._camera;
  34664. if (this._textures.length > 0) {
  34665. for (var i = 0; i < this._textures.length; i++) {
  34666. this._engine._releaseTexture(this._textures.data[i]);
  34667. }
  34668. this._textures.reset();
  34669. }
  34670. if (!camera) {
  34671. return;
  34672. }
  34673. camera.detachPostProcess(this);
  34674. var index = camera._postProcesses.indexOf(this);
  34675. if (index === 0 && camera._postProcesses.length > 0) {
  34676. this._camera._postProcesses[0].markTextureDirty();
  34677. }
  34678. this.onActivateObservable.clear();
  34679. this.onAfterRenderObservable.clear();
  34680. this.onApplyObservable.clear();
  34681. this.onBeforeRenderObservable.clear();
  34682. this.onSizeChangedObservable.clear();
  34683. };
  34684. return PostProcess;
  34685. }());
  34686. BABYLON.PostProcess = PostProcess;
  34687. })(BABYLON || (BABYLON = {}));
  34688. //# sourceMappingURL=babylon.postProcess.js.map
  34689. var BABYLON;
  34690. (function (BABYLON) {
  34691. var PostProcessManager = (function () {
  34692. function PostProcessManager(scene) {
  34693. this._vertexBuffers = {};
  34694. this._scene = scene;
  34695. }
  34696. PostProcessManager.prototype._prepareBuffers = function () {
  34697. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34698. return;
  34699. }
  34700. // VBO
  34701. var vertices = [];
  34702. vertices.push(1, 1);
  34703. vertices.push(-1, 1);
  34704. vertices.push(-1, -1);
  34705. vertices.push(1, -1);
  34706. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34707. // Indices
  34708. var indices = [];
  34709. indices.push(0);
  34710. indices.push(1);
  34711. indices.push(2);
  34712. indices.push(0);
  34713. indices.push(2);
  34714. indices.push(3);
  34715. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34716. };
  34717. // Methods
  34718. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  34719. var postProcesses = this._scene.activeCamera._postProcesses;
  34720. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34721. return false;
  34722. }
  34723. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  34724. return true;
  34725. };
  34726. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  34727. var engine = this._scene.getEngine();
  34728. for (var index = 0; index < postProcesses.length; index++) {
  34729. if (index < postProcesses.length - 1) {
  34730. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34731. }
  34732. else {
  34733. if (targetTexture) {
  34734. engine.bindFramebuffer(targetTexture);
  34735. }
  34736. else {
  34737. engine.restoreDefaultFramebuffer();
  34738. }
  34739. }
  34740. var pp = postProcesses[index];
  34741. var effect = pp.apply();
  34742. if (effect) {
  34743. pp.onBeforeRenderObservable.notifyObservers(effect);
  34744. // VBOs
  34745. this._prepareBuffers();
  34746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34747. // Draw order
  34748. engine.draw(true, 0, 6);
  34749. pp.onAfterRenderObservable.notifyObservers(effect);
  34750. }
  34751. }
  34752. // Restore depth buffer
  34753. engine.setDepthBuffer(true);
  34754. engine.setDepthWrite(true);
  34755. };
  34756. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  34757. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  34758. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34759. return;
  34760. }
  34761. var engine = this._scene.getEngine();
  34762. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34763. if (index < len - 1) {
  34764. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34765. }
  34766. else {
  34767. if (targetTexture) {
  34768. engine.bindFramebuffer(targetTexture, faceIndex);
  34769. }
  34770. else {
  34771. engine.restoreDefaultFramebuffer();
  34772. }
  34773. }
  34774. if (doNotPresent) {
  34775. break;
  34776. }
  34777. var pp = postProcesses[index];
  34778. var effect = pp.apply();
  34779. if (effect) {
  34780. pp.onBeforeRenderObservable.notifyObservers(effect);
  34781. // VBOs
  34782. this._prepareBuffers();
  34783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34784. // Draw order
  34785. engine.draw(true, 0, 6);
  34786. pp.onAfterRenderObservable.notifyObservers(effect);
  34787. }
  34788. }
  34789. // Restore depth buffer
  34790. engine.setDepthBuffer(true);
  34791. engine.setDepthWrite(true);
  34792. };
  34793. PostProcessManager.prototype.dispose = function () {
  34794. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34795. if (buffer) {
  34796. buffer.dispose();
  34797. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34798. }
  34799. if (this._indexBuffer) {
  34800. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34801. this._indexBuffer = null;
  34802. }
  34803. };
  34804. return PostProcessManager;
  34805. }());
  34806. BABYLON.PostProcessManager = PostProcessManager;
  34807. })(BABYLON || (BABYLON = {}));
  34808. //# sourceMappingURL=babylon.postProcessManager.js.map
  34809. var BABYLON;
  34810. (function (BABYLON) {
  34811. var PassPostProcess = (function (_super) {
  34812. __extends(PassPostProcess, _super);
  34813. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  34814. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  34815. }
  34816. return PassPostProcess;
  34817. }(BABYLON.PostProcess));
  34818. BABYLON.PassPostProcess = PassPostProcess;
  34819. })(BABYLON || (BABYLON = {}));
  34820. //# sourceMappingURL=babylon.passPostProcess.js.map
  34821. var BABYLON;
  34822. (function (BABYLON) {
  34823. /**
  34824. * This is a holder class for the physics joint created by the physics plugin.
  34825. * It holds a set of functions to control the underlying joint.
  34826. */
  34827. var PhysicsJoint = (function () {
  34828. function PhysicsJoint(type, jointData) {
  34829. this.type = type;
  34830. this.jointData = jointData;
  34831. jointData.nativeParams = jointData.nativeParams || {};
  34832. }
  34833. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  34834. get: function () {
  34835. return this._physicsJoint;
  34836. },
  34837. set: function (newJoint) {
  34838. if (this._physicsJoint) {
  34839. }
  34840. this._physicsJoint = newJoint;
  34841. },
  34842. enumerable: true,
  34843. configurable: true
  34844. });
  34845. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  34846. set: function (physicsPlugin) {
  34847. this._physicsPlugin = physicsPlugin;
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. /**
  34853. * Execute a function that is physics-plugin specific.
  34854. * @param {Function} func the function that will be executed.
  34855. * It accepts two parameters: the physics world and the physics joint.
  34856. */
  34857. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  34858. func(this._physicsPlugin.world, this._physicsJoint);
  34859. };
  34860. return PhysicsJoint;
  34861. }());
  34862. //TODO check if the native joints are the same
  34863. //Joint Types
  34864. PhysicsJoint.DistanceJoint = 0;
  34865. PhysicsJoint.HingeJoint = 1;
  34866. PhysicsJoint.BallAndSocketJoint = 2;
  34867. PhysicsJoint.WheelJoint = 3;
  34868. PhysicsJoint.SliderJoint = 4;
  34869. //OIMO
  34870. PhysicsJoint.PrismaticJoint = 5;
  34871. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  34872. PhysicsJoint.UniversalJoint = 6;
  34873. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  34874. //Cannon
  34875. //Similar to a Ball-Joint. Different in params
  34876. PhysicsJoint.PointToPointJoint = 8;
  34877. //Cannon only at the moment
  34878. PhysicsJoint.SpringJoint = 9;
  34879. PhysicsJoint.LockJoint = 10;
  34880. BABYLON.PhysicsJoint = PhysicsJoint;
  34881. /**
  34882. * A class representing a physics distance joint.
  34883. */
  34884. var DistanceJoint = (function (_super) {
  34885. __extends(DistanceJoint, _super);
  34886. function DistanceJoint(jointData) {
  34887. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  34888. }
  34889. /**
  34890. * Update the predefined distance.
  34891. */
  34892. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  34893. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  34894. };
  34895. return DistanceJoint;
  34896. }(PhysicsJoint));
  34897. BABYLON.DistanceJoint = DistanceJoint;
  34898. var MotorEnabledJoint = (function (_super) {
  34899. __extends(MotorEnabledJoint, _super);
  34900. function MotorEnabledJoint(type, jointData) {
  34901. return _super.call(this, type, jointData) || this;
  34902. }
  34903. /**
  34904. * Set the motor values.
  34905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34906. * @param {number} force the force to apply
  34907. * @param {number} maxForce max force for this motor.
  34908. */
  34909. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  34910. this._physicsPlugin.setMotor(this, force, maxForce);
  34911. };
  34912. /**
  34913. * Set the motor's limits.
  34914. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34915. */
  34916. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  34917. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  34918. };
  34919. return MotorEnabledJoint;
  34920. }(PhysicsJoint));
  34921. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  34922. /**
  34923. * This class represents a single hinge physics joint
  34924. */
  34925. var HingeJoint = (function (_super) {
  34926. __extends(HingeJoint, _super);
  34927. function HingeJoint(jointData) {
  34928. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  34929. }
  34930. /**
  34931. * Set the motor values.
  34932. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34933. * @param {number} force the force to apply
  34934. * @param {number} maxForce max force for this motor.
  34935. */
  34936. HingeJoint.prototype.setMotor = function (force, maxForce) {
  34937. this._physicsPlugin.setMotor(this, force, maxForce);
  34938. };
  34939. /**
  34940. * Set the motor's limits.
  34941. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34942. */
  34943. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  34944. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  34945. };
  34946. return HingeJoint;
  34947. }(MotorEnabledJoint));
  34948. BABYLON.HingeJoint = HingeJoint;
  34949. /**
  34950. * This class represents a dual hinge physics joint (same as wheel joint)
  34951. */
  34952. var Hinge2Joint = (function (_super) {
  34953. __extends(Hinge2Joint, _super);
  34954. function Hinge2Joint(jointData) {
  34955. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  34956. }
  34957. /**
  34958. * Set the motor values.
  34959. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34960. * @param {number} force the force to apply
  34961. * @param {number} maxForce max force for this motor.
  34962. * @param {motorIndex} the motor's index, 0 or 1.
  34963. */
  34964. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  34965. if (motorIndex === void 0) { motorIndex = 0; }
  34966. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  34967. };
  34968. /**
  34969. * Set the motor limits.
  34970. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34971. * @param {number} upperLimit the upper limit
  34972. * @param {number} lowerLimit lower limit
  34973. * @param {motorIndex} the motor's index, 0 or 1.
  34974. */
  34975. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  34976. if (motorIndex === void 0) { motorIndex = 0; }
  34977. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  34978. };
  34979. return Hinge2Joint;
  34980. }(MotorEnabledJoint));
  34981. BABYLON.Hinge2Joint = Hinge2Joint;
  34982. })(BABYLON || (BABYLON = {}));
  34983. //# sourceMappingURL=babylon.physicsJoint.js.map
  34984. var BABYLON;
  34985. (function (BABYLON) {
  34986. var PhysicsImpostor = (function () {
  34987. function PhysicsImpostor(object, type, _options, _scene) {
  34988. if (_options === void 0) { _options = { mass: 0 }; }
  34989. var _this = this;
  34990. this.object = object;
  34991. this.type = type;
  34992. this._options = _options;
  34993. this._scene = _scene;
  34994. this._bodyUpdateRequired = false;
  34995. this._onBeforePhysicsStepCallbacks = new Array();
  34996. this._onAfterPhysicsStepCallbacks = new Array();
  34997. this._onPhysicsCollideCallbacks = [];
  34998. this._deltaPosition = BABYLON.Vector3.Zero();
  34999. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  35000. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  35001. /**
  35002. * this function is executed by the physics engine.
  35003. */
  35004. this.beforeStep = function () {
  35005. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  35006. //conjugate deltaRotation
  35007. if (_this._deltaRotationConjugated) {
  35008. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  35009. }
  35010. else {
  35011. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  35012. }
  35013. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  35014. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  35015. func(_this);
  35016. });
  35017. };
  35018. /**
  35019. * this function is executed by the physics engine.
  35020. */
  35021. this.afterStep = function () {
  35022. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  35023. func(_this);
  35024. });
  35025. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  35026. _this.object.position.addInPlace(_this._deltaPosition);
  35027. if (_this._deltaRotation) {
  35028. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  35029. }
  35030. };
  35031. /**
  35032. * Legacy collision detection event support
  35033. */
  35034. this.onCollideEvent = null;
  35035. //event and body object due to cannon's event-based architecture.
  35036. this.onCollide = function (e) {
  35037. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  35038. return;
  35039. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  35040. if (otherImpostor) {
  35041. // Legacy collision detection event support
  35042. if (_this.onCollideEvent) {
  35043. _this.onCollideEvent(_this, otherImpostor);
  35044. }
  35045. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  35046. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  35047. }).forEach(function (obj) {
  35048. obj.callback(_this, otherImpostor);
  35049. });
  35050. }
  35051. };
  35052. //sanity check!
  35053. if (!this.object) {
  35054. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  35055. return;
  35056. }
  35057. //legacy support for old syntax.
  35058. if (!this._scene && object.getScene) {
  35059. this._scene = object.getScene();
  35060. }
  35061. this._physicsEngine = this._scene.getPhysicsEngine();
  35062. if (!this._physicsEngine) {
  35063. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  35064. }
  35065. else {
  35066. //set the object's quaternion, if not set
  35067. if (!this.object.rotationQuaternion) {
  35068. if (this.object.rotation) {
  35069. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  35070. }
  35071. else {
  35072. this.object.rotationQuaternion = new BABYLON.Quaternion();
  35073. }
  35074. }
  35075. //default options params
  35076. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  35077. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  35078. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  35079. this._joints = [];
  35080. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  35081. if (!this.object.parent) {
  35082. this._init();
  35083. }
  35084. }
  35085. }
  35086. /**
  35087. * This function will completly initialize this impostor.
  35088. * It will create a new body - but only if this mesh has no parent.
  35089. * If it has, this impostor will not be used other than to define the impostor
  35090. * of the child mesh.
  35091. */
  35092. PhysicsImpostor.prototype._init = function () {
  35093. this._physicsEngine.removeImpostor(this);
  35094. this.physicsBody = null;
  35095. this._parent = this._parent || this._getPhysicsParent();
  35096. if (!this.parent) {
  35097. this._physicsEngine.addImpostor(this);
  35098. }
  35099. };
  35100. PhysicsImpostor.prototype._getPhysicsParent = function () {
  35101. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  35102. var parentMesh = this.object.parent;
  35103. return parentMesh.physicsImpostor;
  35104. }
  35105. return;
  35106. };
  35107. /**
  35108. * Should a new body be generated.
  35109. */
  35110. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  35111. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  35112. };
  35113. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  35114. this.forceUpdate();
  35115. };
  35116. /**
  35117. * Force a regeneration of this or the parent's impostor's body.
  35118. * Use under cautious - This will remove all joints already implemented.
  35119. */
  35120. PhysicsImpostor.prototype.forceUpdate = function () {
  35121. this._init();
  35122. if (this.parent) {
  35123. this.parent.forceUpdate();
  35124. }
  35125. };
  35126. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  35127. /*public get mesh(): AbstractMesh {
  35128. return this._mesh;
  35129. }*/
  35130. /**
  35131. * Gets the body that holds this impostor. Either its own, or its parent.
  35132. */
  35133. get: function () {
  35134. return this._parent ? this._parent.physicsBody : this._physicsBody;
  35135. },
  35136. /**
  35137. * Set the physics body. Used mainly by the physics engine/plugin
  35138. */
  35139. set: function (physicsBody) {
  35140. if (this._physicsBody) {
  35141. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  35142. }
  35143. this._physicsBody = physicsBody;
  35144. this.resetUpdateFlags();
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  35150. get: function () {
  35151. return this._parent;
  35152. },
  35153. set: function (value) {
  35154. this._parent = value;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  35160. this._bodyUpdateRequired = false;
  35161. };
  35162. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  35163. if (this.object.getBoundingInfo) {
  35164. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  35165. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  35166. }
  35167. else {
  35168. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  35169. }
  35170. };
  35171. PhysicsImpostor.prototype.getObjectCenter = function () {
  35172. if (this.object.getBoundingInfo) {
  35173. return this.object.getBoundingInfo().boundingBox.center;
  35174. }
  35175. else {
  35176. return this.object.position;
  35177. }
  35178. };
  35179. /**
  35180. * Get a specific parametes from the options parameter.
  35181. */
  35182. PhysicsImpostor.prototype.getParam = function (paramName) {
  35183. return this._options[paramName];
  35184. };
  35185. /**
  35186. * Sets a specific parameter in the options given to the physics plugin
  35187. */
  35188. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  35189. this._options[paramName] = value;
  35190. this._bodyUpdateRequired = true;
  35191. };
  35192. /**
  35193. * Specifically change the body's mass option. Won't recreate the physics body object
  35194. */
  35195. PhysicsImpostor.prototype.setMass = function (mass) {
  35196. if (this.getParam("mass") !== mass) {
  35197. this.setParam("mass", mass);
  35198. }
  35199. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  35200. };
  35201. PhysicsImpostor.prototype.getLinearVelocity = function () {
  35202. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  35203. };
  35204. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  35205. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  35206. };
  35207. PhysicsImpostor.prototype.getAngularVelocity = function () {
  35208. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  35209. };
  35210. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  35211. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  35212. };
  35213. /**
  35214. * Execute a function with the physics plugin native code.
  35215. * Provide a function the will have two variables - the world object and the physics body object.
  35216. */
  35217. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  35218. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  35219. };
  35220. /**
  35221. * Register a function that will be executed before the physics world is stepping forward.
  35222. */
  35223. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  35224. this._onBeforePhysicsStepCallbacks.push(func);
  35225. };
  35226. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  35227. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  35228. if (index > -1) {
  35229. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  35230. }
  35231. else {
  35232. BABYLON.Tools.Warn("Function to remove was not found");
  35233. }
  35234. };
  35235. /**
  35236. * Register a function that will be executed after the physics step
  35237. */
  35238. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  35239. this._onAfterPhysicsStepCallbacks.push(func);
  35240. };
  35241. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  35242. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  35243. if (index > -1) {
  35244. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  35245. }
  35246. else {
  35247. BABYLON.Tools.Warn("Function to remove was not found");
  35248. }
  35249. };
  35250. /**
  35251. * register a function that will be executed when this impostor collides against a different body.
  35252. */
  35253. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  35254. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35255. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  35256. };
  35257. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  35258. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35259. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  35260. if (index > -1) {
  35261. this._onPhysicsCollideCallbacks.splice(index, 1);
  35262. }
  35263. else {
  35264. BABYLON.Tools.Warn("Function to remove was not found");
  35265. }
  35266. };
  35267. /**
  35268. * Apply a force
  35269. */
  35270. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  35271. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  35272. };
  35273. /**
  35274. * Apply an impulse
  35275. */
  35276. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  35277. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  35278. };
  35279. /**
  35280. * A help function to create a joint.
  35281. */
  35282. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  35283. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  35284. this.addJoint(otherImpostor, joint);
  35285. };
  35286. /**
  35287. * Add a joint to this impostor with a different impostor.
  35288. */
  35289. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  35290. this._joints.push({
  35291. otherImpostor: otherImpostor,
  35292. joint: joint
  35293. });
  35294. this._physicsEngine.addJoint(this, otherImpostor, joint);
  35295. };
  35296. /**
  35297. * Will keep this body still, in a sleep mode.
  35298. */
  35299. PhysicsImpostor.prototype.sleep = function () {
  35300. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  35301. };
  35302. /**
  35303. * Wake the body up.
  35304. */
  35305. PhysicsImpostor.prototype.wakeUp = function () {
  35306. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  35307. };
  35308. PhysicsImpostor.prototype.clone = function (newObject) {
  35309. if (!newObject)
  35310. return null;
  35311. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  35312. };
  35313. PhysicsImpostor.prototype.dispose = function () {
  35314. var _this = this;
  35315. //no dispose if no physics engine is available.
  35316. if (!this._physicsEngine) {
  35317. return;
  35318. }
  35319. this._joints.forEach(function (j) {
  35320. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  35321. });
  35322. //dispose the physics body
  35323. this._physicsEngine.removeImpostor(this);
  35324. if (this.parent) {
  35325. this.parent.forceUpdate();
  35326. }
  35327. else {
  35328. }
  35329. };
  35330. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  35331. this._deltaPosition.copyFrom(position);
  35332. };
  35333. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  35334. if (!this._deltaRotation) {
  35335. this._deltaRotation = new BABYLON.Quaternion();
  35336. }
  35337. this._deltaRotation.copyFrom(rotation);
  35338. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  35339. };
  35340. return PhysicsImpostor;
  35341. }());
  35342. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  35343. //Impostor types
  35344. PhysicsImpostor.NoImpostor = 0;
  35345. PhysicsImpostor.SphereImpostor = 1;
  35346. PhysicsImpostor.BoxImpostor = 2;
  35347. PhysicsImpostor.PlaneImpostor = 3;
  35348. PhysicsImpostor.MeshImpostor = 4;
  35349. PhysicsImpostor.CylinderImpostor = 7;
  35350. PhysicsImpostor.ParticleImpostor = 8;
  35351. PhysicsImpostor.HeightmapImpostor = 9;
  35352. BABYLON.PhysicsImpostor = PhysicsImpostor;
  35353. })(BABYLON || (BABYLON = {}));
  35354. //# sourceMappingURL=babylon.physicsImpostor.js.map
  35355. var BABYLON;
  35356. (function (BABYLON) {
  35357. var PhysicsEngine = (function () {
  35358. function PhysicsEngine(gravity, _physicsPlugin) {
  35359. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  35360. this._physicsPlugin = _physicsPlugin;
  35361. //new methods and parameters
  35362. this._impostors = [];
  35363. this._joints = [];
  35364. if (!this._physicsPlugin.isSupported()) {
  35365. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  35366. + "Please make sure it is included.");
  35367. }
  35368. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  35369. this.setGravity(gravity);
  35370. this.setTimeStep();
  35371. }
  35372. PhysicsEngine.prototype.setGravity = function (gravity) {
  35373. this.gravity = gravity;
  35374. this._physicsPlugin.setGravity(this.gravity);
  35375. };
  35376. /**
  35377. * Set the time step of the physics engine.
  35378. * default is 1/60.
  35379. * To slow it down, enter 1/600 for example.
  35380. * To speed it up, 1/30
  35381. * @param {number} newTimeStep the new timestep to apply to this world.
  35382. */
  35383. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  35384. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  35385. this._physicsPlugin.setTimeStep(newTimeStep);
  35386. };
  35387. PhysicsEngine.prototype.dispose = function () {
  35388. this._impostors.forEach(function (impostor) {
  35389. impostor.dispose();
  35390. });
  35391. this._physicsPlugin.dispose();
  35392. };
  35393. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  35394. return this._physicsPlugin.name;
  35395. };
  35396. /**
  35397. * Adding a new impostor for the impostor tracking.
  35398. * This will be done by the impostor itself.
  35399. * @param {PhysicsImpostor} impostor the impostor to add
  35400. */
  35401. PhysicsEngine.prototype.addImpostor = function (impostor) {
  35402. impostor.uniqueId = this._impostors.push(impostor);
  35403. //if no parent, generate the body
  35404. if (!impostor.parent) {
  35405. this._physicsPlugin.generatePhysicsBody(impostor);
  35406. }
  35407. };
  35408. /**
  35409. * Remove an impostor from the engine.
  35410. * This impostor and its mesh will not longer be updated by the physics engine.
  35411. * @param {PhysicsImpostor} impostor the impostor to remove
  35412. */
  35413. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  35414. var index = this._impostors.indexOf(impostor);
  35415. if (index > -1) {
  35416. var removed = this._impostors.splice(index, 1);
  35417. //Is it needed?
  35418. if (removed.length) {
  35419. //this will also remove it from the world.
  35420. removed[0].physicsBody = null;
  35421. }
  35422. }
  35423. };
  35424. /**
  35425. * Add a joint to the physics engine
  35426. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  35427. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  35428. * @param {PhysicsJoint} the joint that will connect both impostors.
  35429. */
  35430. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  35431. var impostorJoint = {
  35432. mainImpostor: mainImpostor,
  35433. connectedImpostor: connectedImpostor,
  35434. joint: joint
  35435. };
  35436. joint.physicsPlugin = this._physicsPlugin;
  35437. this._joints.push(impostorJoint);
  35438. this._physicsPlugin.generateJoint(impostorJoint);
  35439. };
  35440. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  35441. var matchingJoints = this._joints.filter(function (impostorJoint) {
  35442. return (impostorJoint.connectedImpostor === connectedImpostor
  35443. && impostorJoint.joint === joint
  35444. && impostorJoint.mainImpostor === mainImpostor);
  35445. });
  35446. if (matchingJoints.length) {
  35447. this._physicsPlugin.removeJoint(matchingJoints[0]);
  35448. }
  35449. };
  35450. /**
  35451. * Called by the scene. no need to call it.
  35452. */
  35453. PhysicsEngine.prototype._step = function (delta) {
  35454. var _this = this;
  35455. //check if any mesh has no body / requires an update
  35456. this._impostors.forEach(function (impostor) {
  35457. if (impostor.isBodyInitRequired()) {
  35458. _this._physicsPlugin.generatePhysicsBody(impostor);
  35459. }
  35460. });
  35461. if (delta > 0.1) {
  35462. delta = 0.1;
  35463. }
  35464. else if (delta <= 0) {
  35465. delta = 1.0 / 60.0;
  35466. }
  35467. this._physicsPlugin.executeStep(delta, this._impostors);
  35468. };
  35469. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  35470. return this._physicsPlugin;
  35471. };
  35472. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  35473. for (var i = 0; i < this._impostors.length; ++i) {
  35474. if (this._impostors[i].object === object) {
  35475. return this._impostors[i];
  35476. }
  35477. }
  35478. };
  35479. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  35480. for (var i = 0; i < this._impostors.length; ++i) {
  35481. if (this._impostors[i].physicsBody === body) {
  35482. return this._impostors[i];
  35483. }
  35484. }
  35485. };
  35486. return PhysicsEngine;
  35487. }());
  35488. // Statics, Legacy support.
  35489. /**
  35490. * @Deprecated
  35491. *
  35492. */
  35493. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  35494. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  35495. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  35496. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  35497. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  35498. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  35499. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  35500. PhysicsEngine.CapsuleImpostor = -1;
  35501. PhysicsEngine.ConeImpostor = -1;
  35502. PhysicsEngine.ConvexHullImpostor = -1;
  35503. PhysicsEngine.Epsilon = 0.001;
  35504. BABYLON.PhysicsEngine = PhysicsEngine;
  35505. })(BABYLON || (BABYLON = {}));
  35506. //# sourceMappingURL=babylon.physicsEngine.js.map
  35507. var BABYLON;
  35508. (function (BABYLON) {
  35509. var VertexData = (function () {
  35510. function VertexData() {
  35511. }
  35512. VertexData.prototype.set = function (data, kind) {
  35513. switch (kind) {
  35514. case BABYLON.VertexBuffer.PositionKind:
  35515. this.positions = data;
  35516. break;
  35517. case BABYLON.VertexBuffer.NormalKind:
  35518. this.normals = data;
  35519. break;
  35520. case BABYLON.VertexBuffer.UVKind:
  35521. this.uvs = data;
  35522. break;
  35523. case BABYLON.VertexBuffer.UV2Kind:
  35524. this.uvs2 = data;
  35525. break;
  35526. case BABYLON.VertexBuffer.UV3Kind:
  35527. this.uvs3 = data;
  35528. break;
  35529. case BABYLON.VertexBuffer.UV4Kind:
  35530. this.uvs4 = data;
  35531. break;
  35532. case BABYLON.VertexBuffer.UV5Kind:
  35533. this.uvs5 = data;
  35534. break;
  35535. case BABYLON.VertexBuffer.UV6Kind:
  35536. this.uvs6 = data;
  35537. break;
  35538. case BABYLON.VertexBuffer.ColorKind:
  35539. this.colors = data;
  35540. break;
  35541. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35542. this.matricesIndices = data;
  35543. break;
  35544. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35545. this.matricesWeights = data;
  35546. break;
  35547. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35548. this.matricesIndicesExtra = data;
  35549. break;
  35550. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35551. this.matricesWeightsExtra = data;
  35552. break;
  35553. }
  35554. };
  35555. /**
  35556. * Associates the vertexData to the passed Mesh.
  35557. * Sets it as updatable or not (default `false`).
  35558. * Returns the VertexData.
  35559. */
  35560. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35561. this._applyTo(mesh, updatable);
  35562. return this;
  35563. };
  35564. /**
  35565. * Associates the vertexData to the passed Geometry.
  35566. * Sets it as updatable or not (default `false`).
  35567. * Returns the VertexData.
  35568. */
  35569. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35570. this._applyTo(geometry, updatable);
  35571. return this;
  35572. };
  35573. /**
  35574. * Updates the associated mesh.
  35575. * Returns the VertexData.
  35576. */
  35577. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35578. this._update(mesh);
  35579. return this;
  35580. };
  35581. /**
  35582. * Updates the associated geometry.
  35583. * Returns the VertexData.
  35584. */
  35585. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35586. this._update(geometry);
  35587. return this;
  35588. };
  35589. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35590. if (this.positions) {
  35591. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35592. }
  35593. if (this.normals) {
  35594. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35595. }
  35596. if (this.uvs) {
  35597. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35598. }
  35599. if (this.uvs2) {
  35600. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35601. }
  35602. if (this.uvs3) {
  35603. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35604. }
  35605. if (this.uvs4) {
  35606. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35607. }
  35608. if (this.uvs5) {
  35609. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35610. }
  35611. if (this.uvs6) {
  35612. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35613. }
  35614. if (this.colors) {
  35615. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35616. }
  35617. if (this.matricesIndices) {
  35618. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35619. }
  35620. if (this.matricesWeights) {
  35621. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35622. }
  35623. if (this.matricesIndicesExtra) {
  35624. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35625. }
  35626. if (this.matricesWeightsExtra) {
  35627. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35628. }
  35629. if (this.indices) {
  35630. meshOrGeometry.setIndices(this.indices);
  35631. }
  35632. return this;
  35633. };
  35634. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35635. if (this.positions) {
  35636. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35637. }
  35638. if (this.normals) {
  35639. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35640. }
  35641. if (this.uvs) {
  35642. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35643. }
  35644. if (this.uvs2) {
  35645. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35646. }
  35647. if (this.uvs3) {
  35648. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35649. }
  35650. if (this.uvs4) {
  35651. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35652. }
  35653. if (this.uvs5) {
  35654. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35655. }
  35656. if (this.uvs6) {
  35657. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35658. }
  35659. if (this.colors) {
  35660. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35661. }
  35662. if (this.matricesIndices) {
  35663. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35664. }
  35665. if (this.matricesWeights) {
  35666. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35667. }
  35668. if (this.matricesIndicesExtra) {
  35669. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35670. }
  35671. if (this.matricesWeightsExtra) {
  35672. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35673. }
  35674. if (this.indices) {
  35675. meshOrGeometry.setIndices(this.indices);
  35676. }
  35677. return this;
  35678. };
  35679. /**
  35680. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35681. * Returns the VertexData.
  35682. */
  35683. VertexData.prototype.transform = function (matrix) {
  35684. var transformed = BABYLON.Vector3.Zero();
  35685. var index;
  35686. if (this.positions) {
  35687. var position = BABYLON.Vector3.Zero();
  35688. for (index = 0; index < this.positions.length; index += 3) {
  35689. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35690. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35691. this.positions[index] = transformed.x;
  35692. this.positions[index + 1] = transformed.y;
  35693. this.positions[index + 2] = transformed.z;
  35694. }
  35695. }
  35696. if (this.normals) {
  35697. var normal = BABYLON.Vector3.Zero();
  35698. for (index = 0; index < this.normals.length; index += 3) {
  35699. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35700. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35701. this.normals[index] = transformed.x;
  35702. this.normals[index + 1] = transformed.y;
  35703. this.normals[index + 2] = transformed.z;
  35704. }
  35705. }
  35706. return this;
  35707. };
  35708. /**
  35709. * Merges the passed VertexData into the current one.
  35710. * Returns the modified VertexData.
  35711. */
  35712. VertexData.prototype.merge = function (other) {
  35713. if (other.indices) {
  35714. if (!this.indices) {
  35715. this.indices = [];
  35716. }
  35717. var offset = this.positions ? this.positions.length / 3 : 0;
  35718. for (var index = 0; index < other.indices.length; index++) {
  35719. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35720. this.indices.push(other.indices[index] + offset);
  35721. }
  35722. }
  35723. this.positions = this._mergeElement(this.positions, other.positions);
  35724. this.normals = this._mergeElement(this.normals, other.normals);
  35725. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35726. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35727. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35728. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35729. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35730. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35731. this.colors = this._mergeElement(this.colors, other.colors);
  35732. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35733. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35734. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35735. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35736. return this;
  35737. };
  35738. VertexData.prototype._mergeElement = function (source, other) {
  35739. if (!other)
  35740. return source;
  35741. if (!source)
  35742. return other;
  35743. var len = other.length + source.length;
  35744. var isSrcTypedArray = source instanceof Float32Array;
  35745. var isOthTypedArray = other instanceof Float32Array;
  35746. // use non-loop method when the source is Float32Array
  35747. if (isSrcTypedArray) {
  35748. var ret32 = new Float32Array(len);
  35749. ret32.set(source);
  35750. ret32.set(other, source.length);
  35751. return ret32;
  35752. }
  35753. else if (!isOthTypedArray) {
  35754. return source.concat(other);
  35755. }
  35756. else {
  35757. var ret = source.slice(0); // copy source to a separate array
  35758. for (var i = 0, len = other.length; i < len; i++) {
  35759. ret.push(other[i]);
  35760. }
  35761. return ret;
  35762. }
  35763. };
  35764. /**
  35765. * Serializes the VertexData.
  35766. * Returns a serialized object.
  35767. */
  35768. VertexData.prototype.serialize = function () {
  35769. var serializationObject = this.serialize();
  35770. if (this.positions) {
  35771. serializationObject.positions = this.positions;
  35772. }
  35773. if (this.normals) {
  35774. serializationObject.normals = this.normals;
  35775. }
  35776. if (this.uvs) {
  35777. serializationObject.uvs = this.uvs;
  35778. }
  35779. if (this.uvs2) {
  35780. serializationObject.uvs2 = this.uvs2;
  35781. }
  35782. if (this.uvs3) {
  35783. serializationObject.uvs3 = this.uvs3;
  35784. }
  35785. if (this.uvs4) {
  35786. serializationObject.uvs4 = this.uvs4;
  35787. }
  35788. if (this.uvs5) {
  35789. serializationObject.uvs5 = this.uvs5;
  35790. }
  35791. if (this.uvs6) {
  35792. serializationObject.uvs6 = this.uvs6;
  35793. }
  35794. if (this.colors) {
  35795. serializationObject.colors = this.colors;
  35796. }
  35797. if (this.matricesIndices) {
  35798. serializationObject.matricesIndices = this.matricesIndices;
  35799. serializationObject.matricesIndices._isExpanded = true;
  35800. }
  35801. if (this.matricesWeights) {
  35802. serializationObject.matricesWeights = this.matricesWeights;
  35803. }
  35804. if (this.matricesIndicesExtra) {
  35805. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35806. serializationObject.matricesIndicesExtra._isExpanded = true;
  35807. }
  35808. if (this.matricesWeightsExtra) {
  35809. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35810. }
  35811. serializationObject.indices = this.indices;
  35812. return serializationObject;
  35813. };
  35814. // Statics
  35815. /**
  35816. * Returns the object VertexData associated to the passed mesh.
  35817. */
  35818. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  35819. return VertexData._ExtractFrom(mesh, copyWhenShared);
  35820. };
  35821. /**
  35822. * Returns the object VertexData associated to the passed geometry.
  35823. */
  35824. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  35825. return VertexData._ExtractFrom(geometry, copyWhenShared);
  35826. };
  35827. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  35828. var result = new VertexData();
  35829. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35830. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  35831. }
  35832. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35833. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  35834. }
  35835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35836. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  35837. }
  35838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35839. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  35840. }
  35841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35842. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  35843. }
  35844. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35845. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  35846. }
  35847. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35848. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  35849. }
  35850. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35851. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  35852. }
  35853. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35854. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  35855. }
  35856. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35857. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  35858. }
  35859. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35860. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  35861. }
  35862. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35863. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  35864. }
  35865. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35866. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  35867. }
  35868. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35869. return result;
  35870. };
  35871. /**
  35872. * Creates the vertexData of the Ribbon.
  35873. */
  35874. VertexData.CreateRibbon = function (options) {
  35875. var pathArray = options.pathArray;
  35876. var closeArray = options.closeArray || false;
  35877. var closePath = options.closePath || false;
  35878. var invertUV = options.invertUV || false;
  35879. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35880. var offset = options.offset || defaultOffset;
  35881. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35882. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35883. var positions = [];
  35884. var indices = [];
  35885. var normals = [];
  35886. var uvs = [];
  35887. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35888. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35889. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35890. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35891. var minlg; // minimal length among all paths from pathArray
  35892. var lg = []; // array of path lengths : nb of vertex per path
  35893. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35894. var p; // path iterator
  35895. var i; // point iterator
  35896. var j; // point iterator
  35897. // if single path in pathArray
  35898. if (pathArray.length < 2) {
  35899. var ar1 = [];
  35900. var ar2 = [];
  35901. for (i = 0; i < pathArray[0].length - offset; i++) {
  35902. ar1.push(pathArray[0][i]);
  35903. ar2.push(pathArray[0][i + offset]);
  35904. }
  35905. pathArray = [ar1, ar2];
  35906. }
  35907. // positions and horizontal distances (u)
  35908. var idc = 0;
  35909. var closePathCorr = (closePath) ? 1 : 0;
  35910. var path;
  35911. var l;
  35912. minlg = pathArray[0].length;
  35913. var vectlg;
  35914. var dist;
  35915. for (p = 0; p < pathArray.length; p++) {
  35916. uTotalDistance[p] = 0;
  35917. us[p] = [0];
  35918. path = pathArray[p];
  35919. l = path.length;
  35920. minlg = (minlg < l) ? minlg : l;
  35921. j = 0;
  35922. while (j < l) {
  35923. positions.push(path[j].x, path[j].y, path[j].z);
  35924. if (j > 0) {
  35925. vectlg = path[j].subtract(path[j - 1]).length();
  35926. dist = vectlg + uTotalDistance[p];
  35927. us[p].push(dist);
  35928. uTotalDistance[p] = dist;
  35929. }
  35930. j++;
  35931. }
  35932. if (closePath) {
  35933. j--;
  35934. positions.push(path[0].x, path[0].y, path[0].z);
  35935. vectlg = path[j].subtract(path[0]).length();
  35936. dist = vectlg + uTotalDistance[p];
  35937. us[p].push(dist);
  35938. uTotalDistance[p] = dist;
  35939. }
  35940. lg[p] = l + closePathCorr;
  35941. idx[p] = idc;
  35942. idc += (l + closePathCorr);
  35943. }
  35944. // vertical distances (v)
  35945. var path1;
  35946. var path2;
  35947. var vertex1;
  35948. var vertex2;
  35949. for (i = 0; i < minlg + closePathCorr; i++) {
  35950. vTotalDistance[i] = 0;
  35951. vs[i] = [0];
  35952. for (p = 0; p < pathArray.length - 1; p++) {
  35953. path1 = pathArray[p];
  35954. path2 = pathArray[p + 1];
  35955. if (i === minlg) {
  35956. vertex1 = path1[0];
  35957. vertex2 = path2[0];
  35958. }
  35959. else {
  35960. vertex1 = path1[i];
  35961. vertex2 = path2[i];
  35962. }
  35963. vectlg = vertex2.subtract(vertex1).length();
  35964. dist = vectlg + vTotalDistance[i];
  35965. vs[i].push(dist);
  35966. vTotalDistance[i] = dist;
  35967. }
  35968. if (closeArray) {
  35969. path1 = pathArray[p];
  35970. path2 = pathArray[0];
  35971. if (i === minlg) {
  35972. vertex2 = path2[0];
  35973. }
  35974. vectlg = vertex2.subtract(vertex1).length();
  35975. dist = vectlg + vTotalDistance[i];
  35976. vTotalDistance[i] = dist;
  35977. }
  35978. }
  35979. // uvs
  35980. var u;
  35981. var v;
  35982. for (p = 0; p < pathArray.length; p++) {
  35983. for (i = 0; i < minlg + closePathCorr; i++) {
  35984. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35985. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35986. if (invertUV) {
  35987. uvs.push(v, u);
  35988. }
  35989. else {
  35990. uvs.push(u, v);
  35991. }
  35992. }
  35993. }
  35994. // indices
  35995. p = 0; // path index
  35996. var pi = 0; // positions array index
  35997. var l1 = lg[p] - 1; // path1 length
  35998. var l2 = lg[p + 1] - 1; // path2 length
  35999. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36000. var shft = idx[1] - idx[0]; // shift
  36001. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36002. while (pi <= min && p < path1nb) {
  36003. // 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
  36004. indices.push(pi, pi + shft, pi + 1);
  36005. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36006. pi += 1;
  36007. if (pi === min) {
  36008. p++;
  36009. if (p === lg.length - 1) {
  36010. shft = idx[0] - idx[p];
  36011. l1 = lg[p] - 1;
  36012. l2 = lg[0] - 1;
  36013. }
  36014. else {
  36015. shft = idx[p + 1] - idx[p];
  36016. l1 = lg[p] - 1;
  36017. l2 = lg[p + 1] - 1;
  36018. }
  36019. pi = idx[p];
  36020. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36021. }
  36022. }
  36023. // normals
  36024. VertexData.ComputeNormals(positions, indices, normals);
  36025. if (closePath) {
  36026. var indexFirst = 0;
  36027. var indexLast = 0;
  36028. for (p = 0; p < pathArray.length; p++) {
  36029. indexFirst = idx[p] * 3;
  36030. if (p + 1 < pathArray.length) {
  36031. indexLast = (idx[p + 1] - 1) * 3;
  36032. }
  36033. else {
  36034. indexLast = normals.length - 3;
  36035. }
  36036. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36037. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36038. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36039. normals[indexLast] = normals[indexFirst];
  36040. normals[indexLast + 1] = normals[indexFirst + 1];
  36041. normals[indexLast + 2] = normals[indexFirst + 2];
  36042. }
  36043. }
  36044. // sides
  36045. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36046. // Result
  36047. var vertexData = new VertexData();
  36048. vertexData.indices = indices;
  36049. vertexData.positions = positions;
  36050. vertexData.normals = normals;
  36051. vertexData.uvs = uvs;
  36052. if (closePath) {
  36053. vertexData._idx = idx;
  36054. }
  36055. return vertexData;
  36056. };
  36057. /**
  36058. * Creates the VertexData of the Box.
  36059. */
  36060. VertexData.CreateBox = function (options) {
  36061. var normalsSource = [
  36062. new BABYLON.Vector3(0, 0, 1),
  36063. new BABYLON.Vector3(0, 0, -1),
  36064. new BABYLON.Vector3(1, 0, 0),
  36065. new BABYLON.Vector3(-1, 0, 0),
  36066. new BABYLON.Vector3(0, 1, 0),
  36067. new BABYLON.Vector3(0, -1, 0)
  36068. ];
  36069. var indices = [];
  36070. var positions = [];
  36071. var normals = [];
  36072. var uvs = [];
  36073. var width = options.width || options.size || 1;
  36074. var height = options.height || options.size || 1;
  36075. var depth = options.depth || options.size || 1;
  36076. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36077. var faceUV = options.faceUV || new Array(6);
  36078. var faceColors = options.faceColors;
  36079. var colors = [];
  36080. // default face colors and UV if undefined
  36081. for (var f = 0; f < 6; f++) {
  36082. if (faceUV[f] === undefined) {
  36083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36084. }
  36085. if (faceColors && faceColors[f] === undefined) {
  36086. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36087. }
  36088. }
  36089. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36090. // Create each face in turn.
  36091. for (var index = 0; index < normalsSource.length; index++) {
  36092. var normal = normalsSource[index];
  36093. // Get two vectors perpendicular to the face normal and to each other.
  36094. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36095. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36096. // Six indices (two triangles) per face.
  36097. var verticesLength = positions.length / 3;
  36098. indices.push(verticesLength);
  36099. indices.push(verticesLength + 1);
  36100. indices.push(verticesLength + 2);
  36101. indices.push(verticesLength);
  36102. indices.push(verticesLength + 2);
  36103. indices.push(verticesLength + 3);
  36104. // Four vertices per face.
  36105. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36106. positions.push(vertex.x, vertex.y, vertex.z);
  36107. normals.push(normal.x, normal.y, normal.z);
  36108. uvs.push(faceUV[index].z, faceUV[index].w);
  36109. if (faceColors) {
  36110. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36111. }
  36112. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36113. positions.push(vertex.x, vertex.y, vertex.z);
  36114. normals.push(normal.x, normal.y, normal.z);
  36115. uvs.push(faceUV[index].x, faceUV[index].w);
  36116. if (faceColors) {
  36117. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36118. }
  36119. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36120. positions.push(vertex.x, vertex.y, vertex.z);
  36121. normals.push(normal.x, normal.y, normal.z);
  36122. uvs.push(faceUV[index].x, faceUV[index].y);
  36123. if (faceColors) {
  36124. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36125. }
  36126. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36127. positions.push(vertex.x, vertex.y, vertex.z);
  36128. normals.push(normal.x, normal.y, normal.z);
  36129. uvs.push(faceUV[index].z, faceUV[index].y);
  36130. if (faceColors) {
  36131. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36132. }
  36133. }
  36134. // sides
  36135. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36136. // Result
  36137. var vertexData = new VertexData();
  36138. vertexData.indices = indices;
  36139. vertexData.positions = positions;
  36140. vertexData.normals = normals;
  36141. vertexData.uvs = uvs;
  36142. if (faceColors) {
  36143. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36144. vertexData.colors = totalColors;
  36145. }
  36146. return vertexData;
  36147. };
  36148. /**
  36149. * Creates the VertexData of the Sphere.
  36150. */
  36151. VertexData.CreateSphere = function (options) {
  36152. var segments = options.segments || 32;
  36153. var diameterX = options.diameterX || options.diameter || 1;
  36154. var diameterY = options.diameterY || options.diameter || 1;
  36155. var diameterZ = options.diameterZ || options.diameter || 1;
  36156. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36157. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36158. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36159. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36160. var totalZRotationSteps = 2 + segments;
  36161. var totalYRotationSteps = 2 * totalZRotationSteps;
  36162. var indices = [];
  36163. var positions = [];
  36164. var normals = [];
  36165. var uvs = [];
  36166. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36167. var normalizedZ = zRotationStep / totalZRotationSteps;
  36168. var angleZ = normalizedZ * Math.PI * slice;
  36169. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36170. var normalizedY = yRotationStep / totalYRotationSteps;
  36171. var angleY = normalizedY * Math.PI * 2 * arc;
  36172. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36173. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36174. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36175. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36176. var vertex = complete.multiply(radius);
  36177. var normal = complete.divide(radius).normalize();
  36178. positions.push(vertex.x, vertex.y, vertex.z);
  36179. normals.push(normal.x, normal.y, normal.z);
  36180. uvs.push(normalizedY, normalizedZ);
  36181. }
  36182. if (zRotationStep > 0) {
  36183. var verticesCount = positions.length / 3;
  36184. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36185. indices.push((firstIndex));
  36186. indices.push((firstIndex + 1));
  36187. indices.push(firstIndex + totalYRotationSteps + 1);
  36188. indices.push((firstIndex + totalYRotationSteps + 1));
  36189. indices.push((firstIndex + 1));
  36190. indices.push((firstIndex + totalYRotationSteps + 2));
  36191. }
  36192. }
  36193. }
  36194. // Sides
  36195. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36196. // Result
  36197. var vertexData = new VertexData();
  36198. vertexData.indices = indices;
  36199. vertexData.positions = positions;
  36200. vertexData.normals = normals;
  36201. vertexData.uvs = uvs;
  36202. return vertexData;
  36203. };
  36204. /**
  36205. * Creates the VertexData of the Cylinder or Cone.
  36206. */
  36207. VertexData.CreateCylinder = function (options) {
  36208. var height = options.height || 2;
  36209. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36210. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36211. var tessellation = options.tessellation || 24;
  36212. var subdivisions = options.subdivisions || 1;
  36213. var hasRings = options.hasRings;
  36214. var enclose = options.enclose;
  36215. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36216. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36217. var faceUV = options.faceUV || new Array(3);
  36218. var faceColors = options.faceColors;
  36219. // default face colors and UV if undefined
  36220. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36221. var ringNb = (hasRings) ? subdivisions : 1;
  36222. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36223. var f;
  36224. for (f = 0; f < surfaceNb; f++) {
  36225. if (faceColors && faceColors[f] === undefined) {
  36226. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36227. }
  36228. }
  36229. for (f = 0; f < surfaceNb; f++) {
  36230. if (faceUV && faceUV[f] === undefined) {
  36231. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36232. }
  36233. }
  36234. var indices = [];
  36235. var positions = [];
  36236. var normals = [];
  36237. var uvs = [];
  36238. var colors = [];
  36239. var angle_step = Math.PI * 2 * arc / tessellation;
  36240. var angle;
  36241. var h;
  36242. var radius;
  36243. var tan = (diameterBottom - diameterTop) / 2 / height;
  36244. var ringVertex = BABYLON.Vector3.Zero();
  36245. var ringNormal = BABYLON.Vector3.Zero();
  36246. var ringFirstVertex = BABYLON.Vector3.Zero();
  36247. var ringFirstNormal = BABYLON.Vector3.Zero();
  36248. var quadNormal = BABYLON.Vector3.Zero();
  36249. var Y = BABYLON.Axis.Y;
  36250. // positions, normals, uvs
  36251. var i;
  36252. var j;
  36253. var r;
  36254. var ringIdx = 1;
  36255. var s = 1; // surface index
  36256. var cs = 0;
  36257. var v = 0;
  36258. for (i = 0; i <= subdivisions; i++) {
  36259. h = i / subdivisions;
  36260. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36261. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36262. for (r = 0; r < ringIdx; r++) {
  36263. if (hasRings) {
  36264. s += r;
  36265. }
  36266. if (enclose) {
  36267. s += 2 * r;
  36268. }
  36269. for (j = 0; j <= tessellation; j++) {
  36270. angle = j * angle_step;
  36271. // position
  36272. ringVertex.x = Math.cos(-angle) * radius;
  36273. ringVertex.y = -height / 2 + h * height;
  36274. ringVertex.z = Math.sin(-angle) * radius;
  36275. // normal
  36276. if (diameterTop === 0 && i === subdivisions) {
  36277. // if no top cap, reuse former normals
  36278. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36279. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36280. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36281. }
  36282. else {
  36283. ringNormal.x = ringVertex.x;
  36284. ringNormal.z = ringVertex.z;
  36285. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36286. ringNormal.normalize();
  36287. }
  36288. // keep first ring vertex values for enclose
  36289. if (j === 0) {
  36290. ringFirstVertex.copyFrom(ringVertex);
  36291. ringFirstNormal.copyFrom(ringNormal);
  36292. }
  36293. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36294. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36295. if (hasRings) {
  36296. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36297. }
  36298. else {
  36299. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36300. }
  36301. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36302. if (faceColors) {
  36303. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36304. }
  36305. }
  36306. // if enclose, add four vertices and their dedicated normals
  36307. if (arc !== 1 && enclose) {
  36308. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36309. positions.push(0, ringVertex.y, 0);
  36310. positions.push(0, ringVertex.y, 0);
  36311. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36312. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36313. quadNormal.normalize();
  36314. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36315. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36316. quadNormal.normalize();
  36317. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36318. if (hasRings) {
  36319. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36320. }
  36321. else {
  36322. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36323. }
  36324. uvs.push(faceUV[s + 1].x, v);
  36325. uvs.push(faceUV[s + 1].z, v);
  36326. if (hasRings) {
  36327. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36328. }
  36329. else {
  36330. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36331. }
  36332. uvs.push(faceUV[s + 2].x, v);
  36333. uvs.push(faceUV[s + 2].z, v);
  36334. if (faceColors) {
  36335. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36336. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36337. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36338. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36339. }
  36340. }
  36341. if (cs !== s) {
  36342. cs = s;
  36343. }
  36344. }
  36345. }
  36346. // indices
  36347. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36348. var s;
  36349. i = 0;
  36350. for (s = 0; s < subdivisions; s++) {
  36351. for (j = 0; j < tessellation; j++) {
  36352. var i0 = i * (e + 1) + j;
  36353. var i1 = (i + 1) * (e + 1) + j;
  36354. var i2 = i * (e + 1) + (j + 1);
  36355. var i3 = (i + 1) * (e + 1) + (j + 1);
  36356. indices.push(i0, i1, i2);
  36357. indices.push(i3, i2, i1);
  36358. }
  36359. if (arc !== 1 && enclose) {
  36360. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36361. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36362. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36363. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36364. }
  36365. i = (hasRings) ? (i + 2) : (i + 1);
  36366. }
  36367. // Caps
  36368. var createCylinderCap = function (isTop) {
  36369. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36370. if (radius === 0) {
  36371. return;
  36372. }
  36373. // Cap positions, normals & uvs
  36374. var angle;
  36375. var circleVector;
  36376. var i;
  36377. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36378. var c;
  36379. if (faceColors) {
  36380. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36381. }
  36382. // cap center
  36383. var vbase = positions.length / 3;
  36384. var offset = isTop ? height / 2 : -height / 2;
  36385. var center = new BABYLON.Vector3(0, offset, 0);
  36386. positions.push(center.x, center.y, center.z);
  36387. normals.push(0, isTop ? 1 : -1, 0);
  36388. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36389. if (faceColors) {
  36390. colors.push(c.r, c.g, c.b, c.a);
  36391. }
  36392. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36393. for (i = 0; i <= tessellation; i++) {
  36394. angle = Math.PI * 2 * i * arc / tessellation;
  36395. var cos = Math.cos(-angle);
  36396. var sin = Math.sin(-angle);
  36397. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36398. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36399. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36400. normals.push(0, isTop ? 1 : -1, 0);
  36401. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36402. if (faceColors) {
  36403. colors.push(c.r, c.g, c.b, c.a);
  36404. }
  36405. }
  36406. // Cap indices
  36407. for (i = 0; i < tessellation; i++) {
  36408. if (!isTop) {
  36409. indices.push(vbase);
  36410. indices.push(vbase + (i + 1));
  36411. indices.push(vbase + (i + 2));
  36412. }
  36413. else {
  36414. indices.push(vbase);
  36415. indices.push(vbase + (i + 2));
  36416. indices.push(vbase + (i + 1));
  36417. }
  36418. }
  36419. };
  36420. // add caps to geometry
  36421. createCylinderCap(false);
  36422. createCylinderCap(true);
  36423. // Sides
  36424. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36425. var vertexData = new VertexData();
  36426. vertexData.indices = indices;
  36427. vertexData.positions = positions;
  36428. vertexData.normals = normals;
  36429. vertexData.uvs = uvs;
  36430. if (faceColors) {
  36431. vertexData.colors = colors;
  36432. }
  36433. return vertexData;
  36434. };
  36435. /**
  36436. * Creates the VertexData of the Torus.
  36437. */
  36438. VertexData.CreateTorus = function (options) {
  36439. var indices = [];
  36440. var positions = [];
  36441. var normals = [];
  36442. var uvs = [];
  36443. var diameter = options.diameter || 1;
  36444. var thickness = options.thickness || 0.5;
  36445. var tessellation = options.tessellation || 16;
  36446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36447. var stride = tessellation + 1;
  36448. for (var i = 0; i <= tessellation; i++) {
  36449. var u = i / tessellation;
  36450. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36451. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36452. for (var j = 0; j <= tessellation; j++) {
  36453. var v = 1 - j / tessellation;
  36454. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36455. var dx = Math.cos(innerAngle);
  36456. var dy = Math.sin(innerAngle);
  36457. // Create a vertex.
  36458. var normal = new BABYLON.Vector3(dx, dy, 0);
  36459. var position = normal.scale(thickness / 2);
  36460. var textureCoordinate = new BABYLON.Vector2(u, v);
  36461. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36462. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36463. positions.push(position.x, position.y, position.z);
  36464. normals.push(normal.x, normal.y, normal.z);
  36465. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36466. // And create indices for two triangles.
  36467. var nextI = (i + 1) % stride;
  36468. var nextJ = (j + 1) % stride;
  36469. indices.push(i * stride + j);
  36470. indices.push(i * stride + nextJ);
  36471. indices.push(nextI * stride + j);
  36472. indices.push(i * stride + nextJ);
  36473. indices.push(nextI * stride + nextJ);
  36474. indices.push(nextI * stride + j);
  36475. }
  36476. }
  36477. // Sides
  36478. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36479. // Result
  36480. var vertexData = new VertexData();
  36481. vertexData.indices = indices;
  36482. vertexData.positions = positions;
  36483. vertexData.normals = normals;
  36484. vertexData.uvs = uvs;
  36485. return vertexData;
  36486. };
  36487. /**
  36488. * Creates the VertexData of the LineSystem.
  36489. */
  36490. VertexData.CreateLineSystem = function (options) {
  36491. var indices = [];
  36492. var positions = [];
  36493. var lines = options.lines;
  36494. var idx = 0;
  36495. for (var l = 0; l < lines.length; l++) {
  36496. var points = lines[l];
  36497. for (var index = 0; index < points.length; index++) {
  36498. positions.push(points[index].x, points[index].y, points[index].z);
  36499. if (index > 0) {
  36500. indices.push(idx - 1);
  36501. indices.push(idx);
  36502. }
  36503. idx++;
  36504. }
  36505. }
  36506. var vertexData = new VertexData();
  36507. vertexData.indices = indices;
  36508. vertexData.positions = positions;
  36509. return vertexData;
  36510. };
  36511. /**
  36512. * Create the VertexData of the DashedLines.
  36513. */
  36514. VertexData.CreateDashedLines = function (options) {
  36515. var dashSize = options.dashSize || 3;
  36516. var gapSize = options.gapSize || 1;
  36517. var dashNb = options.dashNb || 200;
  36518. var points = options.points;
  36519. var positions = new Array();
  36520. var indices = new Array();
  36521. var curvect = BABYLON.Vector3.Zero();
  36522. var lg = 0;
  36523. var nb = 0;
  36524. var shft = 0;
  36525. var dashshft = 0;
  36526. var curshft = 0;
  36527. var idx = 0;
  36528. var i = 0;
  36529. for (i = 0; i < points.length - 1; i++) {
  36530. points[i + 1].subtractToRef(points[i], curvect);
  36531. lg += curvect.length();
  36532. }
  36533. shft = lg / dashNb;
  36534. dashshft = dashSize * shft / (dashSize + gapSize);
  36535. for (i = 0; i < points.length - 1; i++) {
  36536. points[i + 1].subtractToRef(points[i], curvect);
  36537. nb = Math.floor(curvect.length() / shft);
  36538. curvect.normalize();
  36539. for (var j = 0; j < nb; j++) {
  36540. curshft = shft * j;
  36541. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36542. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36543. indices.push(idx, idx + 1);
  36544. idx += 2;
  36545. }
  36546. }
  36547. // Result
  36548. var vertexData = new VertexData();
  36549. vertexData.positions = positions;
  36550. vertexData.indices = indices;
  36551. return vertexData;
  36552. };
  36553. /**
  36554. * Creates the VertexData of the Ground.
  36555. */
  36556. VertexData.CreateGround = function (options) {
  36557. var indices = [];
  36558. var positions = [];
  36559. var normals = [];
  36560. var uvs = [];
  36561. var row, col;
  36562. var width = options.width || 1;
  36563. var height = options.height || 1;
  36564. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36565. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36566. for (row = 0; row <= subdivisionsY; row++) {
  36567. for (col = 0; col <= subdivisionsX; col++) {
  36568. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36569. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36570. positions.push(position.x, position.y, position.z);
  36571. normals.push(normal.x, normal.y, normal.z);
  36572. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36573. }
  36574. }
  36575. for (row = 0; row < subdivisionsY; row++) {
  36576. for (col = 0; col < subdivisionsX; col++) {
  36577. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36578. indices.push(col + 1 + row * (subdivisionsX + 1));
  36579. indices.push(col + row * (subdivisionsX + 1));
  36580. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36581. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36582. indices.push(col + row * (subdivisionsX + 1));
  36583. }
  36584. }
  36585. // Result
  36586. var vertexData = new VertexData();
  36587. vertexData.indices = indices;
  36588. vertexData.positions = positions;
  36589. vertexData.normals = normals;
  36590. vertexData.uvs = uvs;
  36591. return vertexData;
  36592. };
  36593. /**
  36594. * Creates the VertexData of the TiledGround.
  36595. */
  36596. VertexData.CreateTiledGround = function (options) {
  36597. var xmin = options.xmin || -1.0;
  36598. var zmin = options.zmin || -1.0;
  36599. var xmax = options.xmax || 1.0;
  36600. var zmax = options.zmax || 1.0;
  36601. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36602. var precision = options.precision || { w: 1, h: 1 };
  36603. var indices = [];
  36604. var positions = [];
  36605. var normals = [];
  36606. var uvs = [];
  36607. var row, col, tileRow, tileCol;
  36608. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36609. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36610. precision.w = (precision.w < 1) ? 1 : precision.w;
  36611. precision.h = (precision.h < 1) ? 1 : precision.h;
  36612. var tileSize = {
  36613. 'w': (xmax - xmin) / subdivisions.w,
  36614. 'h': (zmax - zmin) / subdivisions.h
  36615. };
  36616. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36617. // Indices
  36618. var base = positions.length / 3;
  36619. var rowLength = precision.w + 1;
  36620. for (row = 0; row < precision.h; row++) {
  36621. for (col = 0; col < precision.w; col++) {
  36622. var square = [
  36623. base + col + row * rowLength,
  36624. base + (col + 1) + row * rowLength,
  36625. base + (col + 1) + (row + 1) * rowLength,
  36626. base + col + (row + 1) * rowLength
  36627. ];
  36628. indices.push(square[1]);
  36629. indices.push(square[2]);
  36630. indices.push(square[3]);
  36631. indices.push(square[0]);
  36632. indices.push(square[1]);
  36633. indices.push(square[3]);
  36634. }
  36635. }
  36636. // Position, normals and uvs
  36637. var position = BABYLON.Vector3.Zero();
  36638. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36639. for (row = 0; row <= precision.h; row++) {
  36640. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36641. for (col = 0; col <= precision.w; col++) {
  36642. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36643. position.y = 0;
  36644. positions.push(position.x, position.y, position.z);
  36645. normals.push(normal.x, normal.y, normal.z);
  36646. uvs.push(col / precision.w, row / precision.h);
  36647. }
  36648. }
  36649. }
  36650. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36651. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36652. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36653. }
  36654. }
  36655. // Result
  36656. var vertexData = new VertexData();
  36657. vertexData.indices = indices;
  36658. vertexData.positions = positions;
  36659. vertexData.normals = normals;
  36660. vertexData.uvs = uvs;
  36661. return vertexData;
  36662. };
  36663. /**
  36664. * Creates the VertexData of the Ground designed from a heightmap.
  36665. */
  36666. VertexData.CreateGroundFromHeightMap = function (options) {
  36667. var indices = [];
  36668. var positions = [];
  36669. var normals = [];
  36670. var uvs = [];
  36671. var row, col;
  36672. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36673. // Vertices
  36674. for (row = 0; row <= options.subdivisions; row++) {
  36675. for (col = 0; col <= options.subdivisions; col++) {
  36676. 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));
  36677. // Compute height
  36678. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36679. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36680. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36681. var r = options.buffer[pos] / 255.0;
  36682. var g = options.buffer[pos + 1] / 255.0;
  36683. var b = options.buffer[pos + 2] / 255.0;
  36684. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36685. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36686. // Add vertex
  36687. positions.push(position.x, position.y, position.z);
  36688. normals.push(0, 0, 0);
  36689. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36690. }
  36691. }
  36692. // Indices
  36693. for (row = 0; row < options.subdivisions; row++) {
  36694. for (col = 0; col < options.subdivisions; col++) {
  36695. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36696. indices.push(col + 1 + row * (options.subdivisions + 1));
  36697. indices.push(col + row * (options.subdivisions + 1));
  36698. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36699. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36700. indices.push(col + row * (options.subdivisions + 1));
  36701. }
  36702. }
  36703. // Normals
  36704. VertexData.ComputeNormals(positions, indices, normals);
  36705. // Result
  36706. var vertexData = new VertexData();
  36707. vertexData.indices = indices;
  36708. vertexData.positions = positions;
  36709. vertexData.normals = normals;
  36710. vertexData.uvs = uvs;
  36711. return vertexData;
  36712. };
  36713. /**
  36714. * Creates the VertexData of the Plane.
  36715. */
  36716. VertexData.CreatePlane = function (options) {
  36717. var indices = [];
  36718. var positions = [];
  36719. var normals = [];
  36720. var uvs = [];
  36721. var width = options.width || options.size || 1;
  36722. var height = options.height || options.size || 1;
  36723. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36724. // Vertices
  36725. var halfWidth = width / 2.0;
  36726. var halfHeight = height / 2.0;
  36727. positions.push(-halfWidth, -halfHeight, 0);
  36728. normals.push(0, 0, -1.0);
  36729. uvs.push(0.0, 0.0);
  36730. positions.push(halfWidth, -halfHeight, 0);
  36731. normals.push(0, 0, -1.0);
  36732. uvs.push(1.0, 0.0);
  36733. positions.push(halfWidth, halfHeight, 0);
  36734. normals.push(0, 0, -1.0);
  36735. uvs.push(1.0, 1.0);
  36736. positions.push(-halfWidth, halfHeight, 0);
  36737. normals.push(0, 0, -1.0);
  36738. uvs.push(0.0, 1.0);
  36739. // Indices
  36740. indices.push(0);
  36741. indices.push(1);
  36742. indices.push(2);
  36743. indices.push(0);
  36744. indices.push(2);
  36745. indices.push(3);
  36746. // Sides
  36747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36748. // Result
  36749. var vertexData = new VertexData();
  36750. vertexData.indices = indices;
  36751. vertexData.positions = positions;
  36752. vertexData.normals = normals;
  36753. vertexData.uvs = uvs;
  36754. return vertexData;
  36755. };
  36756. /**
  36757. * Creates the VertexData of the Disc or regular Polygon.
  36758. */
  36759. VertexData.CreateDisc = function (options) {
  36760. var positions = [];
  36761. var indices = [];
  36762. var normals = [];
  36763. var uvs = [];
  36764. var radius = options.radius || 0.5;
  36765. var tessellation = options.tessellation || 64;
  36766. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36767. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36768. // positions and uvs
  36769. positions.push(0, 0, 0); // disc center first
  36770. uvs.push(0.5, 0.5);
  36771. var theta = Math.PI * 2 * arc;
  36772. var step = theta / tessellation;
  36773. for (var a = 0; a < theta; a += step) {
  36774. var x = Math.cos(a);
  36775. var y = Math.sin(a);
  36776. var u = (x + 1) / 2;
  36777. var v = (1 - y) / 2;
  36778. positions.push(radius * x, radius * y, 0);
  36779. uvs.push(u, v);
  36780. }
  36781. if (arc === 1) {
  36782. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36783. uvs.push(uvs[2], uvs[3]);
  36784. }
  36785. //indices
  36786. var vertexNb = positions.length / 3;
  36787. for (var i = 1; i < vertexNb - 1; i++) {
  36788. indices.push(i + 1, 0, i);
  36789. }
  36790. // result
  36791. VertexData.ComputeNormals(positions, indices, normals);
  36792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36793. var vertexData = new VertexData();
  36794. vertexData.indices = indices;
  36795. vertexData.positions = positions;
  36796. vertexData.normals = normals;
  36797. vertexData.uvs = uvs;
  36798. return vertexData;
  36799. };
  36800. /**
  36801. * Creates the VertexData of the IcoSphere.
  36802. */
  36803. VertexData.CreateIcoSphere = function (options) {
  36804. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36805. var radius = options.radius || 1;
  36806. var flat = (options.flat === undefined) ? true : options.flat;
  36807. var subdivisions = options.subdivisions || 4;
  36808. var radiusX = options.radiusX || radius;
  36809. var radiusY = options.radiusY || radius;
  36810. var radiusZ = options.radiusZ || radius;
  36811. var t = (1 + Math.sqrt(5)) / 2;
  36812. // 12 vertex x,y,z
  36813. var ico_vertices = [
  36814. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36815. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36816. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36817. ];
  36818. // index of 3 vertex makes a face of icopshere
  36819. var ico_indices = [
  36820. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36821. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36822. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36823. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36824. ];
  36825. // vertex for uv have aliased position, not for UV
  36826. var vertices_unalias_id = [
  36827. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36828. // vertex alias
  36829. 0,
  36830. 2,
  36831. 3,
  36832. 3,
  36833. 3,
  36834. 4,
  36835. 7,
  36836. 8,
  36837. 9,
  36838. 9,
  36839. 10,
  36840. 11 // 23: B + 12
  36841. ];
  36842. // uv as integer step (not pixels !)
  36843. var ico_vertexuv = [
  36844. 5, 1, 3, 1, 6, 4, 0, 0,
  36845. 5, 3, 4, 2, 2, 2, 4, 0,
  36846. 2, 0, 1, 1, 6, 0, 6, 2,
  36847. // vertex alias (for same vertex on different faces)
  36848. 0, 4,
  36849. 3, 3,
  36850. 4, 4,
  36851. 3, 1,
  36852. 4, 2,
  36853. 4, 4,
  36854. 0, 2,
  36855. 1, 1,
  36856. 2, 2,
  36857. 3, 3,
  36858. 1, 3,
  36859. 2, 4 // 23: B + 12
  36860. ];
  36861. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36862. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36863. // First island of uv mapping
  36864. // v = 4h 3+ 2
  36865. // v = 3h 9+ 4
  36866. // v = 2h 9+ 5 B
  36867. // v = 1h 9 1 0
  36868. // v = 0h 3 8 7 A
  36869. // u = 0 1 2 3 4 5 6 *a
  36870. // Second island of uv mapping
  36871. // v = 4h 0+ B+ 4+
  36872. // v = 3h A+ 2+
  36873. // v = 2h 7+ 6 3+
  36874. // v = 1h 8+ 3+
  36875. // v = 0h
  36876. // u = 0 1 2 3 4 5 6 *a
  36877. // Face layout on texture UV mapping
  36878. // ============
  36879. // \ 4 /\ 16 / ======
  36880. // \ / \ / /\ 11 /
  36881. // \/ 7 \/ / \ /
  36882. // ======= / 10 \/
  36883. // /\ 17 /\ =======
  36884. // / \ / \ \ 15 /\
  36885. // / 8 \/ 12 \ \ / \
  36886. // ============ \/ 6 \
  36887. // \ 18 /\ ============
  36888. // \ / \ \ 5 /\ 0 /
  36889. // \/ 13 \ \ / \ /
  36890. // ======= \/ 1 \/
  36891. // =============
  36892. // /\ 19 /\ 2 /\
  36893. // / \ / \ / \
  36894. // / 14 \/ 9 \/ 3 \
  36895. // ===================
  36896. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36897. var ustep = 138 / 1024;
  36898. var vstep = 239 / 1024;
  36899. var uoffset = 60 / 1024;
  36900. var voffset = 26 / 1024;
  36901. // Second island should have margin, not to touch the first island
  36902. // avoid any borderline artefact in pixel rounding
  36903. var island_u_offset = -40 / 1024;
  36904. var island_v_offset = +20 / 1024;
  36905. // face is either island 0 or 1 :
  36906. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36907. var island = [
  36908. 0, 0, 0, 0, 1,
  36909. 0, 0, 1, 1, 0,
  36910. 0, 0, 1, 1, 0,
  36911. 0, 1, 1, 1, 0 // 15 - 19
  36912. ];
  36913. var indices = [];
  36914. var positions = [];
  36915. var normals = [];
  36916. var uvs = [];
  36917. var current_indice = 0;
  36918. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36919. var face_vertex_pos = new Array(3);
  36920. var face_vertex_uv = new Array(3);
  36921. var v012;
  36922. for (v012 = 0; v012 < 3; v012++) {
  36923. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36924. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36925. }
  36926. // create all with normals
  36927. for (var face = 0; face < 20; face++) {
  36928. // 3 vertex per face
  36929. for (v012 = 0; v012 < 3; v012++) {
  36930. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36931. var v_id = ico_indices[3 * face + v012];
  36932. // vertex have 3D position (x,y,z)
  36933. 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]);
  36934. // Normalize to get normal, then scale to radius
  36935. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36936. // uv Coordinates from vertex ID
  36937. 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);
  36938. }
  36939. // Subdivide the face (interpolate pos, norm, uv)
  36940. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36941. // - norm is linear interpolation of vertex corner normal
  36942. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36943. // - uv is linear interpolation
  36944. //
  36945. // Topology is as below for sub-divide by 2
  36946. // vertex shown as v0,v1,v2
  36947. // interp index is i1 to progress in range [v0,v1[
  36948. // interp index is i2 to progress in range [v0,v2[
  36949. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36950. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  36951. //
  36952. //
  36953. // i2 v2
  36954. // ^ ^
  36955. // / / \
  36956. // / / \
  36957. // / / \
  36958. // / / (0,1) \
  36959. // / #---------\
  36960. // / / \ (0,0)'/ \
  36961. // / / \ / \
  36962. // / / \ / \
  36963. // / / (0,0) \ / (1,0) \
  36964. // / #---------#---------\
  36965. // v0 v1
  36966. //
  36967. // --------------------> i1
  36968. //
  36969. // interp of (i1,i2):
  36970. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  36971. // along i1 : lerp(x0,x1, i1/(S-i2))
  36972. //
  36973. // centroid of triangle is needed to get help normal computation
  36974. // (c1,c2) are used for centroid location
  36975. var interp_vertex = function (i1, i2, c1, c2) {
  36976. // vertex is interpolated from
  36977. // - face_vertex_pos[0..2]
  36978. // - face_vertex_uv[0..2]
  36979. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  36980. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  36981. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  36982. pos_interp.normalize();
  36983. var vertex_normal;
  36984. if (flat) {
  36985. // in flat mode, recalculate normal as face centroid normal
  36986. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  36987. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  36988. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  36989. }
  36990. else {
  36991. // in smooth mode, recalculate normal from each single vertex position
  36992. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  36993. }
  36994. // Vertex normal need correction due to X,Y,Z radius scaling
  36995. vertex_normal.x /= radiusX;
  36996. vertex_normal.y /= radiusY;
  36997. vertex_normal.z /= radiusZ;
  36998. vertex_normal.normalize();
  36999. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37000. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37001. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37002. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37003. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37004. uvs.push(uv_interp.x, uv_interp.y);
  37005. // push each vertex has member of a face
  37006. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37007. indices.push(current_indice);
  37008. current_indice++;
  37009. };
  37010. for (var i2 = 0; i2 < subdivisions; i2++) {
  37011. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37012. // face : (i1,i2) for /\ :
  37013. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37014. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37015. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37016. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37017. if (i1 + i2 + 1 < subdivisions) {
  37018. // face : (i1,i2)' for \/ :
  37019. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37020. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37021. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37022. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37023. }
  37024. }
  37025. }
  37026. }
  37027. // Sides
  37028. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37029. // Result
  37030. var vertexData = new VertexData();
  37031. vertexData.indices = indices;
  37032. vertexData.positions = positions;
  37033. vertexData.normals = normals;
  37034. vertexData.uvs = uvs;
  37035. return vertexData;
  37036. };
  37037. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37038. /**
  37039. * Creates the VertexData of the Polyhedron.
  37040. */
  37041. VertexData.CreatePolyhedron = function (options) {
  37042. // provided polyhedron types :
  37043. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37044. // 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)
  37045. var polyhedra = [];
  37046. 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]] };
  37047. 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]] };
  37048. polyhedra[2] = {
  37049. 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]],
  37050. 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]]
  37051. };
  37052. polyhedra[3] = {
  37053. 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]],
  37054. 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]]
  37055. };
  37056. polyhedra[4] = {
  37057. 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]],
  37058. 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]]
  37059. };
  37060. 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]] };
  37061. 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]] };
  37062. 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]] };
  37063. 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]] };
  37064. 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]] };
  37065. 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]] };
  37066. 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]] };
  37067. 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]] };
  37068. 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]] };
  37069. polyhedra[14] = {
  37070. 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]],
  37071. 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]]
  37072. };
  37073. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37074. var size = options.size;
  37075. var sizeX = options.sizeX || size || 1;
  37076. var sizeY = options.sizeY || size || 1;
  37077. var sizeZ = options.sizeZ || size || 1;
  37078. var data = options.custom || polyhedra[type];
  37079. var nbfaces = data.face.length;
  37080. var faceUV = options.faceUV || new Array(nbfaces);
  37081. var faceColors = options.faceColors;
  37082. var flat = (options.flat === undefined) ? true : options.flat;
  37083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37084. var positions = [];
  37085. var indices = [];
  37086. var normals = [];
  37087. var uvs = [];
  37088. var colors = [];
  37089. var index = 0;
  37090. var faceIdx = 0; // face cursor in the array "indexes"
  37091. var indexes = [];
  37092. var i = 0;
  37093. var f = 0;
  37094. var u, v, ang, x, y, tmp;
  37095. // default face colors and UV if undefined
  37096. if (flat) {
  37097. for (f = 0; f < nbfaces; f++) {
  37098. if (faceColors && faceColors[f] === undefined) {
  37099. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37100. }
  37101. if (faceUV && faceUV[f] === undefined) {
  37102. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37103. }
  37104. }
  37105. }
  37106. if (!flat) {
  37107. for (i = 0; i < data.vertex.length; i++) {
  37108. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37109. uvs.push(0, 0);
  37110. }
  37111. for (f = 0; f < nbfaces; f++) {
  37112. for (i = 0; i < data.face[f].length - 2; i++) {
  37113. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37114. }
  37115. }
  37116. }
  37117. else {
  37118. for (f = 0; f < nbfaces; f++) {
  37119. var fl = data.face[f].length; // number of vertices of the current face
  37120. ang = 2 * Math.PI / fl;
  37121. x = 0.5 * Math.tan(ang / 2);
  37122. y = 0.5;
  37123. // positions, uvs, colors
  37124. for (i = 0; i < fl; i++) {
  37125. // positions
  37126. 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);
  37127. indexes.push(index);
  37128. index++;
  37129. // uvs
  37130. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37131. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37132. uvs.push(u, v);
  37133. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37134. y = x * Math.sin(ang) + y * Math.cos(ang);
  37135. x = tmp;
  37136. // colors
  37137. if (faceColors) {
  37138. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37139. }
  37140. }
  37141. // indices from indexes
  37142. for (i = 0; i < fl - 2; i++) {
  37143. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37144. }
  37145. faceIdx += fl;
  37146. }
  37147. }
  37148. VertexData.ComputeNormals(positions, indices, normals);
  37149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37150. var vertexData = new VertexData();
  37151. vertexData.positions = positions;
  37152. vertexData.indices = indices;
  37153. vertexData.normals = normals;
  37154. vertexData.uvs = uvs;
  37155. if (faceColors && flat) {
  37156. vertexData.colors = colors;
  37157. }
  37158. return vertexData;
  37159. };
  37160. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37161. /**
  37162. * Creates the VertexData of the Torus Knot.
  37163. */
  37164. VertexData.CreateTorusKnot = function (options) {
  37165. var indices = [];
  37166. var positions = [];
  37167. var normals = [];
  37168. var uvs = [];
  37169. var radius = options.radius || 2;
  37170. var tube = options.tube || 0.5;
  37171. var radialSegments = options.radialSegments || 32;
  37172. var tubularSegments = options.tubularSegments || 32;
  37173. var p = options.p || 2;
  37174. var q = options.q || 3;
  37175. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37176. // Helper
  37177. var getPos = function (angle) {
  37178. var cu = Math.cos(angle);
  37179. var su = Math.sin(angle);
  37180. var quOverP = q / p * angle;
  37181. var cs = Math.cos(quOverP);
  37182. var tx = radius * (2 + cs) * 0.5 * cu;
  37183. var ty = radius * (2 + cs) * su * 0.5;
  37184. var tz = radius * Math.sin(quOverP) * 0.5;
  37185. return new BABYLON.Vector3(tx, ty, tz);
  37186. };
  37187. // Vertices
  37188. var i;
  37189. var j;
  37190. for (i = 0; i <= radialSegments; i++) {
  37191. var modI = i % radialSegments;
  37192. var u = modI / radialSegments * 2 * p * Math.PI;
  37193. var p1 = getPos(u);
  37194. var p2 = getPos(u + 0.01);
  37195. var tang = p2.subtract(p1);
  37196. var n = p2.add(p1);
  37197. var bitan = BABYLON.Vector3.Cross(tang, n);
  37198. n = BABYLON.Vector3.Cross(bitan, tang);
  37199. bitan.normalize();
  37200. n.normalize();
  37201. for (j = 0; j < tubularSegments; j++) {
  37202. var modJ = j % tubularSegments;
  37203. var v = modJ / tubularSegments * 2 * Math.PI;
  37204. var cx = -tube * Math.cos(v);
  37205. var cy = tube * Math.sin(v);
  37206. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37207. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37208. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37209. uvs.push(i / radialSegments);
  37210. uvs.push(j / tubularSegments);
  37211. }
  37212. }
  37213. for (i = 0; i < radialSegments; i++) {
  37214. for (j = 0; j < tubularSegments; j++) {
  37215. var jNext = (j + 1) % tubularSegments;
  37216. var a = i * tubularSegments + j;
  37217. var b = (i + 1) * tubularSegments + j;
  37218. var c = (i + 1) * tubularSegments + jNext;
  37219. var d = i * tubularSegments + jNext;
  37220. indices.push(d);
  37221. indices.push(b);
  37222. indices.push(a);
  37223. indices.push(d);
  37224. indices.push(c);
  37225. indices.push(b);
  37226. }
  37227. }
  37228. // Normals
  37229. VertexData.ComputeNormals(positions, indices, normals);
  37230. // Sides
  37231. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37232. // Result
  37233. var vertexData = new VertexData();
  37234. vertexData.indices = indices;
  37235. vertexData.positions = positions;
  37236. vertexData.normals = normals;
  37237. vertexData.uvs = uvs;
  37238. return vertexData;
  37239. };
  37240. // Tools
  37241. /**
  37242. * @param {any} - positions (number[] or Float32Array)
  37243. * @param {any} - indices (number[] or Uint16Array)
  37244. * @param {any} - normals (number[] or Float32Array)
  37245. * options (optional) :
  37246. * facetPositions : optional array of facet positions (vector3)
  37247. * facetNormals : optional array of facet normals (vector3)
  37248. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37249. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37250. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37251. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37252. * bInfo : optional bounding info, required for facetPartitioning computation
  37253. */
  37254. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37255. // temporary scalar variables
  37256. var index = 0; // facet index
  37257. var p1p2x = 0.0; // p1p2 vector x coordinate
  37258. var p1p2y = 0.0; // p1p2 vector y coordinate
  37259. var p1p2z = 0.0; // p1p2 vector z coordinate
  37260. var p3p2x = 0.0; // p3p2 vector x coordinate
  37261. var p3p2y = 0.0; // p3p2 vector y coordinate
  37262. var p3p2z = 0.0; // p3p2 vector z coordinate
  37263. var faceNormalx = 0.0; // facet normal x coordinate
  37264. var faceNormaly = 0.0; // facet normal y coordinate
  37265. var faceNormalz = 0.0; // facet normal z coordinate
  37266. var length = 0.0; // facet normal length before normalization
  37267. var v1x = 0; // vector1 x index in the positions array
  37268. var v1y = 0; // vector1 y index in the positions array
  37269. var v1z = 0; // vector1 z index in the positions array
  37270. var v2x = 0; // vector2 x index in the positions array
  37271. var v2y = 0; // vector2 y index in the positions array
  37272. var v2z = 0; // vector2 z index in the positions array
  37273. var v3x = 0; // vector3 x index in the positions array
  37274. var v3y = 0; // vector3 y index in the positions array
  37275. var v3z = 0; // vector3 z index in the positions array
  37276. var computeFacetNormals = false;
  37277. var computeFacetPositions = false;
  37278. var computeFacetPartitioning = false;
  37279. if (options) {
  37280. computeFacetNormals = (options.facetNormals) ? true : false;
  37281. computeFacetPositions = (options.facetPositions) ? true : false;
  37282. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37283. }
  37284. // facetPartitioning reinit if needed
  37285. if (computeFacetPartitioning) {
  37286. var ox = 0; // X partitioning index for facet position
  37287. var oy = 0; // Y partinioning index for facet position
  37288. var oz = 0; // Z partinioning index for facet position
  37289. var b1x = 0; // X partitioning index for facet v1 vertex
  37290. var b1y = 0; // Y partitioning index for facet v1 vertex
  37291. var b1z = 0; // z partitioning index for facet v1 vertex
  37292. var b2x = 0; // X partitioning index for facet v2 vertex
  37293. var b2y = 0; // Y partitioning index for facet v2 vertex
  37294. var b2z = 0; // Z partitioning index for facet v2 vertex
  37295. var b3x = 0; // X partitioning index for facet v3 vertex
  37296. var b3y = 0; // Y partitioning index for facet v3 vertex
  37297. var b3z = 0; // Z partitioning index for facet v3 vertex
  37298. var block_idx_o = 0; // facet barycenter block index
  37299. var block_idx_v1 = 0; // v1 vertex block index
  37300. var block_idx_v2 = 0; // v2 vertex block index
  37301. var block_idx_v3 = 0; // v3 vertex block index
  37302. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37303. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37304. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  37305. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  37306. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  37307. var subSq = options.subDiv.max * options.subDiv.max;
  37308. options.facetPartitioning.length = 0;
  37309. }
  37310. // reset the normals
  37311. for (index = 0; index < positions.length; index++) {
  37312. normals[index] = 0.0;
  37313. }
  37314. // Loop : 1 indice triplet = 1 facet
  37315. var nbFaces = indices.length / 3;
  37316. for (index = 0; index < nbFaces; index++) {
  37317. // get the indexes of the coordinates of each vertex of the facet
  37318. v1x = indices[index * 3] * 3;
  37319. v1y = v1x + 1;
  37320. v1z = v1x + 2;
  37321. v2x = indices[index * 3 + 1] * 3;
  37322. v2y = v2x + 1;
  37323. v2z = v2x + 2;
  37324. v3x = indices[index * 3 + 2] * 3;
  37325. v3y = v3x + 1;
  37326. v3z = v3x + 2;
  37327. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37328. p1p2y = positions[v1y] - positions[v2y];
  37329. p1p2z = positions[v1z] - positions[v2z];
  37330. p3p2x = positions[v3x] - positions[v2x];
  37331. p3p2y = positions[v3y] - positions[v2y];
  37332. p3p2z = positions[v3z] - positions[v2z];
  37333. // compute the face normal with the cross product
  37334. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  37335. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  37336. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  37337. // normalize this normal and store it in the array facetData
  37338. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37339. length = (length === 0) ? 1.0 : length;
  37340. faceNormalx /= length;
  37341. faceNormaly /= length;
  37342. faceNormalz /= length;
  37343. if (computeFacetNormals) {
  37344. options.facetNormals[index].x = faceNormalx;
  37345. options.facetNormals[index].y = faceNormaly;
  37346. options.facetNormals[index].z = faceNormalz;
  37347. }
  37348. if (computeFacetPositions) {
  37349. // compute and the facet barycenter coordinates in the array facetPositions
  37350. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37351. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37352. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37353. }
  37354. if (computeFacetPartitioning) {
  37355. // store the facet indexes in arrays in the main facetPartitioning array :
  37356. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37357. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37358. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37359. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37360. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37361. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37362. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37363. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37364. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37365. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37366. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37367. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37368. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37369. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37370. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37371. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37372. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37373. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37374. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37375. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37376. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37377. // push each facet index in each block containing the vertex
  37378. options.facetPartitioning[block_idx_v1].push(index);
  37379. if (block_idx_v2 != block_idx_v1) {
  37380. options.facetPartitioning[block_idx_v2].push(index);
  37381. }
  37382. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37383. options.facetPartitioning[block_idx_v3].push(index);
  37384. }
  37385. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37386. options.facetPartitioning[block_idx_o].push(index);
  37387. }
  37388. }
  37389. // compute the normals anyway
  37390. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37391. normals[v1y] += faceNormaly;
  37392. normals[v1z] += faceNormalz;
  37393. normals[v2x] += faceNormalx;
  37394. normals[v2y] += faceNormaly;
  37395. normals[v2z] += faceNormalz;
  37396. normals[v3x] += faceNormalx;
  37397. normals[v3y] += faceNormaly;
  37398. normals[v3z] += faceNormalz;
  37399. }
  37400. // last normalization of each normal
  37401. for (index = 0; index < normals.length / 3; index++) {
  37402. faceNormalx = normals[index * 3];
  37403. faceNormaly = normals[index * 3 + 1];
  37404. faceNormalz = normals[index * 3 + 2];
  37405. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37406. length = (length === 0) ? 1.0 : length;
  37407. faceNormalx /= length;
  37408. faceNormaly /= length;
  37409. faceNormalz /= length;
  37410. normals[index * 3] = faceNormalx;
  37411. normals[index * 3 + 1] = faceNormaly;
  37412. normals[index * 3 + 2] = faceNormalz;
  37413. }
  37414. };
  37415. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  37416. var li = indices.length;
  37417. var ln = normals.length;
  37418. var i;
  37419. var n;
  37420. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37421. switch (sideOrientation) {
  37422. case BABYLON.Mesh.FRONTSIDE:
  37423. // nothing changed
  37424. break;
  37425. case BABYLON.Mesh.BACKSIDE:
  37426. var tmp;
  37427. // indices
  37428. for (i = 0; i < li; i += 3) {
  37429. tmp = indices[i];
  37430. indices[i] = indices[i + 2];
  37431. indices[i + 2] = tmp;
  37432. }
  37433. // normals
  37434. for (n = 0; n < ln; n++) {
  37435. normals[n] = -normals[n];
  37436. }
  37437. break;
  37438. case BABYLON.Mesh.DOUBLESIDE:
  37439. // positions
  37440. var lp = positions.length;
  37441. var l = lp / 3;
  37442. for (var p = 0; p < lp; p++) {
  37443. positions[lp + p] = positions[p];
  37444. }
  37445. // indices
  37446. for (i = 0; i < li; i += 3) {
  37447. indices[i + li] = indices[i + 2] + l;
  37448. indices[i + 1 + li] = indices[i + 1] + l;
  37449. indices[i + 2 + li] = indices[i] + l;
  37450. }
  37451. // normals
  37452. for (n = 0; n < ln; n++) {
  37453. normals[ln + n] = -normals[n];
  37454. }
  37455. // uvs
  37456. var lu = uvs.length;
  37457. for (var u = 0; u < lu; u++) {
  37458. uvs[u + lu] = uvs[u];
  37459. }
  37460. break;
  37461. }
  37462. };
  37463. /**
  37464. * Creates a new VertexData from the imported parameters.
  37465. */
  37466. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37467. var vertexData = new VertexData();
  37468. // positions
  37469. var positions = parsedVertexData.positions;
  37470. if (positions) {
  37471. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37472. }
  37473. // normals
  37474. var normals = parsedVertexData.normals;
  37475. if (normals) {
  37476. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37477. }
  37478. // uvs
  37479. var uvs = parsedVertexData.uvs;
  37480. if (uvs) {
  37481. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37482. }
  37483. // uv2s
  37484. var uv2s = parsedVertexData.uv2s;
  37485. if (uv2s) {
  37486. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37487. }
  37488. // uv3s
  37489. var uv3s = parsedVertexData.uv3s;
  37490. if (uv3s) {
  37491. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37492. }
  37493. // uv4s
  37494. var uv4s = parsedVertexData.uv4s;
  37495. if (uv4s) {
  37496. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37497. }
  37498. // uv5s
  37499. var uv5s = parsedVertexData.uv5s;
  37500. if (uv5s) {
  37501. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37502. }
  37503. // uv6s
  37504. var uv6s = parsedVertexData.uv6s;
  37505. if (uv6s) {
  37506. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37507. }
  37508. // colors
  37509. var colors = parsedVertexData.colors;
  37510. if (colors) {
  37511. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37512. }
  37513. // matricesIndices
  37514. var matricesIndices = parsedVertexData.matricesIndices;
  37515. if (matricesIndices) {
  37516. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37517. }
  37518. // matricesWeights
  37519. var matricesWeights = parsedVertexData.matricesWeights;
  37520. if (matricesWeights) {
  37521. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37522. }
  37523. // indices
  37524. var indices = parsedVertexData.indices;
  37525. if (indices) {
  37526. vertexData.indices = indices;
  37527. }
  37528. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37529. };
  37530. return VertexData;
  37531. }());
  37532. BABYLON.VertexData = VertexData;
  37533. })(BABYLON || (BABYLON = {}));
  37534. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37535. var BABYLON;
  37536. (function (BABYLON) {
  37537. var Tags = (function () {
  37538. function Tags() {
  37539. }
  37540. Tags.EnableFor = function (obj) {
  37541. obj._tags = obj._tags || {};
  37542. obj.hasTags = function () {
  37543. return Tags.HasTags(obj);
  37544. };
  37545. obj.addTags = function (tagsString) {
  37546. return Tags.AddTagsTo(obj, tagsString);
  37547. };
  37548. obj.removeTags = function (tagsString) {
  37549. return Tags.RemoveTagsFrom(obj, tagsString);
  37550. };
  37551. obj.matchesTagsQuery = function (tagsQuery) {
  37552. return Tags.MatchesQuery(obj, tagsQuery);
  37553. };
  37554. };
  37555. Tags.DisableFor = function (obj) {
  37556. delete obj._tags;
  37557. delete obj.hasTags;
  37558. delete obj.addTags;
  37559. delete obj.removeTags;
  37560. delete obj.matchesTagsQuery;
  37561. };
  37562. Tags.HasTags = function (obj) {
  37563. if (!obj._tags) {
  37564. return false;
  37565. }
  37566. return !BABYLON.Tools.IsEmpty(obj._tags);
  37567. };
  37568. Tags.GetTags = function (obj, asString) {
  37569. if (asString === void 0) { asString = true; }
  37570. if (!obj._tags) {
  37571. return null;
  37572. }
  37573. if (asString) {
  37574. var tagsArray = [];
  37575. for (var tag in obj._tags) {
  37576. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  37577. tagsArray.push(tag);
  37578. }
  37579. }
  37580. return tagsArray.join(" ");
  37581. }
  37582. else {
  37583. return obj._tags;
  37584. }
  37585. };
  37586. // the tags 'true' and 'false' are reserved and cannot be used as tags
  37587. // a tag cannot start with '||', '&&', and '!'
  37588. // it cannot contain whitespaces
  37589. Tags.AddTagsTo = function (obj, tagsString) {
  37590. if (!tagsString) {
  37591. return;
  37592. }
  37593. if (typeof tagsString !== "string") {
  37594. return;
  37595. }
  37596. var tags = tagsString.split(" ");
  37597. tags.forEach(function (tag, index, array) {
  37598. Tags._AddTagTo(obj, tag);
  37599. });
  37600. };
  37601. Tags._AddTagTo = function (obj, tag) {
  37602. tag = tag.trim();
  37603. if (tag === "" || tag === "true" || tag === "false") {
  37604. return;
  37605. }
  37606. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  37607. return;
  37608. }
  37609. Tags.EnableFor(obj);
  37610. obj._tags[tag] = true;
  37611. };
  37612. Tags.RemoveTagsFrom = function (obj, tagsString) {
  37613. if (!Tags.HasTags(obj)) {
  37614. return;
  37615. }
  37616. var tags = tagsString.split(" ");
  37617. for (var t in tags) {
  37618. Tags._RemoveTagFrom(obj, tags[t]);
  37619. }
  37620. };
  37621. Tags._RemoveTagFrom = function (obj, tag) {
  37622. delete obj._tags[tag];
  37623. };
  37624. Tags.MatchesQuery = function (obj, tagsQuery) {
  37625. if (tagsQuery === undefined) {
  37626. return true;
  37627. }
  37628. if (tagsQuery === "") {
  37629. return Tags.HasTags(obj);
  37630. }
  37631. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  37632. };
  37633. return Tags;
  37634. }());
  37635. BABYLON.Tags = Tags;
  37636. })(BABYLON || (BABYLON = {}));
  37637. //# sourceMappingURL=babylon.tags.js.map
  37638. var BABYLON;
  37639. (function (BABYLON) {
  37640. var Internals;
  37641. (function (Internals) {
  37642. var AndOrNotEvaluator = (function () {
  37643. function AndOrNotEvaluator() {
  37644. }
  37645. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  37646. if (!query.match(/\([^\(\)]*\)/g)) {
  37647. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  37648. }
  37649. else {
  37650. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  37651. // remove parenthesis
  37652. r = r.slice(1, r.length - 1);
  37653. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  37654. });
  37655. }
  37656. if (query === "true") {
  37657. return true;
  37658. }
  37659. if (query === "false") {
  37660. return false;
  37661. }
  37662. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  37663. };
  37664. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  37665. evaluateCallback = evaluateCallback || (function (r) {
  37666. return r === "true" ? true : false;
  37667. });
  37668. var result;
  37669. var or = parenthesisContent.split("||");
  37670. for (var i in or) {
  37671. if (or.hasOwnProperty(i)) {
  37672. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  37673. var and = ori.split("&&");
  37674. if (and.length > 1) {
  37675. for (var j = 0; j < and.length; ++j) {
  37676. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  37677. if (andj !== "true" && andj !== "false") {
  37678. if (andj[0] === "!") {
  37679. result = !evaluateCallback(andj.substring(1));
  37680. }
  37681. else {
  37682. result = evaluateCallback(andj);
  37683. }
  37684. }
  37685. else {
  37686. result = andj === "true" ? true : false;
  37687. }
  37688. if (!result) {
  37689. ori = "false";
  37690. break;
  37691. }
  37692. }
  37693. }
  37694. if (result || ori === "true") {
  37695. result = true;
  37696. break;
  37697. }
  37698. // result equals false (or undefined)
  37699. if (ori !== "true" && ori !== "false") {
  37700. if (ori[0] === "!") {
  37701. result = !evaluateCallback(ori.substring(1));
  37702. }
  37703. else {
  37704. result = evaluateCallback(ori);
  37705. }
  37706. }
  37707. else {
  37708. result = ori === "true" ? true : false;
  37709. }
  37710. }
  37711. }
  37712. // the whole parenthesis scope is replaced by 'true' or 'false'
  37713. return result ? "true" : "false";
  37714. };
  37715. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  37716. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  37717. // remove whitespaces
  37718. r = r.replace(/[\s]/g, function () { return ""; });
  37719. return r.length % 2 ? "!" : "";
  37720. });
  37721. booleanString = booleanString.trim();
  37722. if (booleanString === "!true") {
  37723. booleanString = "false";
  37724. }
  37725. else if (booleanString === "!false") {
  37726. booleanString = "true";
  37727. }
  37728. return booleanString;
  37729. };
  37730. return AndOrNotEvaluator;
  37731. }());
  37732. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  37733. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37734. })(BABYLON || (BABYLON = {}));
  37735. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  37736. var BABYLON;
  37737. (function (BABYLON) {
  37738. var PostProcessRenderPass = (function () {
  37739. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  37740. this._enabled = true;
  37741. this._refCount = 0;
  37742. this._name = name;
  37743. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  37744. this.setRenderList(renderList);
  37745. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  37746. this._renderTexture.onAfterRenderObservable.add(afterRender);
  37747. this._scene = scene;
  37748. this._renderList = renderList;
  37749. }
  37750. // private
  37751. PostProcessRenderPass.prototype._incRefCount = function () {
  37752. if (this._refCount === 0) {
  37753. this._scene.customRenderTargets.push(this._renderTexture);
  37754. }
  37755. return ++this._refCount;
  37756. };
  37757. PostProcessRenderPass.prototype._decRefCount = function () {
  37758. this._refCount--;
  37759. if (this._refCount <= 0) {
  37760. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  37761. }
  37762. return this._refCount;
  37763. };
  37764. PostProcessRenderPass.prototype._update = function () {
  37765. this.setRenderList(this._renderList);
  37766. };
  37767. // public
  37768. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  37769. this._renderTexture.renderList = renderList;
  37770. };
  37771. PostProcessRenderPass.prototype.getRenderTexture = function () {
  37772. return this._renderTexture;
  37773. };
  37774. return PostProcessRenderPass;
  37775. }());
  37776. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  37777. })(BABYLON || (BABYLON = {}));
  37778. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  37779. var BABYLON;
  37780. (function (BABYLON) {
  37781. var PostProcessRenderEffect = (function () {
  37782. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  37783. this._engine = engine;
  37784. this._name = name;
  37785. this._singleInstance = singleInstance || true;
  37786. this._getPostProcess = getPostProcess;
  37787. this._cameras = [];
  37788. this._indicesForCamera = [];
  37789. this._postProcesses = {};
  37790. this._renderPasses = {};
  37791. this._renderEffectAsPasses = {};
  37792. }
  37793. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  37794. get: function () {
  37795. for (var index in this._postProcesses) {
  37796. if (!this._postProcesses[index].isSupported) {
  37797. return false;
  37798. }
  37799. }
  37800. return true;
  37801. },
  37802. enumerable: true,
  37803. configurable: true
  37804. });
  37805. PostProcessRenderEffect.prototype._update = function () {
  37806. for (var renderPassName in this._renderPasses) {
  37807. this._renderPasses[renderPassName]._update();
  37808. }
  37809. };
  37810. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  37811. this._renderPasses[renderPass._name] = renderPass;
  37812. this._linkParameters();
  37813. };
  37814. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  37815. delete this._renderPasses[renderPass._name];
  37816. this._linkParameters();
  37817. };
  37818. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  37819. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  37820. this._linkParameters();
  37821. };
  37822. PostProcessRenderEffect.prototype.getPass = function (passName) {
  37823. for (var renderPassName in this._renderPasses) {
  37824. if (renderPassName === passName) {
  37825. return this._renderPasses[passName];
  37826. }
  37827. }
  37828. };
  37829. PostProcessRenderEffect.prototype.emptyPasses = function () {
  37830. this._renderPasses = {};
  37831. this._linkParameters();
  37832. };
  37833. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  37834. var cameraKey;
  37835. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37836. for (var i = 0; i < _cam.length; i++) {
  37837. var camera = _cam[i];
  37838. var cameraName = camera.name;
  37839. if (this._singleInstance) {
  37840. cameraKey = 0;
  37841. }
  37842. else {
  37843. cameraKey = cameraName;
  37844. }
  37845. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  37846. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  37847. if (!this._indicesForCamera[cameraName]) {
  37848. this._indicesForCamera[cameraName] = [];
  37849. }
  37850. this._indicesForCamera[cameraName].push(index);
  37851. if (this._cameras.indexOf(camera) === -1) {
  37852. this._cameras[cameraName] = camera;
  37853. }
  37854. for (var passName in this._renderPasses) {
  37855. this._renderPasses[passName]._incRefCount();
  37856. }
  37857. }
  37858. this._linkParameters();
  37859. };
  37860. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  37861. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37862. for (var i = 0; i < _cam.length; i++) {
  37863. var camera = _cam[i];
  37864. var cameraName = camera.name;
  37865. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37866. var index = this._cameras.indexOf(cameraName);
  37867. this._indicesForCamera.splice(index, 1);
  37868. this._cameras.splice(index, 1);
  37869. for (var passName in this._renderPasses) {
  37870. this._renderPasses[passName]._decRefCount();
  37871. }
  37872. }
  37873. };
  37874. PostProcessRenderEffect.prototype._enable = function (cameras) {
  37875. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37876. for (var i = 0; i < _cam.length; i++) {
  37877. var camera = _cam[i];
  37878. var cameraName = camera.name;
  37879. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  37880. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  37881. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  37882. }
  37883. }
  37884. for (var passName in this._renderPasses) {
  37885. this._renderPasses[passName]._incRefCount();
  37886. }
  37887. }
  37888. };
  37889. PostProcessRenderEffect.prototype._disable = function (cameras) {
  37890. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37891. for (var i = 0; i < _cam.length; i++) {
  37892. var camera = _cam[i];
  37893. var cameraName = camera.Name;
  37894. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37895. for (var passName in this._renderPasses) {
  37896. this._renderPasses[passName]._decRefCount();
  37897. }
  37898. }
  37899. };
  37900. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  37901. if (this._singleInstance) {
  37902. return this._postProcesses[0];
  37903. }
  37904. else {
  37905. return this._postProcesses[camera.name];
  37906. }
  37907. };
  37908. PostProcessRenderEffect.prototype._linkParameters = function () {
  37909. var _this = this;
  37910. for (var index in this._postProcesses) {
  37911. if (this.applyParameters) {
  37912. this.applyParameters(this._postProcesses[index]);
  37913. }
  37914. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  37915. _this._linkTextures(effect);
  37916. });
  37917. }
  37918. };
  37919. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  37920. for (var renderPassName in this._renderPasses) {
  37921. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  37922. }
  37923. for (var renderEffectName in this._renderEffectAsPasses) {
  37924. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  37925. }
  37926. };
  37927. return PostProcessRenderEffect;
  37928. }());
  37929. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  37930. })(BABYLON || (BABYLON = {}));
  37931. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  37932. var BABYLON;
  37933. (function (BABYLON) {
  37934. var PostProcessRenderPipeline = (function () {
  37935. function PostProcessRenderPipeline(engine, name) {
  37936. this._engine = engine;
  37937. this._name = name;
  37938. this._renderEffects = {};
  37939. this._renderEffectsForIsolatedPass = {};
  37940. this._cameras = [];
  37941. }
  37942. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  37943. get: function () {
  37944. for (var renderEffectName in this._renderEffects) {
  37945. if (!this._renderEffects[renderEffectName].isSupported) {
  37946. return false;
  37947. }
  37948. }
  37949. return true;
  37950. },
  37951. enumerable: true,
  37952. configurable: true
  37953. });
  37954. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  37955. this._renderEffects[renderEffect._name] = renderEffect;
  37956. };
  37957. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  37958. var renderEffects = this._renderEffects[renderEffectName];
  37959. if (!renderEffects) {
  37960. return;
  37961. }
  37962. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  37963. };
  37964. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  37965. var renderEffects = this._renderEffects[renderEffectName];
  37966. if (!renderEffects) {
  37967. return;
  37968. }
  37969. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  37970. };
  37971. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  37972. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37973. var indicesToDelete = [];
  37974. var i;
  37975. for (i = 0; i < _cam.length; i++) {
  37976. var camera = _cam[i];
  37977. var cameraName = camera.name;
  37978. if (this._cameras.indexOf(camera) === -1) {
  37979. this._cameras[cameraName] = camera;
  37980. }
  37981. else if (unique) {
  37982. indicesToDelete.push(i);
  37983. }
  37984. }
  37985. for (i = 0; i < indicesToDelete.length; i++) {
  37986. cameras.splice(indicesToDelete[i], 1);
  37987. }
  37988. for (var renderEffectName in this._renderEffects) {
  37989. this._renderEffects[renderEffectName]._attachCameras(_cam);
  37990. }
  37991. };
  37992. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  37993. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37994. for (var renderEffectName in this._renderEffects) {
  37995. this._renderEffects[renderEffectName]._detachCameras(_cam);
  37996. }
  37997. for (var i = 0; i < _cam.length; i++) {
  37998. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  37999. }
  38000. };
  38001. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  38002. var _this = this;
  38003. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38004. var pass = null;
  38005. var renderEffectName;
  38006. for (renderEffectName in this._renderEffects) {
  38007. pass = this._renderEffects[renderEffectName].getPass(passName);
  38008. if (pass != null) {
  38009. break;
  38010. }
  38011. }
  38012. if (pass === null) {
  38013. return;
  38014. }
  38015. for (renderEffectName in this._renderEffects) {
  38016. this._renderEffects[renderEffectName]._disable(_cam);
  38017. }
  38018. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  38019. for (var i = 0; i < _cam.length; i++) {
  38020. var camera = _cam[i];
  38021. var cameraName = camera.name;
  38022. 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); });
  38023. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  38024. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  38025. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  38026. }
  38027. };
  38028. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  38029. var _this = this;
  38030. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38031. for (var i = 0; i < _cam.length; i++) {
  38032. var camera = _cam[i];
  38033. var cameraName = camera.name;
  38034. 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); });
  38035. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  38036. }
  38037. for (var renderEffectName in this._renderEffects) {
  38038. this._renderEffects[renderEffectName]._enable(_cam);
  38039. }
  38040. };
  38041. PostProcessRenderPipeline.prototype._update = function () {
  38042. for (var renderEffectName in this._renderEffects) {
  38043. this._renderEffects[renderEffectName]._update();
  38044. }
  38045. for (var i = 0; i < this._cameras.length; i++) {
  38046. var cameraName = this._cameras[i].name;
  38047. if (this._renderEffectsForIsolatedPass[cameraName]) {
  38048. this._renderEffectsForIsolatedPass[cameraName]._update();
  38049. }
  38050. }
  38051. };
  38052. PostProcessRenderPipeline.prototype.dispose = function () {
  38053. // Must be implemented by children
  38054. };
  38055. return PostProcessRenderPipeline;
  38056. }());
  38057. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  38058. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  38059. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  38060. })(BABYLON || (BABYLON = {}));
  38061. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  38062. var BABYLON;
  38063. (function (BABYLON) {
  38064. var PostProcessRenderPipelineManager = (function () {
  38065. function PostProcessRenderPipelineManager() {
  38066. this._renderPipelines = {};
  38067. }
  38068. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  38069. this._renderPipelines[renderPipeline._name] = renderPipeline;
  38070. };
  38071. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  38072. var renderPipeline = this._renderPipelines[renderPipelineName];
  38073. if (!renderPipeline) {
  38074. return;
  38075. }
  38076. renderPipeline._attachCameras(cameras, unique);
  38077. };
  38078. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  38079. var renderPipeline = this._renderPipelines[renderPipelineName];
  38080. if (!renderPipeline) {
  38081. return;
  38082. }
  38083. renderPipeline._detachCameras(cameras);
  38084. };
  38085. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38086. var renderPipeline = this._renderPipelines[renderPipelineName];
  38087. if (!renderPipeline) {
  38088. return;
  38089. }
  38090. renderPipeline._enableEffect(renderEffectName, cameras);
  38091. };
  38092. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38093. var renderPipeline = this._renderPipelines[renderPipelineName];
  38094. if (!renderPipeline) {
  38095. return;
  38096. }
  38097. renderPipeline._disableEffect(renderEffectName, cameras);
  38098. };
  38099. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  38100. var renderPipeline = this._renderPipelines[renderPipelineName];
  38101. if (!renderPipeline) {
  38102. return;
  38103. }
  38104. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  38105. };
  38106. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  38107. var renderPipeline = this._renderPipelines[renderPipelineName];
  38108. if (!renderPipeline) {
  38109. return;
  38110. }
  38111. renderPipeline._disableDisplayOnlyPass(cameras);
  38112. };
  38113. PostProcessRenderPipelineManager.prototype.update = function () {
  38114. for (var renderPipelineName in this._renderPipelines) {
  38115. var pipeline = this._renderPipelines[renderPipelineName];
  38116. if (!pipeline.isSupported) {
  38117. pipeline.dispose();
  38118. delete this._renderPipelines[renderPipelineName];
  38119. }
  38120. else {
  38121. pipeline._update();
  38122. }
  38123. }
  38124. };
  38125. return PostProcessRenderPipelineManager;
  38126. }());
  38127. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  38128. })(BABYLON || (BABYLON = {}));
  38129. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  38130. var BABYLON;
  38131. (function (BABYLON) {
  38132. var BoundingBoxRenderer = (function () {
  38133. function BoundingBoxRenderer(scene) {
  38134. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38135. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38136. this.showBackLines = true;
  38137. this.renderList = new BABYLON.SmartArray(32);
  38138. this._vertexBuffers = {};
  38139. this._scene = scene;
  38140. }
  38141. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38142. if (this._colorShader) {
  38143. return;
  38144. }
  38145. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38146. attributes: [BABYLON.VertexBuffer.PositionKind],
  38147. uniforms: ["worldViewProjection", "color"]
  38148. });
  38149. var engine = this._scene.getEngine();
  38150. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38151. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38152. 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]);
  38153. };
  38154. BoundingBoxRenderer.prototype.reset = function () {
  38155. this.renderList.reset();
  38156. };
  38157. BoundingBoxRenderer.prototype.render = function () {
  38158. if (this.renderList.length === 0) {
  38159. return;
  38160. }
  38161. this._prepareRessources();
  38162. if (!this._colorShader.isReady()) {
  38163. return;
  38164. }
  38165. var engine = this._scene.getEngine();
  38166. engine.setDepthWrite(false);
  38167. this._colorShader._preBind();
  38168. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38169. var boundingBox = this.renderList.data[boundingBoxIndex];
  38170. var min = boundingBox.minimum;
  38171. var max = boundingBox.maximum;
  38172. var diff = max.subtract(min);
  38173. var median = min.add(diff.scale(0.5));
  38174. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38175. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38176. .multiply(boundingBox.getWorldMatrix());
  38177. // VBOs
  38178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38179. if (this.showBackLines) {
  38180. // Back
  38181. engine.setDepthFunctionToGreaterOrEqual();
  38182. this._scene.resetCachedMaterial();
  38183. this._colorShader.setColor4("color", this.backColor.toColor4());
  38184. this._colorShader.bind(worldMatrix);
  38185. // Draw order
  38186. engine.draw(false, 0, 24);
  38187. }
  38188. // Front
  38189. engine.setDepthFunctionToLess();
  38190. this._scene.resetCachedMaterial();
  38191. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38192. this._colorShader.bind(worldMatrix);
  38193. // Draw order
  38194. engine.draw(false, 0, 24);
  38195. }
  38196. this._colorShader.unbind();
  38197. engine.setDepthFunctionToLessOrEqual();
  38198. engine.setDepthWrite(true);
  38199. };
  38200. BoundingBoxRenderer.prototype.dispose = function () {
  38201. if (!this._colorShader) {
  38202. return;
  38203. }
  38204. this._colorShader.dispose();
  38205. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38206. if (buffer) {
  38207. buffer.dispose();
  38208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38209. }
  38210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38211. };
  38212. return BoundingBoxRenderer;
  38213. }());
  38214. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38215. })(BABYLON || (BABYLON = {}));
  38216. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38217. var BABYLON;
  38218. (function (BABYLON) {
  38219. var Condition = (function () {
  38220. function Condition(actionManager) {
  38221. this._actionManager = actionManager;
  38222. }
  38223. Condition.prototype.isValid = function () {
  38224. return true;
  38225. };
  38226. Condition.prototype._getProperty = function (propertyPath) {
  38227. return this._actionManager._getProperty(propertyPath);
  38228. };
  38229. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38230. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38231. };
  38232. Condition.prototype.serialize = function () {
  38233. };
  38234. Condition.prototype._serialize = function (serializedCondition) {
  38235. return {
  38236. type: 2,
  38237. children: [],
  38238. name: serializedCondition.name,
  38239. properties: serializedCondition.properties
  38240. };
  38241. };
  38242. return Condition;
  38243. }());
  38244. BABYLON.Condition = Condition;
  38245. var ValueCondition = (function (_super) {
  38246. __extends(ValueCondition, _super);
  38247. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38248. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38249. var _this = _super.call(this, actionManager) || this;
  38250. _this.propertyPath = propertyPath;
  38251. _this.value = value;
  38252. _this.operator = operator;
  38253. _this._target = target;
  38254. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38255. _this._property = _this._getProperty(_this.propertyPath);
  38256. return _this;
  38257. }
  38258. Object.defineProperty(ValueCondition, "IsEqual", {
  38259. get: function () {
  38260. return ValueCondition._IsEqual;
  38261. },
  38262. enumerable: true,
  38263. configurable: true
  38264. });
  38265. Object.defineProperty(ValueCondition, "IsDifferent", {
  38266. get: function () {
  38267. return ValueCondition._IsDifferent;
  38268. },
  38269. enumerable: true,
  38270. configurable: true
  38271. });
  38272. Object.defineProperty(ValueCondition, "IsGreater", {
  38273. get: function () {
  38274. return ValueCondition._IsGreater;
  38275. },
  38276. enumerable: true,
  38277. configurable: true
  38278. });
  38279. Object.defineProperty(ValueCondition, "IsLesser", {
  38280. get: function () {
  38281. return ValueCondition._IsLesser;
  38282. },
  38283. enumerable: true,
  38284. configurable: true
  38285. });
  38286. // Methods
  38287. ValueCondition.prototype.isValid = function () {
  38288. switch (this.operator) {
  38289. case ValueCondition.IsGreater:
  38290. return this._effectiveTarget[this._property] > this.value;
  38291. case ValueCondition.IsLesser:
  38292. return this._effectiveTarget[this._property] < this.value;
  38293. case ValueCondition.IsEqual:
  38294. case ValueCondition.IsDifferent:
  38295. var check;
  38296. if (this.value.equals) {
  38297. check = this.value.equals(this._effectiveTarget[this._property]);
  38298. }
  38299. else {
  38300. check = this.value === this._effectiveTarget[this._property];
  38301. }
  38302. return this.operator === ValueCondition.IsEqual ? check : !check;
  38303. }
  38304. return false;
  38305. };
  38306. ValueCondition.prototype.serialize = function () {
  38307. return this._serialize({
  38308. name: "ValueCondition",
  38309. properties: [
  38310. BABYLON.Action._GetTargetProperty(this._target),
  38311. { name: "propertyPath", value: this.propertyPath },
  38312. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38313. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38314. ]
  38315. });
  38316. };
  38317. ValueCondition.GetOperatorName = function (operator) {
  38318. switch (operator) {
  38319. case ValueCondition._IsEqual: return "IsEqual";
  38320. case ValueCondition._IsDifferent: return "IsDifferent";
  38321. case ValueCondition._IsGreater: return "IsGreater";
  38322. case ValueCondition._IsLesser: return "IsLesser";
  38323. default: return "";
  38324. }
  38325. };
  38326. return ValueCondition;
  38327. }(Condition));
  38328. // Statics
  38329. ValueCondition._IsEqual = 0;
  38330. ValueCondition._IsDifferent = 1;
  38331. ValueCondition._IsGreater = 2;
  38332. ValueCondition._IsLesser = 3;
  38333. BABYLON.ValueCondition = ValueCondition;
  38334. var PredicateCondition = (function (_super) {
  38335. __extends(PredicateCondition, _super);
  38336. function PredicateCondition(actionManager, predicate) {
  38337. var _this = _super.call(this, actionManager) || this;
  38338. _this.predicate = predicate;
  38339. return _this;
  38340. }
  38341. PredicateCondition.prototype.isValid = function () {
  38342. return this.predicate();
  38343. };
  38344. return PredicateCondition;
  38345. }(Condition));
  38346. BABYLON.PredicateCondition = PredicateCondition;
  38347. var StateCondition = (function (_super) {
  38348. __extends(StateCondition, _super);
  38349. function StateCondition(actionManager, target, value) {
  38350. var _this = _super.call(this, actionManager) || this;
  38351. _this.value = value;
  38352. _this._target = target;
  38353. return _this;
  38354. }
  38355. // Methods
  38356. StateCondition.prototype.isValid = function () {
  38357. return this._target.state === this.value;
  38358. };
  38359. StateCondition.prototype.serialize = function () {
  38360. return this._serialize({
  38361. name: "StateCondition",
  38362. properties: [
  38363. BABYLON.Action._GetTargetProperty(this._target),
  38364. { name: "value", value: this.value }
  38365. ]
  38366. });
  38367. };
  38368. return StateCondition;
  38369. }(Condition));
  38370. BABYLON.StateCondition = StateCondition;
  38371. })(BABYLON || (BABYLON = {}));
  38372. //# sourceMappingURL=babylon.condition.js.map
  38373. var BABYLON;
  38374. (function (BABYLON) {
  38375. var Action = (function () {
  38376. function Action(triggerOptions, condition) {
  38377. this.triggerOptions = triggerOptions;
  38378. if (triggerOptions.parameter) {
  38379. this.trigger = triggerOptions.trigger;
  38380. this._triggerParameter = triggerOptions.parameter;
  38381. }
  38382. else {
  38383. this.trigger = triggerOptions;
  38384. }
  38385. this._nextActiveAction = this;
  38386. this._condition = condition;
  38387. }
  38388. // Methods
  38389. Action.prototype._prepare = function () {
  38390. };
  38391. Action.prototype.getTriggerParameter = function () {
  38392. return this._triggerParameter;
  38393. };
  38394. Action.prototype._executeCurrent = function (evt) {
  38395. if (this._nextActiveAction._condition) {
  38396. var condition = this._nextActiveAction._condition;
  38397. var currentRenderId = this._actionManager.getScene().getRenderId();
  38398. // We cache the current evaluation for the current frame
  38399. if (condition._evaluationId === currentRenderId) {
  38400. if (!condition._currentResult) {
  38401. return;
  38402. }
  38403. }
  38404. else {
  38405. condition._evaluationId = currentRenderId;
  38406. if (!condition.isValid()) {
  38407. condition._currentResult = false;
  38408. return;
  38409. }
  38410. condition._currentResult = true;
  38411. }
  38412. }
  38413. this._nextActiveAction.execute(evt);
  38414. this.skipToNextActiveAction();
  38415. };
  38416. Action.prototype.execute = function (evt) {
  38417. };
  38418. Action.prototype.skipToNextActiveAction = function () {
  38419. if (this._nextActiveAction._child) {
  38420. if (!this._nextActiveAction._child._actionManager) {
  38421. this._nextActiveAction._child._actionManager = this._actionManager;
  38422. }
  38423. this._nextActiveAction = this._nextActiveAction._child;
  38424. }
  38425. else {
  38426. this._nextActiveAction = this;
  38427. }
  38428. };
  38429. Action.prototype.then = function (action) {
  38430. this._child = action;
  38431. action._actionManager = this._actionManager;
  38432. action._prepare();
  38433. return action;
  38434. };
  38435. Action.prototype._getProperty = function (propertyPath) {
  38436. return this._actionManager._getProperty(propertyPath);
  38437. };
  38438. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38439. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38440. };
  38441. Action.prototype.serialize = function (parent) {
  38442. };
  38443. // Called by BABYLON.Action objects in serialize(...). Internal use
  38444. Action.prototype._serialize = function (serializedAction, parent) {
  38445. var serializationObject = {
  38446. type: 1,
  38447. children: [],
  38448. name: serializedAction.name,
  38449. properties: serializedAction.properties || []
  38450. };
  38451. // Serialize child
  38452. if (this._child) {
  38453. this._child.serialize(serializationObject);
  38454. }
  38455. // Check if "this" has a condition
  38456. if (this._condition) {
  38457. var serializedCondition = this._condition.serialize();
  38458. serializedCondition.children.push(serializationObject);
  38459. if (parent) {
  38460. parent.children.push(serializedCondition);
  38461. }
  38462. return serializedCondition;
  38463. }
  38464. if (parent) {
  38465. parent.children.push(serializationObject);
  38466. }
  38467. return serializationObject;
  38468. };
  38469. return Action;
  38470. }());
  38471. Action._SerializeValueAsString = function (value) {
  38472. if (typeof value === "number") {
  38473. return value.toString();
  38474. }
  38475. if (typeof value === "boolean") {
  38476. return value ? "true" : "false";
  38477. }
  38478. if (value instanceof BABYLON.Vector2) {
  38479. return value.x + ", " + value.y;
  38480. }
  38481. if (value instanceof BABYLON.Vector3) {
  38482. return value.x + ", " + value.y + ", " + value.z;
  38483. }
  38484. if (value instanceof BABYLON.Color3) {
  38485. return value.r + ", " + value.g + ", " + value.b;
  38486. }
  38487. if (value instanceof BABYLON.Color4) {
  38488. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38489. }
  38490. return value; // string
  38491. };
  38492. Action._GetTargetProperty = function (target) {
  38493. return {
  38494. name: "target",
  38495. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38496. : target instanceof BABYLON.Light ? "LightProperties"
  38497. : target instanceof BABYLON.Camera ? "CameraProperties"
  38498. : "SceneProperties",
  38499. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38500. };
  38501. };
  38502. BABYLON.Action = Action;
  38503. })(BABYLON || (BABYLON = {}));
  38504. //# sourceMappingURL=babylon.action.js.map
  38505. var BABYLON;
  38506. (function (BABYLON) {
  38507. /**
  38508. * ActionEvent is the event beint sent when an action is triggered.
  38509. */
  38510. var ActionEvent = (function () {
  38511. /**
  38512. * @constructor
  38513. * @param source The mesh or sprite that triggered the action.
  38514. * @param pointerX The X mouse cursor position at the time of the event
  38515. * @param pointerY The Y mouse cursor position at the time of the event
  38516. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38517. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38518. */
  38519. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38520. this.source = source;
  38521. this.pointerX = pointerX;
  38522. this.pointerY = pointerY;
  38523. this.meshUnderPointer = meshUnderPointer;
  38524. this.sourceEvent = sourceEvent;
  38525. this.additionalData = additionalData;
  38526. }
  38527. /**
  38528. * Helper function to auto-create an ActionEvent from a source mesh.
  38529. * @param source The source mesh that triggered the event
  38530. * @param evt {Event} The original (browser) event
  38531. */
  38532. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38533. var scene = source.getScene();
  38534. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38535. };
  38536. /**
  38537. * Helper function to auto-create an ActionEvent from a source mesh.
  38538. * @param source The source sprite that triggered the event
  38539. * @param scene Scene associated with the sprite
  38540. * @param evt {Event} The original (browser) event
  38541. */
  38542. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38543. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38544. };
  38545. /**
  38546. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38547. * @param scene the scene where the event occurred
  38548. * @param evt {Event} The original (browser) event
  38549. */
  38550. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38551. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38552. };
  38553. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38554. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38555. };
  38556. return ActionEvent;
  38557. }());
  38558. BABYLON.ActionEvent = ActionEvent;
  38559. /**
  38560. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38561. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38562. */
  38563. var ActionManager = (function () {
  38564. function ActionManager(scene) {
  38565. // Members
  38566. this.actions = new Array();
  38567. this.hoverCursor = '';
  38568. this._scene = scene;
  38569. scene._actionManagers.push(this);
  38570. }
  38571. Object.defineProperty(ActionManager, "NothingTrigger", {
  38572. get: function () {
  38573. return ActionManager._NothingTrigger;
  38574. },
  38575. enumerable: true,
  38576. configurable: true
  38577. });
  38578. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38579. get: function () {
  38580. return ActionManager._OnPickTrigger;
  38581. },
  38582. enumerable: true,
  38583. configurable: true
  38584. });
  38585. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38586. get: function () {
  38587. return ActionManager._OnLeftPickTrigger;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38593. get: function () {
  38594. return ActionManager._OnRightPickTrigger;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38600. get: function () {
  38601. return ActionManager._OnCenterPickTrigger;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38607. get: function () {
  38608. return ActionManager._OnPickDownTrigger;
  38609. },
  38610. enumerable: true,
  38611. configurable: true
  38612. });
  38613. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38614. get: function () {
  38615. return ActionManager._OnPickUpTrigger;
  38616. },
  38617. enumerable: true,
  38618. configurable: true
  38619. });
  38620. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38621. /// This trigger will only be raised if you also declared a OnPickDown
  38622. get: function () {
  38623. return ActionManager._OnPickOutTrigger;
  38624. },
  38625. enumerable: true,
  38626. configurable: true
  38627. });
  38628. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38629. get: function () {
  38630. return ActionManager._OnLongPressTrigger;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38636. get: function () {
  38637. return ActionManager._OnPointerOverTrigger;
  38638. },
  38639. enumerable: true,
  38640. configurable: true
  38641. });
  38642. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38643. get: function () {
  38644. return ActionManager._OnPointerOutTrigger;
  38645. },
  38646. enumerable: true,
  38647. configurable: true
  38648. });
  38649. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38650. get: function () {
  38651. return ActionManager._OnEveryFrameTrigger;
  38652. },
  38653. enumerable: true,
  38654. configurable: true
  38655. });
  38656. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38657. get: function () {
  38658. return ActionManager._OnIntersectionEnterTrigger;
  38659. },
  38660. enumerable: true,
  38661. configurable: true
  38662. });
  38663. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38664. get: function () {
  38665. return ActionManager._OnIntersectionExitTrigger;
  38666. },
  38667. enumerable: true,
  38668. configurable: true
  38669. });
  38670. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38671. get: function () {
  38672. return ActionManager._OnKeyDownTrigger;
  38673. },
  38674. enumerable: true,
  38675. configurable: true
  38676. });
  38677. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38678. get: function () {
  38679. return ActionManager._OnKeyUpTrigger;
  38680. },
  38681. enumerable: true,
  38682. configurable: true
  38683. });
  38684. // Methods
  38685. ActionManager.prototype.dispose = function () {
  38686. var index = this._scene._actionManagers.indexOf(this);
  38687. if (index > -1) {
  38688. this._scene._actionManagers.splice(index, 1);
  38689. }
  38690. };
  38691. ActionManager.prototype.getScene = function () {
  38692. return this._scene;
  38693. };
  38694. /**
  38695. * Does this action manager handles actions of any of the given triggers
  38696. * @param {number[]} triggers - the triggers to be tested
  38697. * @return {boolean} whether one (or more) of the triggers is handeled
  38698. */
  38699. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38700. for (var index = 0; index < this.actions.length; index++) {
  38701. var action = this.actions[index];
  38702. if (triggers.indexOf(action.trigger) > -1) {
  38703. return true;
  38704. }
  38705. }
  38706. return false;
  38707. };
  38708. /**
  38709. * Does this action manager handles actions of a given trigger
  38710. * @param {number} trigger - the trigger to be tested
  38711. * @return {boolean} whether the trigger is handeled
  38712. */
  38713. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38714. for (var index = 0; index < this.actions.length; index++) {
  38715. var action = this.actions[index];
  38716. if (action.trigger === trigger) {
  38717. return true;
  38718. }
  38719. }
  38720. return false;
  38721. };
  38722. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38723. /**
  38724. * Does this action manager has pointer triggers
  38725. * @return {boolean} whether or not it has pointer triggers
  38726. */
  38727. get: function () {
  38728. for (var index = 0; index < this.actions.length; index++) {
  38729. var action = this.actions[index];
  38730. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38731. return true;
  38732. }
  38733. }
  38734. return false;
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38740. /**
  38741. * Does this action manager has pick triggers
  38742. * @return {boolean} whether or not it has pick triggers
  38743. */
  38744. get: function () {
  38745. for (var index = 0; index < this.actions.length; index++) {
  38746. var action = this.actions[index];
  38747. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38748. return true;
  38749. }
  38750. }
  38751. return false;
  38752. },
  38753. enumerable: true,
  38754. configurable: true
  38755. });
  38756. /**
  38757. * Registers an action to this action manager
  38758. * @param {BABYLON.Action} action - the action to be registered
  38759. * @return {BABYLON.Action} the action amended (prepared) after registration
  38760. */
  38761. ActionManager.prototype.registerAction = function (action) {
  38762. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38763. if (this.getScene().actionManager !== this) {
  38764. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38765. return null;
  38766. }
  38767. }
  38768. this.actions.push(action);
  38769. action._actionManager = this;
  38770. action._prepare();
  38771. return action;
  38772. };
  38773. /**
  38774. * Process a specific trigger
  38775. * @param {number} trigger - the trigger to process
  38776. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38777. */
  38778. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38779. for (var index = 0; index < this.actions.length; index++) {
  38780. var action = this.actions[index];
  38781. if (action.trigger === trigger) {
  38782. if (trigger === ActionManager.OnKeyUpTrigger
  38783. || trigger === ActionManager.OnKeyDownTrigger) {
  38784. var parameter = action.getTriggerParameter();
  38785. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38786. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38787. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38788. if (actualkey !== parameter.toLowerCase()) {
  38789. continue;
  38790. }
  38791. }
  38792. }
  38793. action._executeCurrent(evt);
  38794. }
  38795. }
  38796. };
  38797. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38798. var properties = propertyPath.split(".");
  38799. for (var index = 0; index < properties.length - 1; index++) {
  38800. target = target[properties[index]];
  38801. }
  38802. return target;
  38803. };
  38804. ActionManager.prototype._getProperty = function (propertyPath) {
  38805. var properties = propertyPath.split(".");
  38806. return properties[properties.length - 1];
  38807. };
  38808. ActionManager.prototype.serialize = function (name) {
  38809. var root = {
  38810. children: [],
  38811. name: name,
  38812. type: 3,
  38813. properties: [] // Empty for root but required
  38814. };
  38815. for (var i = 0; i < this.actions.length; i++) {
  38816. var triggerObject = {
  38817. type: 0,
  38818. children: [],
  38819. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38820. properties: []
  38821. };
  38822. var triggerOptions = this.actions[i].triggerOptions;
  38823. if (triggerOptions && typeof triggerOptions !== "number") {
  38824. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38825. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38826. }
  38827. else {
  38828. var parameter = {};
  38829. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38830. if (triggerOptions.parameter.mesh) {
  38831. parameter._meshId = triggerOptions.parameter.mesh.id;
  38832. }
  38833. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38834. }
  38835. }
  38836. // Serialize child action, recursively
  38837. this.actions[i].serialize(triggerObject);
  38838. // Add serialized trigger
  38839. root.children.push(triggerObject);
  38840. }
  38841. return root;
  38842. };
  38843. ActionManager.Parse = function (parsedActions, object, scene) {
  38844. var actionManager = new BABYLON.ActionManager(scene);
  38845. if (object === null)
  38846. scene.actionManager = actionManager;
  38847. else
  38848. object.actionManager = actionManager;
  38849. // instanciate a new object
  38850. var instanciate = function (name, params) {
  38851. var newInstance = Object.create(BABYLON[name].prototype);
  38852. newInstance.constructor.apply(newInstance, params);
  38853. return newInstance;
  38854. };
  38855. var parseParameter = function (name, value, target, propertyPath) {
  38856. if (propertyPath === null) {
  38857. // String, boolean or float
  38858. var floatValue = parseFloat(value);
  38859. if (value === "true" || value === "false")
  38860. return value === "true";
  38861. else
  38862. return isNaN(floatValue) ? value : floatValue;
  38863. }
  38864. var effectiveTarget = propertyPath.split(".");
  38865. var values = value.split(",");
  38866. // Get effective Target
  38867. for (var i = 0; i < effectiveTarget.length; i++) {
  38868. target = target[effectiveTarget[i]];
  38869. }
  38870. // Return appropriate value with its type
  38871. if (typeof (target) === "boolean")
  38872. return values[0] === "true";
  38873. if (typeof (target) === "string")
  38874. return values[0];
  38875. // Parameters with multiple values such as Vector3 etc.
  38876. var split = new Array();
  38877. for (var i = 0; i < values.length; i++)
  38878. split.push(parseFloat(values[i]));
  38879. if (target instanceof BABYLON.Vector3)
  38880. return BABYLON.Vector3.FromArray(split);
  38881. if (target instanceof BABYLON.Vector4)
  38882. return BABYLON.Vector4.FromArray(split);
  38883. if (target instanceof BABYLON.Color3)
  38884. return BABYLON.Color3.FromArray(split);
  38885. if (target instanceof BABYLON.Color4)
  38886. return BABYLON.Color4.FromArray(split);
  38887. return parseFloat(values[0]);
  38888. };
  38889. // traverse graph per trigger
  38890. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38891. if (combineArray === void 0) { combineArray = null; }
  38892. if (parsedAction.detached)
  38893. return;
  38894. var parameters = new Array();
  38895. var target = null;
  38896. var propertyPath = null;
  38897. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38898. // Parameters
  38899. if (parsedAction.type === 2)
  38900. parameters.push(actionManager);
  38901. else
  38902. parameters.push(trigger);
  38903. if (combine) {
  38904. var actions = new Array();
  38905. for (var j = 0; j < parsedAction.combine.length; j++) {
  38906. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38907. }
  38908. parameters.push(actions);
  38909. }
  38910. else {
  38911. for (var i = 0; i < parsedAction.properties.length; i++) {
  38912. var value = parsedAction.properties[i].value;
  38913. var name = parsedAction.properties[i].name;
  38914. var targetType = parsedAction.properties[i].targetType;
  38915. if (name === "target")
  38916. if (targetType !== null && targetType === "SceneProperties")
  38917. value = target = scene;
  38918. else
  38919. value = target = scene.getNodeByName(value);
  38920. else if (name === "parent")
  38921. value = scene.getNodeByName(value);
  38922. else if (name === "sound")
  38923. value = scene.getSoundByName(value);
  38924. else if (name !== "propertyPath") {
  38925. if (parsedAction.type === 2 && name === "operator")
  38926. value = BABYLON.ValueCondition[value];
  38927. else
  38928. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38929. }
  38930. else {
  38931. propertyPath = value;
  38932. }
  38933. parameters.push(value);
  38934. }
  38935. }
  38936. if (combineArray === null) {
  38937. parameters.push(condition);
  38938. }
  38939. else {
  38940. parameters.push(null);
  38941. }
  38942. // If interpolate value action
  38943. if (parsedAction.name === "InterpolateValueAction") {
  38944. var param = parameters[parameters.length - 2];
  38945. parameters[parameters.length - 1] = param;
  38946. parameters[parameters.length - 2] = condition;
  38947. }
  38948. // Action or condition(s) and not CombineAction
  38949. var newAction = instanciate(parsedAction.name, parameters);
  38950. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38951. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38952. if (action)
  38953. action.then(nothing);
  38954. else
  38955. actionManager.registerAction(nothing);
  38956. action = nothing;
  38957. }
  38958. if (combineArray === null) {
  38959. if (newAction instanceof BABYLON.Condition) {
  38960. condition = newAction;
  38961. newAction = action;
  38962. }
  38963. else {
  38964. condition = null;
  38965. if (action)
  38966. action.then(newAction);
  38967. else
  38968. actionManager.registerAction(newAction);
  38969. }
  38970. }
  38971. else {
  38972. combineArray.push(newAction);
  38973. }
  38974. for (var i = 0; i < parsedAction.children.length; i++)
  38975. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38976. };
  38977. // triggers
  38978. for (var i = 0; i < parsedActions.children.length; i++) {
  38979. var triggerParams;
  38980. var trigger = parsedActions.children[i];
  38981. if (trigger.properties.length > 0) {
  38982. var param = trigger.properties[0].value;
  38983. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38984. if (value._meshId) {
  38985. value.mesh = scene.getMeshByID(value._meshId);
  38986. }
  38987. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38988. }
  38989. else
  38990. triggerParams = BABYLON.ActionManager[trigger.name];
  38991. for (var j = 0; j < trigger.children.length; j++) {
  38992. if (!trigger.detached)
  38993. traverse(trigger.children[j], triggerParams, null, null);
  38994. }
  38995. }
  38996. };
  38997. ActionManager.GetTriggerName = function (trigger) {
  38998. switch (trigger) {
  38999. case 0: return "NothingTrigger";
  39000. case 1: return "OnPickTrigger";
  39001. case 2: return "OnLeftPickTrigger";
  39002. case 3: return "OnRightPickTrigger";
  39003. case 4: return "OnCenterPickTrigger";
  39004. case 5: return "OnPickDownTrigger";
  39005. case 6: return "OnPickUpTrigger";
  39006. case 7: return "OnLongPressTrigger";
  39007. case 8: return "OnPointerOverTrigger";
  39008. case 9: return "OnPointerOutTrigger";
  39009. case 10: return "OnEveryFrameTrigger";
  39010. case 11: return "OnIntersectionEnterTrigger";
  39011. case 12: return "OnIntersectionExitTrigger";
  39012. case 13: return "OnKeyDownTrigger";
  39013. case 14: return "OnKeyUpTrigger";
  39014. case 15: return "OnPickOutTrigger";
  39015. default: return "";
  39016. }
  39017. };
  39018. return ActionManager;
  39019. }());
  39020. // Statics
  39021. ActionManager._NothingTrigger = 0;
  39022. ActionManager._OnPickTrigger = 1;
  39023. ActionManager._OnLeftPickTrigger = 2;
  39024. ActionManager._OnRightPickTrigger = 3;
  39025. ActionManager._OnCenterPickTrigger = 4;
  39026. ActionManager._OnPickDownTrigger = 5;
  39027. ActionManager._OnPickUpTrigger = 6;
  39028. ActionManager._OnLongPressTrigger = 7;
  39029. ActionManager._OnPointerOverTrigger = 8;
  39030. ActionManager._OnPointerOutTrigger = 9;
  39031. ActionManager._OnEveryFrameTrigger = 10;
  39032. ActionManager._OnIntersectionEnterTrigger = 11;
  39033. ActionManager._OnIntersectionExitTrigger = 12;
  39034. ActionManager._OnKeyDownTrigger = 13;
  39035. ActionManager._OnKeyUpTrigger = 14;
  39036. ActionManager._OnPickOutTrigger = 15;
  39037. ActionManager.DragMovementThreshold = 10; // in pixels
  39038. ActionManager.LongPressDelay = 500; // in milliseconds
  39039. BABYLON.ActionManager = ActionManager;
  39040. })(BABYLON || (BABYLON = {}));
  39041. //# sourceMappingURL=babylon.actionManager.js.map
  39042. var BABYLON;
  39043. (function (BABYLON) {
  39044. var InterpolateValueAction = (function (_super) {
  39045. __extends(InterpolateValueAction, _super);
  39046. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39047. if (duration === void 0) { duration = 1000; }
  39048. var _this = _super.call(this, triggerOptions, condition) || this;
  39049. _this.propertyPath = propertyPath;
  39050. _this.value = value;
  39051. _this.duration = duration;
  39052. _this.stopOtherAnimations = stopOtherAnimations;
  39053. _this.onInterpolationDone = onInterpolationDone;
  39054. _this._target = _this._effectiveTarget = target;
  39055. return _this;
  39056. }
  39057. InterpolateValueAction.prototype._prepare = function () {
  39058. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39059. this._property = this._getProperty(this.propertyPath);
  39060. };
  39061. InterpolateValueAction.prototype.execute = function () {
  39062. var scene = this._actionManager.getScene();
  39063. var keys = [
  39064. {
  39065. frame: 0,
  39066. value: this._effectiveTarget[this._property]
  39067. }, {
  39068. frame: 100,
  39069. value: this.value
  39070. }
  39071. ];
  39072. var dataType;
  39073. if (typeof this.value === "number") {
  39074. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39075. }
  39076. else if (this.value instanceof BABYLON.Color3) {
  39077. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39078. }
  39079. else if (this.value instanceof BABYLON.Vector3) {
  39080. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39081. }
  39082. else if (this.value instanceof BABYLON.Matrix) {
  39083. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39084. }
  39085. else if (this.value instanceof BABYLON.Quaternion) {
  39086. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39087. }
  39088. else {
  39089. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39090. return;
  39091. }
  39092. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39093. animation.setKeys(keys);
  39094. if (this.stopOtherAnimations) {
  39095. scene.stopAnimation(this._effectiveTarget);
  39096. }
  39097. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39098. };
  39099. InterpolateValueAction.prototype.serialize = function (parent) {
  39100. return _super.prototype._serialize.call(this, {
  39101. name: "InterpolateValueAction",
  39102. properties: [
  39103. BABYLON.Action._GetTargetProperty(this._target),
  39104. { name: "propertyPath", value: this.propertyPath },
  39105. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39106. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39107. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39108. ]
  39109. }, parent);
  39110. };
  39111. return InterpolateValueAction;
  39112. }(BABYLON.Action));
  39113. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39114. })(BABYLON || (BABYLON = {}));
  39115. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39116. var BABYLON;
  39117. (function (BABYLON) {
  39118. var SwitchBooleanAction = (function (_super) {
  39119. __extends(SwitchBooleanAction, _super);
  39120. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39121. var _this = _super.call(this, triggerOptions, condition) || this;
  39122. _this.propertyPath = propertyPath;
  39123. _this._target = _this._effectiveTarget = target;
  39124. return _this;
  39125. }
  39126. SwitchBooleanAction.prototype._prepare = function () {
  39127. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39128. this._property = this._getProperty(this.propertyPath);
  39129. };
  39130. SwitchBooleanAction.prototype.execute = function () {
  39131. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39132. };
  39133. SwitchBooleanAction.prototype.serialize = function (parent) {
  39134. return _super.prototype._serialize.call(this, {
  39135. name: "SwitchBooleanAction",
  39136. properties: [
  39137. BABYLON.Action._GetTargetProperty(this._target),
  39138. { name: "propertyPath", value: this.propertyPath }
  39139. ]
  39140. }, parent);
  39141. };
  39142. return SwitchBooleanAction;
  39143. }(BABYLON.Action));
  39144. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39145. var SetStateAction = (function (_super) {
  39146. __extends(SetStateAction, _super);
  39147. function SetStateAction(triggerOptions, target, value, condition) {
  39148. var _this = _super.call(this, triggerOptions, condition) || this;
  39149. _this.value = value;
  39150. _this._target = target;
  39151. return _this;
  39152. }
  39153. SetStateAction.prototype.execute = function () {
  39154. this._target.state = this.value;
  39155. };
  39156. SetStateAction.prototype.serialize = function (parent) {
  39157. return _super.prototype._serialize.call(this, {
  39158. name: "SetStateAction",
  39159. properties: [
  39160. BABYLON.Action._GetTargetProperty(this._target),
  39161. { name: "value", value: this.value }
  39162. ]
  39163. }, parent);
  39164. };
  39165. return SetStateAction;
  39166. }(BABYLON.Action));
  39167. BABYLON.SetStateAction = SetStateAction;
  39168. var SetValueAction = (function (_super) {
  39169. __extends(SetValueAction, _super);
  39170. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39171. var _this = _super.call(this, triggerOptions, condition) || this;
  39172. _this.propertyPath = propertyPath;
  39173. _this.value = value;
  39174. _this._target = _this._effectiveTarget = target;
  39175. return _this;
  39176. }
  39177. SetValueAction.prototype._prepare = function () {
  39178. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39179. this._property = this._getProperty(this.propertyPath);
  39180. };
  39181. SetValueAction.prototype.execute = function () {
  39182. this._effectiveTarget[this._property] = this.value;
  39183. if (this._target.markAsDirty) {
  39184. this._target.markAsDirty(this._property);
  39185. }
  39186. };
  39187. SetValueAction.prototype.serialize = function (parent) {
  39188. return _super.prototype._serialize.call(this, {
  39189. name: "SetValueAction",
  39190. properties: [
  39191. BABYLON.Action._GetTargetProperty(this._target),
  39192. { name: "propertyPath", value: this.propertyPath },
  39193. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39194. ]
  39195. }, parent);
  39196. };
  39197. return SetValueAction;
  39198. }(BABYLON.Action));
  39199. BABYLON.SetValueAction = SetValueAction;
  39200. var IncrementValueAction = (function (_super) {
  39201. __extends(IncrementValueAction, _super);
  39202. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39203. var _this = _super.call(this, triggerOptions, condition) || this;
  39204. _this.propertyPath = propertyPath;
  39205. _this.value = value;
  39206. _this._target = _this._effectiveTarget = target;
  39207. return _this;
  39208. }
  39209. IncrementValueAction.prototype._prepare = function () {
  39210. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39211. this._property = this._getProperty(this.propertyPath);
  39212. if (typeof this._effectiveTarget[this._property] !== "number") {
  39213. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39214. }
  39215. };
  39216. IncrementValueAction.prototype.execute = function () {
  39217. this._effectiveTarget[this._property] += this.value;
  39218. if (this._target.markAsDirty) {
  39219. this._target.markAsDirty(this._property);
  39220. }
  39221. };
  39222. IncrementValueAction.prototype.serialize = function (parent) {
  39223. return _super.prototype._serialize.call(this, {
  39224. name: "IncrementValueAction",
  39225. properties: [
  39226. BABYLON.Action._GetTargetProperty(this._target),
  39227. { name: "propertyPath", value: this.propertyPath },
  39228. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39229. ]
  39230. }, parent);
  39231. };
  39232. return IncrementValueAction;
  39233. }(BABYLON.Action));
  39234. BABYLON.IncrementValueAction = IncrementValueAction;
  39235. var PlayAnimationAction = (function (_super) {
  39236. __extends(PlayAnimationAction, _super);
  39237. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39238. var _this = _super.call(this, triggerOptions, condition) || this;
  39239. _this.from = from;
  39240. _this.to = to;
  39241. _this.loop = loop;
  39242. _this._target = target;
  39243. return _this;
  39244. }
  39245. PlayAnimationAction.prototype._prepare = function () {
  39246. };
  39247. PlayAnimationAction.prototype.execute = function () {
  39248. var scene = this._actionManager.getScene();
  39249. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39250. };
  39251. PlayAnimationAction.prototype.serialize = function (parent) {
  39252. return _super.prototype._serialize.call(this, {
  39253. name: "PlayAnimationAction",
  39254. properties: [
  39255. BABYLON.Action._GetTargetProperty(this._target),
  39256. { name: "from", value: String(this.from) },
  39257. { name: "to", value: String(this.to) },
  39258. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39259. ]
  39260. }, parent);
  39261. };
  39262. return PlayAnimationAction;
  39263. }(BABYLON.Action));
  39264. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39265. var StopAnimationAction = (function (_super) {
  39266. __extends(StopAnimationAction, _super);
  39267. function StopAnimationAction(triggerOptions, target, condition) {
  39268. var _this = _super.call(this, triggerOptions, condition) || this;
  39269. _this._target = target;
  39270. return _this;
  39271. }
  39272. StopAnimationAction.prototype._prepare = function () {
  39273. };
  39274. StopAnimationAction.prototype.execute = function () {
  39275. var scene = this._actionManager.getScene();
  39276. scene.stopAnimation(this._target);
  39277. };
  39278. StopAnimationAction.prototype.serialize = function (parent) {
  39279. return _super.prototype._serialize.call(this, {
  39280. name: "StopAnimationAction",
  39281. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39282. }, parent);
  39283. };
  39284. return StopAnimationAction;
  39285. }(BABYLON.Action));
  39286. BABYLON.StopAnimationAction = StopAnimationAction;
  39287. var DoNothingAction = (function (_super) {
  39288. __extends(DoNothingAction, _super);
  39289. function DoNothingAction(triggerOptions, condition) {
  39290. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39291. return _super.call(this, triggerOptions, condition) || this;
  39292. }
  39293. DoNothingAction.prototype.execute = function () {
  39294. };
  39295. DoNothingAction.prototype.serialize = function (parent) {
  39296. return _super.prototype._serialize.call(this, {
  39297. name: "DoNothingAction",
  39298. properties: []
  39299. }, parent);
  39300. };
  39301. return DoNothingAction;
  39302. }(BABYLON.Action));
  39303. BABYLON.DoNothingAction = DoNothingAction;
  39304. var CombineAction = (function (_super) {
  39305. __extends(CombineAction, _super);
  39306. function CombineAction(triggerOptions, children, condition) {
  39307. var _this = _super.call(this, triggerOptions, condition) || this;
  39308. _this.children = children;
  39309. return _this;
  39310. }
  39311. CombineAction.prototype._prepare = function () {
  39312. for (var index = 0; index < this.children.length; index++) {
  39313. this.children[index]._actionManager = this._actionManager;
  39314. this.children[index]._prepare();
  39315. }
  39316. };
  39317. CombineAction.prototype.execute = function (evt) {
  39318. for (var index = 0; index < this.children.length; index++) {
  39319. this.children[index].execute(evt);
  39320. }
  39321. };
  39322. CombineAction.prototype.serialize = function (parent) {
  39323. var serializationObject = _super.prototype._serialize.call(this, {
  39324. name: "CombineAction",
  39325. properties: [],
  39326. combine: []
  39327. }, parent);
  39328. for (var i = 0; i < this.children.length; i++) {
  39329. serializationObject.combine.push(this.children[i].serialize(null));
  39330. }
  39331. return serializationObject;
  39332. };
  39333. return CombineAction;
  39334. }(BABYLON.Action));
  39335. BABYLON.CombineAction = CombineAction;
  39336. var ExecuteCodeAction = (function (_super) {
  39337. __extends(ExecuteCodeAction, _super);
  39338. function ExecuteCodeAction(triggerOptions, func, condition) {
  39339. var _this = _super.call(this, triggerOptions, condition) || this;
  39340. _this.func = func;
  39341. return _this;
  39342. }
  39343. ExecuteCodeAction.prototype.execute = function (evt) {
  39344. this.func(evt);
  39345. };
  39346. return ExecuteCodeAction;
  39347. }(BABYLON.Action));
  39348. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39349. var SetParentAction = (function (_super) {
  39350. __extends(SetParentAction, _super);
  39351. function SetParentAction(triggerOptions, target, parent, condition) {
  39352. var _this = _super.call(this, triggerOptions, condition) || this;
  39353. _this._target = target;
  39354. _this._parent = parent;
  39355. return _this;
  39356. }
  39357. SetParentAction.prototype._prepare = function () {
  39358. };
  39359. SetParentAction.prototype.execute = function () {
  39360. if (this._target.parent === this._parent) {
  39361. return;
  39362. }
  39363. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39364. invertParentWorldMatrix.invert();
  39365. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39366. this._target.parent = this._parent;
  39367. };
  39368. SetParentAction.prototype.serialize = function (parent) {
  39369. return _super.prototype._serialize.call(this, {
  39370. name: "SetParentAction",
  39371. properties: [
  39372. BABYLON.Action._GetTargetProperty(this._target),
  39373. BABYLON.Action._GetTargetProperty(this._parent),
  39374. ]
  39375. }, parent);
  39376. };
  39377. return SetParentAction;
  39378. }(BABYLON.Action));
  39379. BABYLON.SetParentAction = SetParentAction;
  39380. var PlaySoundAction = (function (_super) {
  39381. __extends(PlaySoundAction, _super);
  39382. function PlaySoundAction(triggerOptions, sound, condition) {
  39383. var _this = _super.call(this, triggerOptions, condition) || this;
  39384. _this._sound = sound;
  39385. return _this;
  39386. }
  39387. PlaySoundAction.prototype._prepare = function () {
  39388. };
  39389. PlaySoundAction.prototype.execute = function () {
  39390. if (this._sound !== undefined)
  39391. this._sound.play();
  39392. };
  39393. PlaySoundAction.prototype.serialize = function (parent) {
  39394. return _super.prototype._serialize.call(this, {
  39395. name: "PlaySoundAction",
  39396. properties: [{ name: "sound", value: this._sound.name }]
  39397. }, parent);
  39398. };
  39399. return PlaySoundAction;
  39400. }(BABYLON.Action));
  39401. BABYLON.PlaySoundAction = PlaySoundAction;
  39402. var StopSoundAction = (function (_super) {
  39403. __extends(StopSoundAction, _super);
  39404. function StopSoundAction(triggerOptions, sound, condition) {
  39405. var _this = _super.call(this, triggerOptions, condition) || this;
  39406. _this._sound = sound;
  39407. return _this;
  39408. }
  39409. StopSoundAction.prototype._prepare = function () {
  39410. };
  39411. StopSoundAction.prototype.execute = function () {
  39412. if (this._sound !== undefined)
  39413. this._sound.stop();
  39414. };
  39415. StopSoundAction.prototype.serialize = function (parent) {
  39416. return _super.prototype._serialize.call(this, {
  39417. name: "StopSoundAction",
  39418. properties: [{ name: "sound", value: this._sound.name }]
  39419. }, parent);
  39420. };
  39421. return StopSoundAction;
  39422. }(BABYLON.Action));
  39423. BABYLON.StopSoundAction = StopSoundAction;
  39424. })(BABYLON || (BABYLON = {}));
  39425. //# sourceMappingURL=babylon.directActions.js.map
  39426. var BABYLON;
  39427. (function (BABYLON) {
  39428. var Geometry = (function () {
  39429. function Geometry(id, scene, vertexData, updatable, mesh) {
  39430. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39431. this._totalVertices = 0;
  39432. this._isDisposed = false;
  39433. this.id = id;
  39434. this._engine = scene.getEngine();
  39435. this._meshes = [];
  39436. this._scene = scene;
  39437. //Init vertex buffer cache
  39438. this._vertexBuffers = {};
  39439. this._indices = [];
  39440. // vertexData
  39441. if (vertexData) {
  39442. this.setAllVerticesData(vertexData, updatable);
  39443. }
  39444. else {
  39445. this._totalVertices = 0;
  39446. this._indices = [];
  39447. }
  39448. if (this._engine.getCaps().vertexArrayObject) {
  39449. this._vertexArrayObjects = {};
  39450. }
  39451. // applyToMesh
  39452. if (mesh) {
  39453. if (mesh instanceof BABYLON.LinesMesh) {
  39454. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39455. this.updateExtend();
  39456. }
  39457. this.applyToMesh(mesh);
  39458. mesh.computeWorldMatrix(true);
  39459. }
  39460. }
  39461. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39462. /**
  39463. * 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
  39464. * @returns The Bias Vector
  39465. */
  39466. get: function () {
  39467. return this._boundingBias;
  39468. },
  39469. set: function (value) {
  39470. if (this._boundingBias && this._boundingBias.equals(value)) {
  39471. return;
  39472. }
  39473. this._boundingBias = value.clone();
  39474. this.updateBoundingInfo(true, null);
  39475. },
  39476. enumerable: true,
  39477. configurable: true
  39478. });
  39479. Object.defineProperty(Geometry.prototype, "extend", {
  39480. get: function () {
  39481. return this._extend;
  39482. },
  39483. enumerable: true,
  39484. configurable: true
  39485. });
  39486. Geometry.prototype.getScene = function () {
  39487. return this._scene;
  39488. };
  39489. Geometry.prototype.getEngine = function () {
  39490. return this._engine;
  39491. };
  39492. Geometry.prototype.isReady = function () {
  39493. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39494. };
  39495. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39496. get: function () {
  39497. for (var index = 0; index < this._meshes.length; index++) {
  39498. if (!this._meshes[index].doNotSerialize) {
  39499. return false;
  39500. }
  39501. }
  39502. return true;
  39503. },
  39504. enumerable: true,
  39505. configurable: true
  39506. });
  39507. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39508. vertexData.applyToGeometry(this, updatable);
  39509. this.notifyUpdate();
  39510. };
  39511. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39512. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39513. this.setVerticesBuffer(buffer);
  39514. };
  39515. Geometry.prototype.setVerticesBuffer = function (buffer) {
  39516. var kind = buffer.getKind();
  39517. if (this._vertexBuffers[kind]) {
  39518. this._vertexBuffers[kind].dispose();
  39519. }
  39520. this._vertexBuffers[kind] = buffer;
  39521. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39522. var data = buffer.getData();
  39523. var stride = buffer.getStrideSize();
  39524. this._totalVertices = data.length / stride;
  39525. this.updateExtend(data, stride);
  39526. var meshes = this._meshes;
  39527. var numOfMeshes = meshes.length;
  39528. for (var index = 0; index < numOfMeshes; index++) {
  39529. var mesh = meshes[index];
  39530. mesh._resetPointsArrayCache();
  39531. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39532. mesh._createGlobalSubMesh();
  39533. mesh.computeWorldMatrix(true);
  39534. }
  39535. }
  39536. this.notifyUpdate(kind);
  39537. if (this._vertexArrayObjects) {
  39538. this._disposeVertexArrayObjects();
  39539. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39540. }
  39541. };
  39542. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  39543. var vertexBuffer = this.getVertexBuffer(kind);
  39544. if (!vertexBuffer) {
  39545. return;
  39546. }
  39547. vertexBuffer.updateDirectly(data, offset);
  39548. this.notifyUpdate(kind);
  39549. };
  39550. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39551. var vertexBuffer = this.getVertexBuffer(kind);
  39552. if (!vertexBuffer) {
  39553. return;
  39554. }
  39555. vertexBuffer.update(data);
  39556. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39557. var stride = vertexBuffer.getStrideSize();
  39558. this._totalVertices = data.length / stride;
  39559. this.updateBoundingInfo(updateExtends, data);
  39560. }
  39561. this.notifyUpdate(kind);
  39562. };
  39563. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  39564. if (updateExtends) {
  39565. this.updateExtend(data);
  39566. }
  39567. var meshes = this._meshes;
  39568. var numOfMeshes = meshes.length;
  39569. for (var index = 0; index < numOfMeshes; index++) {
  39570. var mesh = meshes[index];
  39571. mesh._resetPointsArrayCache();
  39572. if (updateExtends) {
  39573. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39574. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39575. var subMesh = mesh.subMeshes[subIndex];
  39576. subMesh.refreshBoundingInfo();
  39577. }
  39578. }
  39579. }
  39580. };
  39581. Geometry.prototype._bind = function (effect, indexToBind) {
  39582. if (indexToBind === void 0) { indexToBind = undefined; }
  39583. if (indexToBind === undefined) {
  39584. indexToBind = this._indexBuffer;
  39585. }
  39586. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39587. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  39588. return;
  39589. }
  39590. // Using VAO
  39591. if (!this._vertexArrayObjects[effect.key]) {
  39592. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  39593. }
  39594. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39595. };
  39596. Geometry.prototype.getTotalVertices = function () {
  39597. if (!this.isReady()) {
  39598. return 0;
  39599. }
  39600. return this._totalVertices;
  39601. };
  39602. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  39603. var vertexBuffer = this.getVertexBuffer(kind);
  39604. if (!vertexBuffer) {
  39605. return null;
  39606. }
  39607. var orig = vertexBuffer.getData();
  39608. if (!copyWhenShared || this._meshes.length === 1) {
  39609. return orig;
  39610. }
  39611. else {
  39612. var len = orig.length;
  39613. var copy = [];
  39614. for (var i = 0; i < len; i++) {
  39615. copy.push(orig[i]);
  39616. }
  39617. return copy;
  39618. }
  39619. };
  39620. Geometry.prototype.getVertexBuffer = function (kind) {
  39621. if (!this.isReady()) {
  39622. return null;
  39623. }
  39624. return this._vertexBuffers[kind];
  39625. };
  39626. Geometry.prototype.getVertexBuffers = function () {
  39627. if (!this.isReady()) {
  39628. return null;
  39629. }
  39630. return this._vertexBuffers;
  39631. };
  39632. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39633. if (!this._vertexBuffers) {
  39634. if (this._delayInfo) {
  39635. return this._delayInfo.indexOf(kind) !== -1;
  39636. }
  39637. return false;
  39638. }
  39639. return this._vertexBuffers[kind] !== undefined;
  39640. };
  39641. Geometry.prototype.getVerticesDataKinds = function () {
  39642. var result = [];
  39643. var kind;
  39644. if (!this._vertexBuffers && this._delayInfo) {
  39645. for (kind in this._delayInfo) {
  39646. result.push(kind);
  39647. }
  39648. }
  39649. else {
  39650. for (kind in this._vertexBuffers) {
  39651. result.push(kind);
  39652. }
  39653. }
  39654. return result;
  39655. };
  39656. Geometry.prototype.setIndices = function (indices, totalVertices) {
  39657. if (this._indexBuffer) {
  39658. this._engine._releaseBuffer(this._indexBuffer);
  39659. }
  39660. this._disposeVertexArrayObjects();
  39661. this._indices = indices;
  39662. if (this._meshes.length !== 0 && this._indices) {
  39663. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39664. }
  39665. if (totalVertices !== undefined) {
  39666. this._totalVertices = totalVertices;
  39667. }
  39668. var meshes = this._meshes;
  39669. var numOfMeshes = meshes.length;
  39670. for (var index = 0; index < numOfMeshes; index++) {
  39671. meshes[index]._createGlobalSubMesh();
  39672. }
  39673. this.notifyUpdate();
  39674. };
  39675. Geometry.prototype.getTotalIndices = function () {
  39676. if (!this.isReady()) {
  39677. return 0;
  39678. }
  39679. return this._indices.length;
  39680. };
  39681. Geometry.prototype.getIndices = function (copyWhenShared) {
  39682. if (!this.isReady()) {
  39683. return null;
  39684. }
  39685. var orig = this._indices;
  39686. if (!copyWhenShared || this._meshes.length === 1) {
  39687. return orig;
  39688. }
  39689. else {
  39690. var len = orig.length;
  39691. var copy = [];
  39692. for (var i = 0; i < len; i++) {
  39693. copy.push(orig[i]);
  39694. }
  39695. return copy;
  39696. }
  39697. };
  39698. Geometry.prototype.getIndexBuffer = function () {
  39699. if (!this.isReady()) {
  39700. return null;
  39701. }
  39702. return this._indexBuffer;
  39703. };
  39704. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39705. var meshes = this._meshes;
  39706. var index = meshes.indexOf(mesh);
  39707. if (index === -1) {
  39708. return;
  39709. }
  39710. meshes.splice(index, 1);
  39711. mesh._geometry = null;
  39712. if (meshes.length === 0 && shouldDispose) {
  39713. this.dispose();
  39714. }
  39715. };
  39716. Geometry.prototype.applyToMesh = function (mesh) {
  39717. if (mesh._geometry === this) {
  39718. return;
  39719. }
  39720. var previousGeometry = mesh._geometry;
  39721. if (previousGeometry) {
  39722. previousGeometry.releaseForMesh(mesh);
  39723. }
  39724. var meshes = this._meshes;
  39725. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39726. mesh._geometry = this;
  39727. this._scene.pushGeometry(this);
  39728. meshes.push(mesh);
  39729. if (this.isReady()) {
  39730. this._applyToMesh(mesh);
  39731. }
  39732. else {
  39733. mesh._boundingInfo = this._boundingInfo;
  39734. }
  39735. };
  39736. Geometry.prototype.updateExtend = function (data, stride) {
  39737. if (data === void 0) { data = null; }
  39738. if (!data) {
  39739. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  39740. }
  39741. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  39742. };
  39743. Geometry.prototype._applyToMesh = function (mesh) {
  39744. var numOfMeshes = this._meshes.length;
  39745. // vertexBuffers
  39746. for (var kind in this._vertexBuffers) {
  39747. if (numOfMeshes === 1) {
  39748. this._vertexBuffers[kind].create();
  39749. }
  39750. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  39751. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39752. mesh._resetPointsArrayCache();
  39753. if (!this._extend) {
  39754. this.updateExtend(this._vertexBuffers[kind].getData());
  39755. }
  39756. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39757. mesh._createGlobalSubMesh();
  39758. //bounding info was just created again, world matrix should be applied again.
  39759. mesh._updateBoundingInfo();
  39760. }
  39761. }
  39762. // indexBuffer
  39763. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39764. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39765. }
  39766. if (this._indexBuffer) {
  39767. this._indexBuffer.references = numOfMeshes;
  39768. }
  39769. };
  39770. Geometry.prototype.notifyUpdate = function (kind) {
  39771. if (this.onGeometryUpdated) {
  39772. this.onGeometryUpdated(this, kind);
  39773. }
  39774. };
  39775. Geometry.prototype.load = function (scene, onLoaded) {
  39776. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39777. return;
  39778. }
  39779. if (this.isReady()) {
  39780. if (onLoaded) {
  39781. onLoaded();
  39782. }
  39783. return;
  39784. }
  39785. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39786. this._queueLoad(scene, onLoaded);
  39787. };
  39788. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39789. var _this = this;
  39790. scene._addPendingData(this);
  39791. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  39792. _this._delayLoadingFunction(JSON.parse(data), _this);
  39793. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39794. _this._delayInfo = [];
  39795. scene._removePendingData(_this);
  39796. var meshes = _this._meshes;
  39797. var numOfMeshes = meshes.length;
  39798. for (var index = 0; index < numOfMeshes; index++) {
  39799. _this._applyToMesh(meshes[index]);
  39800. }
  39801. if (onLoaded) {
  39802. onLoaded();
  39803. }
  39804. }, function () { }, scene.database);
  39805. };
  39806. /**
  39807. * Invert the geometry to move from a right handed system to a left handed one.
  39808. */
  39809. Geometry.prototype.toLeftHanded = function () {
  39810. // Flip faces
  39811. var tIndices = this.getIndices(false);
  39812. if (tIndices != null && tIndices.length > 0) {
  39813. for (var i = 0; i < tIndices.length; i += 3) {
  39814. var tTemp = tIndices[i + 0];
  39815. tIndices[i + 0] = tIndices[i + 2];
  39816. tIndices[i + 2] = tTemp;
  39817. }
  39818. this.setIndices(tIndices);
  39819. }
  39820. // Negate position.z
  39821. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39822. if (tPositions != null && tPositions.length > 0) {
  39823. for (var i = 0; i < tPositions.length; i += 3) {
  39824. tPositions[i + 2] = -tPositions[i + 2];
  39825. }
  39826. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39827. }
  39828. // Negate normal.z
  39829. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39830. if (tNormals != null && tNormals.length > 0) {
  39831. for (var i = 0; i < tNormals.length; i += 3) {
  39832. tNormals[i + 2] = -tNormals[i + 2];
  39833. }
  39834. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39835. }
  39836. };
  39837. Geometry.prototype.isDisposed = function () {
  39838. return this._isDisposed;
  39839. };
  39840. Geometry.prototype._disposeVertexArrayObjects = function () {
  39841. if (this._vertexArrayObjects) {
  39842. for (var kind in this._vertexArrayObjects) {
  39843. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39844. }
  39845. this._vertexArrayObjects = {};
  39846. }
  39847. };
  39848. Geometry.prototype.dispose = function () {
  39849. var meshes = this._meshes;
  39850. var numOfMeshes = meshes.length;
  39851. var index;
  39852. for (index = 0; index < numOfMeshes; index++) {
  39853. this.releaseForMesh(meshes[index]);
  39854. }
  39855. this._meshes = [];
  39856. this._disposeVertexArrayObjects();
  39857. for (var kind in this._vertexBuffers) {
  39858. this._vertexBuffers[kind].dispose();
  39859. }
  39860. this._vertexBuffers = {};
  39861. this._totalVertices = 0;
  39862. if (this._indexBuffer) {
  39863. this._engine._releaseBuffer(this._indexBuffer);
  39864. }
  39865. this._indexBuffer = null;
  39866. this._indices = [];
  39867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39868. this.delayLoadingFile = null;
  39869. this._delayLoadingFunction = null;
  39870. this._delayInfo = [];
  39871. this._boundingInfo = null;
  39872. this._scene.removeGeometry(this);
  39873. this._isDisposed = true;
  39874. };
  39875. Geometry.prototype.copy = function (id) {
  39876. var vertexData = new BABYLON.VertexData();
  39877. vertexData.indices = [];
  39878. var indices = this.getIndices();
  39879. for (var index = 0; index < indices.length; index++) {
  39880. vertexData.indices.push(indices[index]);
  39881. }
  39882. var updatable = false;
  39883. var stopChecking = false;
  39884. var kind;
  39885. for (kind in this._vertexBuffers) {
  39886. // using slice() to make a copy of the array and not just reference it
  39887. var data = this.getVerticesData(kind);
  39888. if (data instanceof Float32Array) {
  39889. vertexData.set(new Float32Array(data), kind);
  39890. }
  39891. else {
  39892. vertexData.set(data.slice(0), kind);
  39893. }
  39894. if (!stopChecking) {
  39895. updatable = this.getVertexBuffer(kind).isUpdatable();
  39896. stopChecking = !updatable;
  39897. }
  39898. }
  39899. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  39900. geometry.delayLoadState = this.delayLoadState;
  39901. geometry.delayLoadingFile = this.delayLoadingFile;
  39902. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39903. for (kind in this._delayInfo) {
  39904. geometry._delayInfo = geometry._delayInfo || [];
  39905. geometry._delayInfo.push(kind);
  39906. }
  39907. // Bounding info
  39908. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39909. return geometry;
  39910. };
  39911. Geometry.prototype.serialize = function () {
  39912. var serializationObject = {};
  39913. serializationObject.id = this.id;
  39914. if (BABYLON.Tags.HasTags(this)) {
  39915. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39916. }
  39917. return serializationObject;
  39918. };
  39919. Geometry.prototype.serializeVerticeData = function () {
  39920. var serializationObject = this.serialize();
  39921. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39922. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39923. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  39924. serializationObject.positions._updatable = true;
  39925. }
  39926. }
  39927. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39928. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39929. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  39930. serializationObject.normals._updatable = true;
  39931. }
  39932. }
  39933. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39934. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39935. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  39936. serializationObject.uvs._updatable = true;
  39937. }
  39938. }
  39939. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39940. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  39941. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  39942. serializationObject.uv2s._updatable = true;
  39943. }
  39944. }
  39945. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39946. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  39947. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  39948. serializationObject.uv3s._updatable = true;
  39949. }
  39950. }
  39951. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39952. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  39953. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  39954. serializationObject.uv4s._updatable = true;
  39955. }
  39956. }
  39957. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39958. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  39959. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  39960. serializationObject.uv5s._updatable = true;
  39961. }
  39962. }
  39963. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39964. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  39965. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  39966. serializationObject.uv6s._updatable = true;
  39967. }
  39968. }
  39969. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39970. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  39971. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  39972. serializationObject.colors._updatable = true;
  39973. }
  39974. }
  39975. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39976. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39977. serializationObject.matricesIndices._isExpanded = true;
  39978. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  39979. serializationObject.matricesIndices._updatable = true;
  39980. }
  39981. }
  39982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39983. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  39984. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  39985. serializationObject.matricesWeights._updatable = true;
  39986. }
  39987. }
  39988. serializationObject.indices = this.getIndices();
  39989. return serializationObject;
  39990. };
  39991. // Statics
  39992. Geometry.ExtractFromMesh = function (mesh, id) {
  39993. var geometry = mesh._geometry;
  39994. if (!geometry) {
  39995. return null;
  39996. }
  39997. return geometry.copy(id);
  39998. };
  39999. /**
  40000. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40001. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40002. * Be aware Math.random() could cause collisions, but:
  40003. * "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"
  40004. */
  40005. Geometry.RandomId = function () {
  40006. return BABYLON.Tools.RandomId();
  40007. };
  40008. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  40009. var scene = mesh.getScene();
  40010. // Geometry
  40011. var geometryId = parsedGeometry.geometryId;
  40012. if (geometryId) {
  40013. var geometry = scene.getGeometryByID(geometryId);
  40014. if (geometry) {
  40015. geometry.applyToMesh(mesh);
  40016. }
  40017. }
  40018. else if (parsedGeometry instanceof ArrayBuffer) {
  40019. var binaryInfo = mesh._binaryInfo;
  40020. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40021. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40023. }
  40024. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40025. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40027. }
  40028. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40029. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40031. }
  40032. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40033. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40035. }
  40036. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40037. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40039. }
  40040. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40041. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40042. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40043. }
  40044. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40045. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40046. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40047. }
  40048. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40049. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40051. }
  40052. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40053. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40054. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40055. }
  40056. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40057. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40058. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40059. }
  40060. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40061. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40063. }
  40064. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40065. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40066. mesh.setIndices(indicesData);
  40067. }
  40068. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40069. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40070. mesh.subMeshes = [];
  40071. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40072. var materialIndex = subMeshesData[(i * 5) + 0];
  40073. var verticesStart = subMeshesData[(i * 5) + 1];
  40074. var verticesCount = subMeshesData[(i * 5) + 2];
  40075. var indexStart = subMeshesData[(i * 5) + 3];
  40076. var indexCount = subMeshesData[(i * 5) + 4];
  40077. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40078. }
  40079. }
  40080. }
  40081. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40082. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40083. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40084. if (parsedGeometry.uvs) {
  40085. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40086. }
  40087. if (parsedGeometry.uvs2) {
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40089. }
  40090. if (parsedGeometry.uvs3) {
  40091. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40092. }
  40093. if (parsedGeometry.uvs4) {
  40094. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40095. }
  40096. if (parsedGeometry.uvs5) {
  40097. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40098. }
  40099. if (parsedGeometry.uvs6) {
  40100. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40101. }
  40102. if (parsedGeometry.colors) {
  40103. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40104. }
  40105. if (parsedGeometry.matricesIndices) {
  40106. if (!parsedGeometry.matricesIndices._isExpanded) {
  40107. var floatIndices = [];
  40108. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40109. var matricesIndex = parsedGeometry.matricesIndices[i];
  40110. floatIndices.push(matricesIndex & 0x000000FF);
  40111. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40112. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40113. floatIndices.push(matricesIndex >> 24);
  40114. }
  40115. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40116. }
  40117. else {
  40118. delete parsedGeometry.matricesIndices._isExpanded;
  40119. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40120. }
  40121. }
  40122. if (parsedGeometry.matricesIndicesExtra) {
  40123. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40124. var floatIndices = [];
  40125. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40126. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40127. floatIndices.push(matricesIndex & 0x000000FF);
  40128. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40129. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40130. floatIndices.push(matricesIndex >> 24);
  40131. }
  40132. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40133. }
  40134. else {
  40135. delete parsedGeometry.matricesIndices._isExpanded;
  40136. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40137. }
  40138. }
  40139. if (parsedGeometry.matricesWeights) {
  40140. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40141. }
  40142. if (parsedGeometry.matricesWeightsExtra) {
  40143. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40144. }
  40145. mesh.setIndices(parsedGeometry.indices);
  40146. }
  40147. // SubMeshes
  40148. if (parsedGeometry.subMeshes) {
  40149. mesh.subMeshes = [];
  40150. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40151. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40152. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40153. }
  40154. }
  40155. // Flat shading
  40156. if (mesh._shouldGenerateFlatShading) {
  40157. mesh.convertToFlatShadedMesh();
  40158. delete mesh._shouldGenerateFlatShading;
  40159. }
  40160. // Update
  40161. mesh.computeWorldMatrix(true);
  40162. // Octree
  40163. if (scene['_selectionOctree']) {
  40164. scene['_selectionOctree'].addMesh(mesh);
  40165. }
  40166. };
  40167. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40168. if (scene.getGeometryByID(parsedVertexData.id)) {
  40169. return null; // null since geometry could be something else than a box...
  40170. }
  40171. var geometry = new Geometry(parsedVertexData.id, scene);
  40172. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40173. if (parsedVertexData.delayLoadingFile) {
  40174. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40175. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40176. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40177. geometry._delayInfo = [];
  40178. if (parsedVertexData.hasUVs) {
  40179. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40180. }
  40181. if (parsedVertexData.hasUVs2) {
  40182. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40183. }
  40184. if (parsedVertexData.hasUVs3) {
  40185. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40186. }
  40187. if (parsedVertexData.hasUVs4) {
  40188. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40189. }
  40190. if (parsedVertexData.hasUVs5) {
  40191. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40192. }
  40193. if (parsedVertexData.hasUVs6) {
  40194. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40195. }
  40196. if (parsedVertexData.hasColors) {
  40197. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40198. }
  40199. if (parsedVertexData.hasMatricesIndices) {
  40200. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40201. }
  40202. if (parsedVertexData.hasMatricesWeights) {
  40203. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40204. }
  40205. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40206. }
  40207. else {
  40208. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40209. }
  40210. scene.pushGeometry(geometry, true);
  40211. return geometry;
  40212. };
  40213. return Geometry;
  40214. }());
  40215. BABYLON.Geometry = Geometry;
  40216. /////// Primitives //////////////////////////////////////////////
  40217. (function (Geometry) {
  40218. var Primitives;
  40219. (function (Primitives) {
  40220. /// Abstract class
  40221. var _Primitive = (function (_super) {
  40222. __extends(_Primitive, _super);
  40223. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  40224. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  40225. _this._canBeRegenerated = _canBeRegenerated;
  40226. _this._beingRegenerated = true;
  40227. _this.regenerate();
  40228. _this._beingRegenerated = false;
  40229. return _this;
  40230. }
  40231. _Primitive.prototype.canBeRegenerated = function () {
  40232. return this._canBeRegenerated;
  40233. };
  40234. _Primitive.prototype.regenerate = function () {
  40235. if (!this._canBeRegenerated) {
  40236. return;
  40237. }
  40238. this._beingRegenerated = true;
  40239. this.setAllVerticesData(this._regenerateVertexData(), false);
  40240. this._beingRegenerated = false;
  40241. };
  40242. _Primitive.prototype.asNewGeometry = function (id) {
  40243. return _super.prototype.copy.call(this, id);
  40244. };
  40245. // overrides
  40246. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  40247. if (!this._beingRegenerated) {
  40248. return;
  40249. }
  40250. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40251. };
  40252. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  40253. if (!this._beingRegenerated) {
  40254. return;
  40255. }
  40256. _super.prototype.setVerticesData.call(this, kind, data, false);
  40257. };
  40258. // to override
  40259. // protected
  40260. _Primitive.prototype._regenerateVertexData = function () {
  40261. throw new Error("Abstract method");
  40262. };
  40263. _Primitive.prototype.copy = function (id) {
  40264. throw new Error("Must be overriden in sub-classes.");
  40265. };
  40266. _Primitive.prototype.serialize = function () {
  40267. var serializationObject = _super.prototype.serialize.call(this);
  40268. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40269. return serializationObject;
  40270. };
  40271. return _Primitive;
  40272. }(Geometry));
  40273. Primitives._Primitive = _Primitive;
  40274. var Ribbon = (function (_super) {
  40275. __extends(Ribbon, _super);
  40276. // Members
  40277. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  40278. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40279. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40280. _this.pathArray = pathArray;
  40281. _this.closeArray = closeArray;
  40282. _this.closePath = closePath;
  40283. _this.offset = offset;
  40284. _this.side = side;
  40285. return _this;
  40286. }
  40287. Ribbon.prototype._regenerateVertexData = function () {
  40288. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40289. };
  40290. Ribbon.prototype.copy = function (id) {
  40291. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  40292. };
  40293. return Ribbon;
  40294. }(_Primitive));
  40295. Primitives.Ribbon = Ribbon;
  40296. var Box = (function (_super) {
  40297. __extends(Box, _super);
  40298. // Members
  40299. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  40300. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40301. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40302. _this.size = size;
  40303. _this.side = side;
  40304. return _this;
  40305. }
  40306. Box.prototype._regenerateVertexData = function () {
  40307. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40308. };
  40309. Box.prototype.copy = function (id) {
  40310. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40311. };
  40312. Box.prototype.serialize = function () {
  40313. var serializationObject = _super.prototype.serialize.call(this);
  40314. serializationObject.size = this.size;
  40315. return serializationObject;
  40316. };
  40317. Box.Parse = function (parsedBox, scene) {
  40318. if (scene.getGeometryByID(parsedBox.id)) {
  40319. return null; // null since geometry could be something else than a box...
  40320. }
  40321. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40322. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40323. scene.pushGeometry(box, true);
  40324. return box;
  40325. };
  40326. return Box;
  40327. }(_Primitive));
  40328. Primitives.Box = Box;
  40329. var Sphere = (function (_super) {
  40330. __extends(Sphere, _super);
  40331. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  40332. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40333. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40334. _this.segments = segments;
  40335. _this.diameter = diameter;
  40336. _this.side = side;
  40337. return _this;
  40338. }
  40339. Sphere.prototype._regenerateVertexData = function () {
  40340. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40341. };
  40342. Sphere.prototype.copy = function (id) {
  40343. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40344. };
  40345. Sphere.prototype.serialize = function () {
  40346. var serializationObject = _super.prototype.serialize.call(this);
  40347. serializationObject.segments = this.segments;
  40348. serializationObject.diameter = this.diameter;
  40349. return serializationObject;
  40350. };
  40351. Sphere.Parse = function (parsedSphere, scene) {
  40352. if (scene.getGeometryByID(parsedSphere.id)) {
  40353. return null; // null since geometry could be something else than a sphere...
  40354. }
  40355. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40356. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40357. scene.pushGeometry(sphere, true);
  40358. return sphere;
  40359. };
  40360. return Sphere;
  40361. }(_Primitive));
  40362. Primitives.Sphere = Sphere;
  40363. var Disc = (function (_super) {
  40364. __extends(Disc, _super);
  40365. // Members
  40366. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  40367. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40368. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40369. _this.radius = radius;
  40370. _this.tessellation = tessellation;
  40371. _this.side = side;
  40372. return _this;
  40373. }
  40374. Disc.prototype._regenerateVertexData = function () {
  40375. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40376. };
  40377. Disc.prototype.copy = function (id) {
  40378. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40379. };
  40380. return Disc;
  40381. }(_Primitive));
  40382. Primitives.Disc = Disc;
  40383. var Cylinder = (function (_super) {
  40384. __extends(Cylinder, _super);
  40385. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  40386. if (subdivisions === void 0) { subdivisions = 1; }
  40387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40389. _this.height = height;
  40390. _this.diameterTop = diameterTop;
  40391. _this.diameterBottom = diameterBottom;
  40392. _this.tessellation = tessellation;
  40393. _this.subdivisions = subdivisions;
  40394. _this.side = side;
  40395. return _this;
  40396. }
  40397. Cylinder.prototype._regenerateVertexData = function () {
  40398. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40399. };
  40400. Cylinder.prototype.copy = function (id) {
  40401. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40402. };
  40403. Cylinder.prototype.serialize = function () {
  40404. var serializationObject = _super.prototype.serialize.call(this);
  40405. serializationObject.height = this.height;
  40406. serializationObject.diameterTop = this.diameterTop;
  40407. serializationObject.diameterBottom = this.diameterBottom;
  40408. serializationObject.tessellation = this.tessellation;
  40409. return serializationObject;
  40410. };
  40411. Cylinder.Parse = function (parsedCylinder, scene) {
  40412. if (scene.getGeometryByID(parsedCylinder.id)) {
  40413. return null; // null since geometry could be something else than a cylinder...
  40414. }
  40415. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40416. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40417. scene.pushGeometry(cylinder, true);
  40418. return cylinder;
  40419. };
  40420. return Cylinder;
  40421. }(_Primitive));
  40422. Primitives.Cylinder = Cylinder;
  40423. var Torus = (function (_super) {
  40424. __extends(Torus, _super);
  40425. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  40426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40428. _this.diameter = diameter;
  40429. _this.thickness = thickness;
  40430. _this.tessellation = tessellation;
  40431. _this.side = side;
  40432. return _this;
  40433. }
  40434. Torus.prototype._regenerateVertexData = function () {
  40435. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40436. };
  40437. Torus.prototype.copy = function (id) {
  40438. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40439. };
  40440. Torus.prototype.serialize = function () {
  40441. var serializationObject = _super.prototype.serialize.call(this);
  40442. serializationObject.diameter = this.diameter;
  40443. serializationObject.thickness = this.thickness;
  40444. serializationObject.tessellation = this.tessellation;
  40445. return serializationObject;
  40446. };
  40447. Torus.Parse = function (parsedTorus, scene) {
  40448. if (scene.getGeometryByID(parsedTorus.id)) {
  40449. return null; // null since geometry could be something else than a torus...
  40450. }
  40451. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40452. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40453. scene.pushGeometry(torus, true);
  40454. return torus;
  40455. };
  40456. return Torus;
  40457. }(_Primitive));
  40458. Primitives.Torus = Torus;
  40459. var Ground = (function (_super) {
  40460. __extends(Ground, _super);
  40461. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  40462. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40463. _this.width = width;
  40464. _this.height = height;
  40465. _this.subdivisions = subdivisions;
  40466. return _this;
  40467. }
  40468. Ground.prototype._regenerateVertexData = function () {
  40469. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40470. };
  40471. Ground.prototype.copy = function (id) {
  40472. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40473. };
  40474. Ground.prototype.serialize = function () {
  40475. var serializationObject = _super.prototype.serialize.call(this);
  40476. serializationObject.width = this.width;
  40477. serializationObject.height = this.height;
  40478. serializationObject.subdivisions = this.subdivisions;
  40479. return serializationObject;
  40480. };
  40481. Ground.Parse = function (parsedGround, scene) {
  40482. if (scene.getGeometryByID(parsedGround.id)) {
  40483. return null; // null since geometry could be something else than a ground...
  40484. }
  40485. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40486. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40487. scene.pushGeometry(ground, true);
  40488. return ground;
  40489. };
  40490. return Ground;
  40491. }(_Primitive));
  40492. Primitives.Ground = Ground;
  40493. var TiledGround = (function (_super) {
  40494. __extends(TiledGround, _super);
  40495. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  40496. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40497. _this.xmin = xmin;
  40498. _this.zmin = zmin;
  40499. _this.xmax = xmax;
  40500. _this.zmax = zmax;
  40501. _this.subdivisions = subdivisions;
  40502. _this.precision = precision;
  40503. return _this;
  40504. }
  40505. TiledGround.prototype._regenerateVertexData = function () {
  40506. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40507. };
  40508. TiledGround.prototype.copy = function (id) {
  40509. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40510. };
  40511. return TiledGround;
  40512. }(_Primitive));
  40513. Primitives.TiledGround = TiledGround;
  40514. var Plane = (function (_super) {
  40515. __extends(Plane, _super);
  40516. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  40517. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40518. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40519. _this.size = size;
  40520. _this.side = side;
  40521. return _this;
  40522. }
  40523. Plane.prototype._regenerateVertexData = function () {
  40524. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40525. };
  40526. Plane.prototype.copy = function (id) {
  40527. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40528. };
  40529. Plane.prototype.serialize = function () {
  40530. var serializationObject = _super.prototype.serialize.call(this);
  40531. serializationObject.size = this.size;
  40532. return serializationObject;
  40533. };
  40534. Plane.Parse = function (parsedPlane, scene) {
  40535. if (scene.getGeometryByID(parsedPlane.id)) {
  40536. return null; // null since geometry could be something else than a ground...
  40537. }
  40538. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40539. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40540. scene.pushGeometry(plane, true);
  40541. return plane;
  40542. };
  40543. return Plane;
  40544. }(_Primitive));
  40545. Primitives.Plane = Plane;
  40546. var TorusKnot = (function (_super) {
  40547. __extends(TorusKnot, _super);
  40548. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  40549. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40550. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40551. _this.radius = radius;
  40552. _this.tube = tube;
  40553. _this.radialSegments = radialSegments;
  40554. _this.tubularSegments = tubularSegments;
  40555. _this.p = p;
  40556. _this.q = q;
  40557. _this.side = side;
  40558. return _this;
  40559. }
  40560. TorusKnot.prototype._regenerateVertexData = function () {
  40561. 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 });
  40562. };
  40563. TorusKnot.prototype.copy = function (id) {
  40564. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40565. };
  40566. TorusKnot.prototype.serialize = function () {
  40567. var serializationObject = _super.prototype.serialize.call(this);
  40568. serializationObject.radius = this.radius;
  40569. serializationObject.tube = this.tube;
  40570. serializationObject.radialSegments = this.radialSegments;
  40571. serializationObject.tubularSegments = this.tubularSegments;
  40572. serializationObject.p = this.p;
  40573. serializationObject.q = this.q;
  40574. return serializationObject;
  40575. };
  40576. ;
  40577. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  40578. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40579. return null; // null since geometry could be something else than a ground...
  40580. }
  40581. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40582. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40583. scene.pushGeometry(torusKnot, true);
  40584. return torusKnot;
  40585. };
  40586. return TorusKnot;
  40587. }(_Primitive));
  40588. Primitives.TorusKnot = TorusKnot;
  40589. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  40590. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  40591. })(BABYLON || (BABYLON = {}));
  40592. //# sourceMappingURL=babylon.geometry.js.map
  40593. /// <reference path="babylon.mesh.ts" />
  40594. var BABYLON;
  40595. (function (BABYLON) {
  40596. var GroundMesh = (function (_super) {
  40597. __extends(GroundMesh, _super);
  40598. function GroundMesh(name, scene) {
  40599. var _this = _super.call(this, name, scene) || this;
  40600. _this.generateOctree = false;
  40601. _this._worldInverse = new BABYLON.Matrix();
  40602. return _this;
  40603. }
  40604. GroundMesh.prototype.getClassName = function () {
  40605. return "GroundMesh";
  40606. };
  40607. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40608. get: function () {
  40609. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40610. },
  40611. enumerable: true,
  40612. configurable: true
  40613. });
  40614. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40615. get: function () {
  40616. return this._subdivisionsX;
  40617. },
  40618. enumerable: true,
  40619. configurable: true
  40620. });
  40621. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40622. get: function () {
  40623. return this._subdivisionsY;
  40624. },
  40625. enumerable: true,
  40626. configurable: true
  40627. });
  40628. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40629. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40630. this._subdivisionsX = chunksCount;
  40631. this._subdivisionsY = chunksCount;
  40632. this.subdivide(chunksCount);
  40633. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40634. };
  40635. /**
  40636. * Returns a height (y) value in the Worl system :
  40637. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40638. * Returns the ground y position if (x, z) are outside the ground surface.
  40639. */
  40640. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40641. var world = this.getWorldMatrix();
  40642. var invMat = BABYLON.Tmp.Matrix[5];
  40643. world.invertToRef(invMat);
  40644. var tmpVect = BABYLON.Tmp.Vector3[8];
  40645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40646. x = tmpVect.x;
  40647. z = tmpVect.z;
  40648. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40649. return this.position.y;
  40650. }
  40651. if (!this._heightQuads || this._heightQuads.length == 0) {
  40652. this._initHeightQuads();
  40653. this._computeHeightQuads();
  40654. }
  40655. var facet = this._getFacetAt(x, z);
  40656. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40657. // return y in the World system
  40658. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40659. return tmpVect.y;
  40660. };
  40661. /**
  40662. * Returns a normalized vector (Vector3) orthogonal to the ground
  40663. * at the ground coordinates (x, z) expressed in the World system.
  40664. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40665. */
  40666. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40667. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40668. this.getNormalAtCoordinatesToRef(x, z, normal);
  40669. return normal;
  40670. };
  40671. /**
  40672. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40673. * at the ground coordinates (x, z) expressed in the World system.
  40674. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40675. * Returns the GroundMesh.
  40676. */
  40677. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40678. var world = this.getWorldMatrix();
  40679. var tmpMat = BABYLON.Tmp.Matrix[5];
  40680. world.invertToRef(tmpMat);
  40681. var tmpVect = BABYLON.Tmp.Vector3[8];
  40682. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40683. x = tmpVect.x;
  40684. z = tmpVect.z;
  40685. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40686. return this;
  40687. }
  40688. if (!this._heightQuads || this._heightQuads.length == 0) {
  40689. this._initHeightQuads();
  40690. this._computeHeightQuads();
  40691. }
  40692. var facet = this._getFacetAt(x, z);
  40693. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40694. return this;
  40695. };
  40696. /**
  40697. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40698. * if the ground has been updated.
  40699. * This can be used in the render loop.
  40700. * Returns the GroundMesh.
  40701. */
  40702. GroundMesh.prototype.updateCoordinateHeights = function () {
  40703. if (!this._heightQuads || this._heightQuads.length == 0) {
  40704. this._initHeightQuads();
  40705. }
  40706. this._computeHeightQuads();
  40707. return this;
  40708. };
  40709. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40710. GroundMesh.prototype._getFacetAt = function (x, z) {
  40711. // retrieve col and row from x, z coordinates in the ground local system
  40712. var subdivisionsX = this._subdivisionsX;
  40713. var subdivisionsY = this._subdivisionsY;
  40714. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40715. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40716. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40717. var facet;
  40718. if (z < quad.slope.x * x + quad.slope.y) {
  40719. facet = quad.facet1;
  40720. }
  40721. else {
  40722. facet = quad.facet2;
  40723. }
  40724. return facet;
  40725. };
  40726. // Creates and populates the heightMap array with "facet" elements :
  40727. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40728. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40729. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40730. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40731. // Returns the GroundMesh.
  40732. GroundMesh.prototype._initHeightQuads = function () {
  40733. var subdivisionsX = this._subdivisionsX;
  40734. var subdivisionsY = this._subdivisionsY;
  40735. this._heightQuads = new Array();
  40736. for (var row = 0; row < subdivisionsY; row++) {
  40737. for (var col = 0; col < subdivisionsX; col++) {
  40738. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  40739. this._heightQuads[row * subdivisionsX + col] = quad;
  40740. }
  40741. }
  40742. return this;
  40743. };
  40744. // Compute each quad element values and update the the heightMap array :
  40745. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40746. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40747. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40748. // Returns the GroundMesh.
  40749. GroundMesh.prototype._computeHeightQuads = function () {
  40750. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40751. var v1 = BABYLON.Tmp.Vector3[3];
  40752. var v2 = BABYLON.Tmp.Vector3[2];
  40753. var v3 = BABYLON.Tmp.Vector3[1];
  40754. var v4 = BABYLON.Tmp.Vector3[0];
  40755. var v1v2 = BABYLON.Tmp.Vector3[4];
  40756. var v1v3 = BABYLON.Tmp.Vector3[5];
  40757. var v1v4 = BABYLON.Tmp.Vector3[6];
  40758. var norm1 = BABYLON.Tmp.Vector3[7];
  40759. var norm2 = BABYLON.Tmp.Vector3[8];
  40760. var i = 0;
  40761. var j = 0;
  40762. var k = 0;
  40763. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40764. var h = 0;
  40765. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40766. var d2 = 0;
  40767. var subdivisionsX = this._subdivisionsX;
  40768. var subdivisionsY = this._subdivisionsY;
  40769. for (var row = 0; row < subdivisionsY; row++) {
  40770. for (var col = 0; col < subdivisionsX; col++) {
  40771. i = col * 3;
  40772. j = row * (subdivisionsX + 1) * 3;
  40773. k = (row + 1) * (subdivisionsX + 1) * 3;
  40774. v1.x = positions[j + i];
  40775. v1.y = positions[j + i + 1];
  40776. v1.z = positions[j + i + 2];
  40777. v2.x = positions[j + i + 3];
  40778. v2.y = positions[j + i + 4];
  40779. v2.z = positions[j + i + 5];
  40780. v3.x = positions[k + i];
  40781. v3.y = positions[k + i + 1];
  40782. v3.z = positions[k + i + 2];
  40783. v4.x = positions[k + i + 3];
  40784. v4.y = positions[k + i + 4];
  40785. v4.z = positions[k + i + 5];
  40786. // 2D slope V1V4
  40787. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40788. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40789. // facet equations :
  40790. // we compute each facet normal vector
  40791. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40792. // we compute the value d by applying the equation to v1 which belongs to the plane
  40793. // then we store the facet equation in a Vector4
  40794. v2.subtractToRef(v1, v1v2);
  40795. v3.subtractToRef(v1, v1v3);
  40796. v4.subtractToRef(v1, v1v4);
  40797. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40798. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40799. norm1.normalize();
  40800. norm2.normalize();
  40801. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40802. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40803. var quad = this._heightQuads[row * subdivisionsX + col];
  40804. quad.slope.copyFromFloats(cd, h);
  40805. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40806. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40807. }
  40808. }
  40809. return this;
  40810. };
  40811. return GroundMesh;
  40812. }(BABYLON.Mesh));
  40813. BABYLON.GroundMesh = GroundMesh;
  40814. })(BABYLON || (BABYLON = {}));
  40815. //# sourceMappingURL=babylon.groundMesh.js.map
  40816. /// <reference path="babylon.mesh.ts" />
  40817. var BABYLON;
  40818. (function (BABYLON) {
  40819. var LinesMesh = (function (_super) {
  40820. __extends(LinesMesh, _super);
  40821. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  40822. if (parent === void 0) { parent = null; }
  40823. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40824. _this.color = new BABYLON.Color3(1, 1, 1);
  40825. _this.alpha = 1;
  40826. _this._positionBuffer = {};
  40827. if (source) {
  40828. _this.color = source.color.clone();
  40829. _this.alpha = source.alpha;
  40830. }
  40831. _this._intersectionThreshold = 0.1;
  40832. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  40833. attributes: [BABYLON.VertexBuffer.PositionKind],
  40834. uniforms: ["worldViewProjection", "color"],
  40835. needAlphaBlending: true
  40836. });
  40837. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  40838. return _this;
  40839. }
  40840. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40841. /**
  40842. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40843. * This margin is expressed in world space coordinates, so its value may vary.
  40844. * Default value is 0.1
  40845. * @returns the intersection Threshold value.
  40846. */
  40847. get: function () {
  40848. return this._intersectionThreshold;
  40849. },
  40850. /**
  40851. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40852. * This margin is expressed in world space coordinates, so its value may vary.
  40853. * @param value the new threshold to apply
  40854. */
  40855. set: function (value) {
  40856. if (this._intersectionThreshold === value) {
  40857. return;
  40858. }
  40859. this._intersectionThreshold = value;
  40860. if (this.geometry) {
  40861. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40862. }
  40863. },
  40864. enumerable: true,
  40865. configurable: true
  40866. });
  40867. /**
  40868. * Returns the string "LineMesh"
  40869. */
  40870. LinesMesh.prototype.getClassName = function () {
  40871. return "LinesMesh";
  40872. };
  40873. Object.defineProperty(LinesMesh.prototype, "material", {
  40874. get: function () {
  40875. return this._colorShader;
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40881. get: function () {
  40882. return false;
  40883. },
  40884. enumerable: true,
  40885. configurable: true
  40886. });
  40887. LinesMesh.prototype.createInstance = function (name) {
  40888. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40889. return null;
  40890. };
  40891. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40892. var engine = this.getScene().getEngine();
  40893. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  40894. // VBOs
  40895. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  40896. // Color
  40897. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40898. return this;
  40899. };
  40900. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40901. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40902. return this;
  40903. }
  40904. var engine = this.getScene().getEngine();
  40905. // Draw order
  40906. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40907. return this;
  40908. };
  40909. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40910. this._colorShader.dispose();
  40911. _super.prototype.dispose.call(this, doNotRecurse);
  40912. };
  40913. /**
  40914. * Returns a new LineMesh object cloned from the current one.
  40915. */
  40916. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40917. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40918. };
  40919. return LinesMesh;
  40920. }(BABYLON.Mesh));
  40921. BABYLON.LinesMesh = LinesMesh;
  40922. })(BABYLON || (BABYLON = {}));
  40923. //# sourceMappingURL=babylon.linesMesh.js.map
  40924. var BABYLON;
  40925. (function (BABYLON) {
  40926. var DefaultLoadingScreen = (function () {
  40927. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  40928. if (_loadingText === void 0) { _loadingText = ""; }
  40929. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  40930. var _this = this;
  40931. this._renderingCanvas = _renderingCanvas;
  40932. this._loadingText = _loadingText;
  40933. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  40934. // Resize
  40935. this._resizeLoadingUI = function () {
  40936. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  40937. _this._loadingDiv.style.position = "absolute";
  40938. _this._loadingDiv.style.left = canvasRect.left + "px";
  40939. _this._loadingDiv.style.top = canvasRect.top + "px";
  40940. _this._loadingDiv.style.width = canvasRect.width + "px";
  40941. _this._loadingDiv.style.height = canvasRect.height + "px";
  40942. };
  40943. }
  40944. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  40945. var _this = this;
  40946. if (this._loadingDiv) {
  40947. // Do not add a loading screen if there is already one
  40948. return;
  40949. }
  40950. this._loadingDiv = document.createElement("div");
  40951. this._loadingDiv.id = "babylonjsLoadingDiv";
  40952. this._loadingDiv.style.opacity = "0";
  40953. this._loadingDiv.style.transition = "opacity 1.5s ease";
  40954. // Loading text
  40955. this._loadingTextDiv = document.createElement("div");
  40956. this._loadingTextDiv.style.position = "absolute";
  40957. this._loadingTextDiv.style.left = "0";
  40958. this._loadingTextDiv.style.top = "50%";
  40959. this._loadingTextDiv.style.marginTop = "80px";
  40960. this._loadingTextDiv.style.width = "100%";
  40961. this._loadingTextDiv.style.height = "20px";
  40962. this._loadingTextDiv.style.fontFamily = "Arial";
  40963. this._loadingTextDiv.style.fontSize = "14px";
  40964. this._loadingTextDiv.style.color = "white";
  40965. this._loadingTextDiv.style.textAlign = "center";
  40966. this._loadingTextDiv.innerHTML = "Loading";
  40967. this._loadingDiv.appendChild(this._loadingTextDiv);
  40968. //set the predefined text
  40969. this._loadingTextDiv.innerHTML = this._loadingText;
  40970. // Loading img
  40971. var imgBack = new Image();
  40972. 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==";
  40973. imgBack.style.position = "absolute";
  40974. imgBack.style.left = "50%";
  40975. imgBack.style.top = "50%";
  40976. imgBack.style.marginLeft = "-50px";
  40977. imgBack.style.marginTop = "-50px";
  40978. imgBack.style.transition = "transform 1.0s ease";
  40979. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  40980. var deg = 360;
  40981. var onTransitionEnd = function () {
  40982. deg += 360;
  40983. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  40984. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  40985. };
  40986. imgBack.addEventListener("transitionend", onTransitionEnd);
  40987. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  40988. this._loadingDiv.appendChild(imgBack);
  40989. // front image
  40990. var imgFront = new Image();
  40991. 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=";
  40992. imgFront.style.position = "absolute";
  40993. imgFront.style.left = "50%";
  40994. imgFront.style.top = "50%";
  40995. imgFront.style.marginLeft = "-50px";
  40996. imgFront.style.marginTop = "-50px";
  40997. this._loadingDiv.appendChild(imgFront);
  40998. this._resizeLoadingUI();
  40999. window.addEventListener("resize", this._resizeLoadingUI);
  41000. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41001. document.body.appendChild(this._loadingDiv);
  41002. setTimeout(function () {
  41003. _this._loadingDiv.style.opacity = "1";
  41004. imgBack.style.transform = "rotateZ(360deg)";
  41005. imgBack.style.webkitTransform = "rotateZ(360deg)";
  41006. }, 0);
  41007. };
  41008. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  41009. var _this = this;
  41010. if (!this._loadingDiv) {
  41011. return;
  41012. }
  41013. var onTransitionEnd = function () {
  41014. if (!_this._loadingDiv) {
  41015. return;
  41016. }
  41017. document.body.removeChild(_this._loadingDiv);
  41018. window.removeEventListener("resize", _this._resizeLoadingUI);
  41019. _this._loadingDiv = null;
  41020. };
  41021. this._loadingDiv.style.opacity = "0";
  41022. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  41023. };
  41024. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  41025. set: function (text) {
  41026. this._loadingText = text;
  41027. if (this._loadingTextDiv) {
  41028. this._loadingTextDiv.innerHTML = this._loadingText;
  41029. }
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  41035. get: function () {
  41036. return this._loadingDivBackgroundColor;
  41037. },
  41038. set: function (color) {
  41039. this._loadingDivBackgroundColor = color;
  41040. if (!this._loadingDiv) {
  41041. return;
  41042. }
  41043. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41044. },
  41045. enumerable: true,
  41046. configurable: true
  41047. });
  41048. return DefaultLoadingScreen;
  41049. }());
  41050. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  41051. })(BABYLON || (BABYLON = {}));
  41052. //# sourceMappingURL=babylon.loadingScreen.js.map
  41053. var BABYLON;
  41054. (function (BABYLON) {
  41055. var AudioEngine = (function () {
  41056. function AudioEngine() {
  41057. this._audioContext = null;
  41058. this._audioContextInitialized = false;
  41059. this.canUseWebAudio = false;
  41060. this.WarnedWebAudioUnsupported = false;
  41061. this.unlocked = false;
  41062. this.isMP3supported = false;
  41063. this.isOGGsupported = false;
  41064. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41065. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41066. this.canUseWebAudio = true;
  41067. }
  41068. var audioElem = document.createElement('audio');
  41069. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41070. this.isMP3supported = true;
  41071. }
  41072. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41073. this.isOGGsupported = true;
  41074. }
  41075. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41076. this._unlockiOSaudio();
  41077. }
  41078. else {
  41079. this.unlocked = true;
  41080. }
  41081. }
  41082. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41083. get: function () {
  41084. if (!this._audioContextInitialized) {
  41085. this._initializeAudioContext();
  41086. }
  41087. return this._audioContext;
  41088. },
  41089. enumerable: true,
  41090. configurable: true
  41091. });
  41092. AudioEngine.prototype._unlockiOSaudio = function () {
  41093. var _this = this;
  41094. var unlockaudio = function () {
  41095. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41096. var source = _this.audioContext.createBufferSource();
  41097. source.buffer = buffer;
  41098. source.connect(_this.audioContext.destination);
  41099. source.start(0);
  41100. setTimeout(function () {
  41101. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41102. _this.unlocked = true;
  41103. window.removeEventListener('touchend', unlockaudio, false);
  41104. if (_this.onAudioUnlocked) {
  41105. _this.onAudioUnlocked();
  41106. }
  41107. }
  41108. }, 0);
  41109. };
  41110. window.addEventListener('touchend', unlockaudio, false);
  41111. };
  41112. AudioEngine.prototype._initializeAudioContext = function () {
  41113. try {
  41114. if (this.canUseWebAudio) {
  41115. this._audioContext = new AudioContext();
  41116. // create a global volume gain node
  41117. this.masterGain = this._audioContext.createGain();
  41118. this.masterGain.gain.value = 1;
  41119. this.masterGain.connect(this._audioContext.destination);
  41120. this._audioContextInitialized = true;
  41121. }
  41122. }
  41123. catch (e) {
  41124. this.canUseWebAudio = false;
  41125. BABYLON.Tools.Error("Web Audio: " + e.message);
  41126. }
  41127. };
  41128. AudioEngine.prototype.dispose = function () {
  41129. if (this.canUseWebAudio && this._audioContextInitialized) {
  41130. if (this._connectedAnalyser) {
  41131. this._connectedAnalyser.stopDebugCanvas();
  41132. this._connectedAnalyser.dispose();
  41133. this.masterGain.disconnect();
  41134. this.masterGain.connect(this._audioContext.destination);
  41135. this._connectedAnalyser = null;
  41136. }
  41137. this.masterGain.gain.value = 1;
  41138. }
  41139. this.WarnedWebAudioUnsupported = false;
  41140. };
  41141. AudioEngine.prototype.getGlobalVolume = function () {
  41142. if (this.canUseWebAudio && this._audioContextInitialized) {
  41143. return this.masterGain.gain.value;
  41144. }
  41145. else {
  41146. return -1;
  41147. }
  41148. };
  41149. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41150. if (this.canUseWebAudio && this._audioContextInitialized) {
  41151. this.masterGain.gain.value = newVolume;
  41152. }
  41153. };
  41154. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41155. if (this._connectedAnalyser) {
  41156. this._connectedAnalyser.stopDebugCanvas();
  41157. }
  41158. if (this.canUseWebAudio && this._audioContextInitialized) {
  41159. this._connectedAnalyser = analyser;
  41160. this.masterGain.disconnect();
  41161. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41162. }
  41163. };
  41164. return AudioEngine;
  41165. }());
  41166. BABYLON.AudioEngine = AudioEngine;
  41167. })(BABYLON || (BABYLON = {}));
  41168. //# sourceMappingURL=babylon.audioEngine.js.map
  41169. var BABYLON;
  41170. (function (BABYLON) {
  41171. var Sound = (function () {
  41172. /**
  41173. * Create a sound and attach it to a scene
  41174. * @param name Name of your sound
  41175. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41176. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41177. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41178. */
  41179. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41180. var _this = this;
  41181. this.autoplay = false;
  41182. this.loop = false;
  41183. this.useCustomAttenuation = false;
  41184. this.spatialSound = false;
  41185. this.refDistance = 1;
  41186. this.rolloffFactor = 1;
  41187. this.maxDistance = 100;
  41188. this.distanceModel = "linear";
  41189. this._panningModel = "equalpower";
  41190. this._playbackRate = 1;
  41191. this._streaming = false;
  41192. this._startTime = 0;
  41193. this._startOffset = 0;
  41194. this._position = BABYLON.Vector3.Zero();
  41195. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41196. this._volume = 1;
  41197. this._isLoaded = false;
  41198. this._isReadyToPlay = false;
  41199. this.isPlaying = false;
  41200. this.isPaused = false;
  41201. this._isDirectional = false;
  41202. // Used if you'd like to create a directional sound.
  41203. // If not set, the sound will be omnidirectional
  41204. this._coneInnerAngle = 360;
  41205. this._coneOuterAngle = 360;
  41206. this._coneOuterGain = 0;
  41207. this._isOutputConnected = false;
  41208. this._urlType = "Unknown";
  41209. this.name = name;
  41210. this._scene = scene;
  41211. this._readyToPlayCallback = readyToPlayCallback;
  41212. // Default custom attenuation function is a linear attenuation
  41213. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41214. if (currentDistance < maxDistance) {
  41215. return currentVolume * (1 - currentDistance / maxDistance);
  41216. }
  41217. else {
  41218. return 0;
  41219. }
  41220. };
  41221. if (options) {
  41222. this.autoplay = options.autoplay || false;
  41223. this.loop = options.loop || false;
  41224. // if volume === 0, we need another way to check this option
  41225. if (options.volume !== undefined) {
  41226. this._volume = options.volume;
  41227. }
  41228. this.spatialSound = options.spatialSound || false;
  41229. this.maxDistance = options.maxDistance || 100;
  41230. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41231. this.rolloffFactor = options.rolloffFactor || 1;
  41232. this.refDistance = options.refDistance || 1;
  41233. this.distanceModel = options.distanceModel || "linear";
  41234. this._playbackRate = options.playbackRate || 1;
  41235. this._streaming = options.streaming || false;
  41236. }
  41237. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41238. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41239. this._soundGain.gain.value = this._volume;
  41240. this._inputAudioNode = this._soundGain;
  41241. this._ouputAudioNode = this._soundGain;
  41242. if (this.spatialSound) {
  41243. this._createSpatialParameters();
  41244. }
  41245. this._scene.mainSoundTrack.AddSound(this);
  41246. var validParameter = true;
  41247. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41248. if (urlOrArrayBuffer) {
  41249. if (typeof (urlOrArrayBuffer) === "string")
  41250. this._urlType = "String";
  41251. if (Array.isArray(urlOrArrayBuffer))
  41252. this._urlType = "Array";
  41253. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41254. this._urlType = "ArrayBuffer";
  41255. var urls = [];
  41256. var codecSupportedFound = false;
  41257. switch (this._urlType) {
  41258. case "ArrayBuffer":
  41259. if (urlOrArrayBuffer.byteLength > 0) {
  41260. codecSupportedFound = true;
  41261. this._soundLoaded(urlOrArrayBuffer);
  41262. }
  41263. break;
  41264. case "String":
  41265. urls.push(urlOrArrayBuffer);
  41266. case "Array":
  41267. if (urls.length === 0)
  41268. urls = urlOrArrayBuffer;
  41269. // If we found a supported format, we load it immediately and stop the loop
  41270. for (var i = 0; i < urls.length; i++) {
  41271. var url = urls[i];
  41272. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41273. codecSupportedFound = true;
  41274. }
  41275. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41276. codecSupportedFound = true;
  41277. }
  41278. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41279. codecSupportedFound = true;
  41280. }
  41281. if (codecSupportedFound) {
  41282. // Loading sound using XHR2
  41283. if (!this._streaming) {
  41284. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41285. }
  41286. else {
  41287. this._htmlAudioElement = new Audio(url);
  41288. this._htmlAudioElement.controls = false;
  41289. this._htmlAudioElement.loop = this.loop;
  41290. this._htmlAudioElement.crossOrigin = "anonymous";
  41291. this._htmlAudioElement.preload = "auto";
  41292. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41293. _this._isReadyToPlay = true;
  41294. if (_this.autoplay) {
  41295. _this.play();
  41296. }
  41297. if (_this._readyToPlayCallback) {
  41298. _this._readyToPlayCallback();
  41299. }
  41300. });
  41301. document.body.appendChild(this._htmlAudioElement);
  41302. }
  41303. break;
  41304. }
  41305. }
  41306. break;
  41307. default:
  41308. validParameter = false;
  41309. break;
  41310. }
  41311. if (!validParameter) {
  41312. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41313. }
  41314. else {
  41315. if (!codecSupportedFound) {
  41316. this._isReadyToPlay = true;
  41317. // Simulating a ready to play event to avoid breaking code path
  41318. if (this._readyToPlayCallback) {
  41319. window.setTimeout(function () {
  41320. _this._readyToPlayCallback();
  41321. }, 1000);
  41322. }
  41323. }
  41324. }
  41325. }
  41326. }
  41327. else {
  41328. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41329. this._scene.mainSoundTrack.AddSound(this);
  41330. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41331. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41332. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41333. }
  41334. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41335. if (this._readyToPlayCallback) {
  41336. window.setTimeout(function () {
  41337. _this._readyToPlayCallback();
  41338. }, 1000);
  41339. }
  41340. }
  41341. }
  41342. Sound.prototype.dispose = function () {
  41343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41344. if (this.isPlaying) {
  41345. this.stop();
  41346. }
  41347. this._isReadyToPlay = false;
  41348. if (this.soundTrackId === -1) {
  41349. this._scene.mainSoundTrack.RemoveSound(this);
  41350. }
  41351. else {
  41352. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41353. }
  41354. if (this._soundGain) {
  41355. this._soundGain.disconnect();
  41356. this._soundGain = null;
  41357. }
  41358. if (this._soundPanner) {
  41359. this._soundPanner.disconnect();
  41360. this._soundPanner = null;
  41361. }
  41362. if (this._soundSource) {
  41363. this._soundSource.disconnect();
  41364. this._soundSource = null;
  41365. }
  41366. this._audioBuffer = null;
  41367. if (this._htmlAudioElement) {
  41368. this._htmlAudioElement.pause();
  41369. this._htmlAudioElement.src = "";
  41370. document.body.removeChild(this._htmlAudioElement);
  41371. }
  41372. if (this._connectedMesh) {
  41373. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41374. this._connectedMesh = null;
  41375. }
  41376. }
  41377. };
  41378. Sound.prototype.isReady = function () {
  41379. return this._isReadyToPlay;
  41380. };
  41381. Sound.prototype._soundLoaded = function (audioData) {
  41382. var _this = this;
  41383. this._isLoaded = true;
  41384. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41385. _this._audioBuffer = buffer;
  41386. _this._isReadyToPlay = true;
  41387. if (_this.autoplay) {
  41388. _this.play();
  41389. }
  41390. if (_this._readyToPlayCallback) {
  41391. _this._readyToPlayCallback();
  41392. }
  41393. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41394. };
  41395. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41396. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41397. this._audioBuffer = audioBuffer;
  41398. this._isReadyToPlay = true;
  41399. }
  41400. };
  41401. Sound.prototype.updateOptions = function (options) {
  41402. if (options) {
  41403. this.loop = options.loop || this.loop;
  41404. this.maxDistance = options.maxDistance || this.maxDistance;
  41405. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41406. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41407. this.refDistance = options.refDistance || this.refDistance;
  41408. this.distanceModel = options.distanceModel || this.distanceModel;
  41409. this._playbackRate = options.playbackRate || this._playbackRate;
  41410. this._updateSpatialParameters();
  41411. if (this.isPlaying) {
  41412. if (this._streaming) {
  41413. this._htmlAudioElement.playbackRate = this._playbackRate;
  41414. }
  41415. else {
  41416. this._soundSource.playbackRate.value = this._playbackRate;
  41417. }
  41418. }
  41419. }
  41420. };
  41421. Sound.prototype._createSpatialParameters = function () {
  41422. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41423. if (this._scene.headphone) {
  41424. this._panningModel = "HRTF";
  41425. }
  41426. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41427. this._updateSpatialParameters();
  41428. this._soundPanner.connect(this._ouputAudioNode);
  41429. this._inputAudioNode = this._soundPanner;
  41430. }
  41431. };
  41432. Sound.prototype._updateSpatialParameters = function () {
  41433. if (this.spatialSound) {
  41434. if (this.useCustomAttenuation) {
  41435. // Tricks to disable in a way embedded Web Audio attenuation
  41436. this._soundPanner.distanceModel = "linear";
  41437. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41438. this._soundPanner.refDistance = 1;
  41439. this._soundPanner.rolloffFactor = 1;
  41440. this._soundPanner.panningModel = this._panningModel;
  41441. }
  41442. else {
  41443. this._soundPanner.distanceModel = this.distanceModel;
  41444. this._soundPanner.maxDistance = this.maxDistance;
  41445. this._soundPanner.refDistance = this.refDistance;
  41446. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41447. this._soundPanner.panningModel = this._panningModel;
  41448. }
  41449. }
  41450. };
  41451. Sound.prototype.switchPanningModelToHRTF = function () {
  41452. this._panningModel = "HRTF";
  41453. this._switchPanningModel();
  41454. };
  41455. Sound.prototype.switchPanningModelToEqualPower = function () {
  41456. this._panningModel = "equalpower";
  41457. this._switchPanningModel();
  41458. };
  41459. Sound.prototype._switchPanningModel = function () {
  41460. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41461. this._soundPanner.panningModel = this._panningModel;
  41462. }
  41463. };
  41464. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41465. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41466. if (this._isOutputConnected) {
  41467. this._ouputAudioNode.disconnect();
  41468. }
  41469. this._ouputAudioNode.connect(soundTrackAudioNode);
  41470. this._isOutputConnected = true;
  41471. }
  41472. };
  41473. /**
  41474. * Transform this sound into a directional source
  41475. * @param coneInnerAngle Size of the inner cone in degree
  41476. * @param coneOuterAngle Size of the outer cone in degree
  41477. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41478. */
  41479. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41480. if (coneOuterAngle < coneInnerAngle) {
  41481. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41482. return;
  41483. }
  41484. this._coneInnerAngle = coneInnerAngle;
  41485. this._coneOuterAngle = coneOuterAngle;
  41486. this._coneOuterGain = coneOuterGain;
  41487. this._isDirectional = true;
  41488. if (this.isPlaying && this.loop) {
  41489. this.stop();
  41490. this.play();
  41491. }
  41492. };
  41493. Sound.prototype.setPosition = function (newPosition) {
  41494. this._position = newPosition;
  41495. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41496. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41497. }
  41498. };
  41499. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41500. this._localDirection = newLocalDirection;
  41501. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41502. this._updateDirection();
  41503. }
  41504. };
  41505. Sound.prototype._updateDirection = function () {
  41506. var mat = this._connectedMesh.getWorldMatrix();
  41507. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41508. direction.normalize();
  41509. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41510. };
  41511. Sound.prototype.updateDistanceFromListener = function () {
  41512. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41513. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41514. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41515. }
  41516. };
  41517. Sound.prototype.setAttenuationFunction = function (callback) {
  41518. this._customAttenuationFunction = callback;
  41519. };
  41520. /**
  41521. * Play the sound
  41522. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41523. * @param offset (optional) Start the sound setting it at a specific time
  41524. */
  41525. Sound.prototype.play = function (time, offset) {
  41526. var _this = this;
  41527. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41528. try {
  41529. if (this._startOffset < 0) {
  41530. time = -this._startOffset;
  41531. this._startOffset = 0;
  41532. }
  41533. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41534. if (!this._soundSource || !this._streamingSource) {
  41535. if (this.spatialSound) {
  41536. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41537. if (this._isDirectional) {
  41538. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41539. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41540. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41541. if (this._connectedMesh) {
  41542. this._updateDirection();
  41543. }
  41544. else {
  41545. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41546. }
  41547. }
  41548. }
  41549. }
  41550. if (this._streaming) {
  41551. if (!this._streamingSource) {
  41552. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41553. this._htmlAudioElement.onended = function () { _this._onended(); };
  41554. this._htmlAudioElement.playbackRate = this._playbackRate;
  41555. }
  41556. this._streamingSource.disconnect();
  41557. this._streamingSource.connect(this._inputAudioNode);
  41558. this._htmlAudioElement.play();
  41559. }
  41560. else {
  41561. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41562. this._soundSource.buffer = this._audioBuffer;
  41563. this._soundSource.connect(this._inputAudioNode);
  41564. this._soundSource.loop = this.loop;
  41565. this._soundSource.playbackRate.value = this._playbackRate;
  41566. this._soundSource.onended = function () { _this._onended(); };
  41567. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  41568. }
  41569. this._startTime = startTime;
  41570. this.isPlaying = true;
  41571. this.isPaused = false;
  41572. }
  41573. catch (ex) {
  41574. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  41575. }
  41576. }
  41577. };
  41578. Sound.prototype._onended = function () {
  41579. this.isPlaying = false;
  41580. if (this.onended) {
  41581. this.onended();
  41582. }
  41583. };
  41584. /**
  41585. * Stop the sound
  41586. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  41587. */
  41588. Sound.prototype.stop = function (time) {
  41589. if (this.isPlaying) {
  41590. if (this._streaming) {
  41591. this._htmlAudioElement.pause();
  41592. // Test needed for Firefox or it will generate an Invalid State Error
  41593. if (this._htmlAudioElement.currentTime > 0) {
  41594. this._htmlAudioElement.currentTime = 0;
  41595. }
  41596. }
  41597. else {
  41598. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41599. this._soundSource.stop(stopTime);
  41600. this._soundSource.onended = null;
  41601. if (!this.isPaused) {
  41602. this._startOffset = 0;
  41603. }
  41604. }
  41605. this.isPlaying = false;
  41606. }
  41607. };
  41608. Sound.prototype.pause = function () {
  41609. if (this.isPlaying) {
  41610. this.isPaused = true;
  41611. if (this._streaming) {
  41612. this._htmlAudioElement.pause();
  41613. }
  41614. else {
  41615. this.stop(0);
  41616. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  41617. }
  41618. }
  41619. };
  41620. Sound.prototype.setVolume = function (newVolume, time) {
  41621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41622. if (time) {
  41623. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  41624. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  41625. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  41626. }
  41627. else {
  41628. this._soundGain.gain.value = newVolume;
  41629. }
  41630. }
  41631. this._volume = newVolume;
  41632. };
  41633. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  41634. this._playbackRate = newPlaybackRate;
  41635. if (this.isPlaying) {
  41636. if (this._streaming) {
  41637. this._htmlAudioElement.playbackRate = this._playbackRate;
  41638. }
  41639. else {
  41640. this._soundSource.playbackRate.value = this._playbackRate;
  41641. }
  41642. }
  41643. };
  41644. Sound.prototype.getVolume = function () {
  41645. return this._volume;
  41646. };
  41647. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  41648. var _this = this;
  41649. if (this._connectedMesh) {
  41650. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41651. this._registerFunc = null;
  41652. }
  41653. this._connectedMesh = meshToConnectTo;
  41654. if (!this.spatialSound) {
  41655. this.spatialSound = true;
  41656. this._createSpatialParameters();
  41657. if (this.isPlaying && this.loop) {
  41658. this.stop();
  41659. this.play();
  41660. }
  41661. }
  41662. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  41663. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  41664. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  41665. };
  41666. Sound.prototype.detachFromMesh = function () {
  41667. if (this._connectedMesh) {
  41668. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41669. this._registerFunc = null;
  41670. this._connectedMesh = null;
  41671. }
  41672. };
  41673. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  41674. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  41675. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  41676. this._updateDirection();
  41677. }
  41678. };
  41679. Sound.prototype.clone = function () {
  41680. var _this = this;
  41681. if (!this._streaming) {
  41682. var setBufferAndRun = function () {
  41683. if (_this._isReadyToPlay) {
  41684. clonedSound._audioBuffer = _this.getAudioBuffer();
  41685. clonedSound._isReadyToPlay = true;
  41686. if (clonedSound.autoplay) {
  41687. clonedSound.play();
  41688. }
  41689. }
  41690. else {
  41691. window.setTimeout(setBufferAndRun, 300);
  41692. }
  41693. };
  41694. var currentOptions = {
  41695. autoplay: this.autoplay, loop: this.loop,
  41696. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  41697. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  41698. refDistance: this.refDistance, distanceModel: this.distanceModel
  41699. };
  41700. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  41701. if (this.useCustomAttenuation) {
  41702. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  41703. }
  41704. clonedSound.setPosition(this._position);
  41705. clonedSound.setPlaybackRate(this._playbackRate);
  41706. setBufferAndRun();
  41707. return clonedSound;
  41708. }
  41709. else {
  41710. return null;
  41711. }
  41712. };
  41713. Sound.prototype.getAudioBuffer = function () {
  41714. return this._audioBuffer;
  41715. };
  41716. Sound.prototype.serialize = function () {
  41717. var serializationObject = {
  41718. name: this.name,
  41719. url: this.name,
  41720. autoplay: this.autoplay,
  41721. loop: this.loop,
  41722. volume: this._volume,
  41723. spatialSound: this.spatialSound,
  41724. maxDistance: this.maxDistance,
  41725. rolloffFactor: this.rolloffFactor,
  41726. refDistance: this.refDistance,
  41727. distanceModel: this.distanceModel,
  41728. playbackRate: this._playbackRate,
  41729. panningModel: this._panningModel,
  41730. soundTrackId: this.soundTrackId
  41731. };
  41732. if (this.spatialSound) {
  41733. if (this._connectedMesh)
  41734. serializationObject.connectedMeshId = this._connectedMesh.id;
  41735. serializationObject.position = this._position.asArray();
  41736. serializationObject.refDistance = this.refDistance;
  41737. serializationObject.distanceModel = this.distanceModel;
  41738. serializationObject.isDirectional = this._isDirectional;
  41739. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  41740. serializationObject.coneInnerAngle = this._coneInnerAngle;
  41741. serializationObject.coneOuterAngle = this._coneOuterAngle;
  41742. serializationObject.coneOuterGain = this._coneOuterGain;
  41743. }
  41744. return serializationObject;
  41745. };
  41746. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  41747. var soundName = parsedSound.name;
  41748. var soundUrl;
  41749. if (parsedSound.url) {
  41750. soundUrl = rootUrl + parsedSound.url;
  41751. }
  41752. else {
  41753. soundUrl = rootUrl + soundName;
  41754. }
  41755. var options = {
  41756. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  41757. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  41758. rolloffFactor: parsedSound.rolloffFactor,
  41759. refDistance: parsedSound.refDistance,
  41760. distanceModel: parsedSound.distanceModel,
  41761. playbackRate: parsedSound.playbackRate
  41762. };
  41763. var newSound;
  41764. if (!sourceSound) {
  41765. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  41766. scene._addPendingData(newSound);
  41767. }
  41768. else {
  41769. var setBufferAndRun = function () {
  41770. if (sourceSound._isReadyToPlay) {
  41771. newSound._audioBuffer = sourceSound.getAudioBuffer();
  41772. newSound._isReadyToPlay = true;
  41773. if (newSound.autoplay) {
  41774. newSound.play();
  41775. }
  41776. }
  41777. else {
  41778. window.setTimeout(setBufferAndRun, 300);
  41779. }
  41780. };
  41781. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  41782. setBufferAndRun();
  41783. }
  41784. if (parsedSound.position) {
  41785. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  41786. newSound.setPosition(soundPosition);
  41787. }
  41788. if (parsedSound.isDirectional) {
  41789. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  41790. if (parsedSound.localDirectionToMesh) {
  41791. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  41792. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  41793. }
  41794. }
  41795. if (parsedSound.connectedMeshId) {
  41796. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  41797. if (connectedMesh) {
  41798. newSound.attachToMesh(connectedMesh);
  41799. }
  41800. }
  41801. return newSound;
  41802. };
  41803. return Sound;
  41804. }());
  41805. BABYLON.Sound = Sound;
  41806. })(BABYLON || (BABYLON = {}));
  41807. //# sourceMappingURL=babylon.sound.js.map
  41808. var BABYLON;
  41809. (function (BABYLON) {
  41810. var SoundTrack = (function () {
  41811. function SoundTrack(scene, options) {
  41812. this.id = -1;
  41813. this._isMainTrack = false;
  41814. this._isInitialized = false;
  41815. this._scene = scene;
  41816. this.soundCollection = new Array();
  41817. this._options = options;
  41818. if (!this._isMainTrack) {
  41819. this._scene.soundTracks.push(this);
  41820. this.id = this._scene.soundTracks.length - 1;
  41821. }
  41822. }
  41823. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  41824. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41825. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  41826. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  41827. if (this._options) {
  41828. if (this._options.volume) {
  41829. this._outputAudioNode.gain.value = this._options.volume;
  41830. }
  41831. if (this._options.mainTrack) {
  41832. this._isMainTrack = this._options.mainTrack;
  41833. }
  41834. }
  41835. this._isInitialized = true;
  41836. }
  41837. };
  41838. SoundTrack.prototype.dispose = function () {
  41839. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41840. if (this._connectedAnalyser) {
  41841. this._connectedAnalyser.stopDebugCanvas();
  41842. }
  41843. while (this.soundCollection.length) {
  41844. this.soundCollection[0].dispose();
  41845. }
  41846. if (this._outputAudioNode) {
  41847. this._outputAudioNode.disconnect();
  41848. }
  41849. this._outputAudioNode = null;
  41850. }
  41851. };
  41852. SoundTrack.prototype.AddSound = function (sound) {
  41853. if (!this._isInitialized) {
  41854. this._initializeSoundTrackAudioGraph();
  41855. }
  41856. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41857. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  41858. }
  41859. if (sound.soundTrackId) {
  41860. if (sound.soundTrackId === -1) {
  41861. this._scene.mainSoundTrack.RemoveSound(sound);
  41862. }
  41863. else {
  41864. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  41865. }
  41866. }
  41867. this.soundCollection.push(sound);
  41868. sound.soundTrackId = this.id;
  41869. };
  41870. SoundTrack.prototype.RemoveSound = function (sound) {
  41871. var index = this.soundCollection.indexOf(sound);
  41872. if (index !== -1) {
  41873. this.soundCollection.splice(index, 1);
  41874. }
  41875. };
  41876. SoundTrack.prototype.setVolume = function (newVolume) {
  41877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41878. this._outputAudioNode.gain.value = newVolume;
  41879. }
  41880. };
  41881. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  41882. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41883. for (var i = 0; i < this.soundCollection.length; i++) {
  41884. this.soundCollection[i].switchPanningModelToHRTF();
  41885. }
  41886. }
  41887. };
  41888. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  41889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41890. for (var i = 0; i < this.soundCollection.length; i++) {
  41891. this.soundCollection[i].switchPanningModelToEqualPower();
  41892. }
  41893. }
  41894. };
  41895. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  41896. if (this._connectedAnalyser) {
  41897. this._connectedAnalyser.stopDebugCanvas();
  41898. }
  41899. this._connectedAnalyser = analyser;
  41900. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41901. this._outputAudioNode.disconnect();
  41902. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  41903. }
  41904. };
  41905. return SoundTrack;
  41906. }());
  41907. BABYLON.SoundTrack = SoundTrack;
  41908. })(BABYLON || (BABYLON = {}));
  41909. //# sourceMappingURL=babylon.soundtrack.js.map
  41910. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  41911. /// <reference path="..\Math\babylon.math.ts" />
  41912. var BABYLON;
  41913. (function (BABYLON) {
  41914. /**
  41915. * Special Glow Blur post process only blurring the alpha channel
  41916. * It enforces keeping the most luminous color in the color channel.
  41917. */
  41918. var GlowBlurPostProcess = (function (_super) {
  41919. __extends(GlowBlurPostProcess, _super);
  41920. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  41921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41922. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  41923. _this.direction = direction;
  41924. _this.blurWidth = blurWidth;
  41925. _this.onApplyObservable.add(function (effect) {
  41926. effect.setFloat2("screenSize", _this.width, _this.height);
  41927. effect.setVector2("direction", _this.direction);
  41928. effect.setFloat("blurWidth", _this.blurWidth);
  41929. });
  41930. return _this;
  41931. }
  41932. return GlowBlurPostProcess;
  41933. }(BABYLON.PostProcess));
  41934. /**
  41935. * The highlight layer Helps adding a glow effect around a mesh.
  41936. *
  41937. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  41938. * glowy meshes to your scene.
  41939. *
  41940. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  41941. */
  41942. var HighlightLayer = (function () {
  41943. /**
  41944. * Instantiates a new highlight Layer and references it to the scene..
  41945. * @param name The name of the layer
  41946. * @param scene The scene to use the layer in
  41947. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  41948. */
  41949. function HighlightLayer(name, scene, options) {
  41950. this._vertexBuffers = {};
  41951. this._mainTextureDesiredSize = { width: 0, height: 0 };
  41952. this._meshes = {};
  41953. this._maxSize = 0;
  41954. this._shouldRender = false;
  41955. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  41956. this._excludedMeshes = {};
  41957. /**
  41958. * Specifies whether or not the inner glow is ACTIVE in the layer.
  41959. */
  41960. this.innerGlow = true;
  41961. /**
  41962. * Specifies whether or not the outer glow is ACTIVE in the layer.
  41963. */
  41964. this.outerGlow = true;
  41965. /**
  41966. * Specifies wether the highlight layer is enabled or not.
  41967. */
  41968. this.isEnabled = true;
  41969. /**
  41970. * An event triggered when the highlight layer has been disposed.
  41971. * @type {BABYLON.Observable}
  41972. */
  41973. this.onDisposeObservable = new BABYLON.Observable();
  41974. /**
  41975. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  41976. * @type {BABYLON.Observable}
  41977. */
  41978. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  41979. /**
  41980. * An event triggered when the highlight layer is being blurred.
  41981. * @type {BABYLON.Observable}
  41982. */
  41983. this.onBeforeBlurObservable = new BABYLON.Observable();
  41984. /**
  41985. * An event triggered when the highlight layer has been blurred.
  41986. * @type {BABYLON.Observable}
  41987. */
  41988. this.onAfterBlurObservable = new BABYLON.Observable();
  41989. /**
  41990. * An event triggered when the glowing blurred texture is being merged in the scene.
  41991. * @type {BABYLON.Observable}
  41992. */
  41993. this.onBeforeComposeObservable = new BABYLON.Observable();
  41994. /**
  41995. * An event triggered when the glowing blurred texture has been merged in the scene.
  41996. * @type {BABYLON.Observable}
  41997. */
  41998. this.onAfterComposeObservable = new BABYLON.Observable();
  41999. /**
  42000. * An event triggered when the highlight layer changes its size.
  42001. * @type {BABYLON.Observable}
  42002. */
  42003. this.onSizeChangedObservable = new BABYLON.Observable();
  42004. this._scene = scene;
  42005. var engine = scene.getEngine();
  42006. this._engine = engine;
  42007. this._maxSize = this._engine.getCaps().maxTextureSize;
  42008. this._scene.highlightLayers.push(this);
  42009. // Warn on stencil.
  42010. if (!this._engine.isStencilEnable) {
  42011. 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 }");
  42012. }
  42013. // Adapt options
  42014. this._options = options || {
  42015. mainTextureRatio: 0.25,
  42016. blurTextureSizeRatio: 0.5,
  42017. blurHorizontalSize: 1,
  42018. blurVerticalSize: 1,
  42019. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  42020. };
  42021. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  42022. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  42023. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  42024. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  42025. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  42026. // VBO
  42027. var vertices = [];
  42028. vertices.push(1, 1);
  42029. vertices.push(-1, 1);
  42030. vertices.push(-1, -1);
  42031. vertices.push(1, -1);
  42032. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  42033. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  42034. // Indices
  42035. var indices = [];
  42036. indices.push(0);
  42037. indices.push(1);
  42038. indices.push(2);
  42039. indices.push(0);
  42040. indices.push(2);
  42041. indices.push(3);
  42042. this._indexBuffer = engine.createIndexBuffer(indices);
  42043. // Effect
  42044. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  42045. // Render target
  42046. this.setMainTextureSize();
  42047. // Create Textures and post processes
  42048. this.createTextureAndPostProcesses();
  42049. }
  42050. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  42051. /**
  42052. * Gets the horizontal size of the blur.
  42053. */
  42054. get: function () {
  42055. return this._horizontalBlurPostprocess.blurWidth;
  42056. },
  42057. /**
  42058. * Specifies the horizontal size of the blur.
  42059. */
  42060. set: function (value) {
  42061. this._horizontalBlurPostprocess.blurWidth = value;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  42067. /**
  42068. * Gets the vertical size of the blur.
  42069. */
  42070. get: function () {
  42071. return this._verticalBlurPostprocess.blurWidth;
  42072. },
  42073. /**
  42074. * Specifies the vertical size of the blur.
  42075. */
  42076. set: function (value) {
  42077. this._verticalBlurPostprocess.blurWidth = value;
  42078. },
  42079. enumerable: true,
  42080. configurable: true
  42081. });
  42082. Object.defineProperty(HighlightLayer.prototype, "camera", {
  42083. /**
  42084. * Gets the camera attached to the layer.
  42085. */
  42086. get: function () {
  42087. return this._options.camera;
  42088. },
  42089. enumerable: true,
  42090. configurable: true
  42091. });
  42092. /**
  42093. * Creates the render target textures and post processes used in the highlight layer.
  42094. */
  42095. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  42096. var _this = this;
  42097. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  42098. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  42099. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  42100. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  42101. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  42102. width: this._mainTextureDesiredSize.width,
  42103. height: this._mainTextureDesiredSize.height
  42104. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42105. this._mainTexture.activeCamera = this._options.camera;
  42106. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42107. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42108. this._mainTexture.anisotropicFilteringLevel = 1;
  42109. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42110. this._mainTexture.renderParticles = false;
  42111. this._mainTexture.renderList = null;
  42112. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  42113. width: blurTextureWidth,
  42114. height: blurTextureHeight
  42115. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42116. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42117. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42118. this._blurTexture.anisotropicFilteringLevel = 16;
  42119. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  42120. this._blurTexture.renderParticles = false;
  42121. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42122. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42123. effect.setTexture("textureSampler", _this._mainTexture);
  42124. });
  42125. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  42126. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42127. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42128. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42129. });
  42130. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42131. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42132. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42133. });
  42134. }
  42135. else {
  42136. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42137. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42138. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42139. });
  42140. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42141. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42142. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42143. });
  42144. }
  42145. this._mainTexture.onAfterUnbindObservable.add(function () {
  42146. _this.onBeforeBlurObservable.notifyObservers(_this);
  42147. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  42148. _this.onAfterBlurObservable.notifyObservers(_this);
  42149. });
  42150. // Custom render function
  42151. var renderSubMesh = function (subMesh) {
  42152. var mesh = subMesh.getRenderingMesh();
  42153. var scene = _this._scene;
  42154. var engine = scene.getEngine();
  42155. // Culling
  42156. engine.setState(subMesh.getMaterial().backFaceCulling);
  42157. // Managing instances
  42158. var batch = mesh._getInstancesRenderList(subMesh._id);
  42159. if (batch.mustReturn) {
  42160. return;
  42161. }
  42162. // Excluded Mesh
  42163. if (_this._excludedMeshes[mesh.uniqueId]) {
  42164. return;
  42165. }
  42166. ;
  42167. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42168. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  42169. var material = subMesh.getMaterial();
  42170. var emissiveTexture = null;
  42171. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  42172. emissiveTexture = material.emissiveTexture;
  42173. }
  42174. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  42175. engine.enableEffect(_this._glowMapGenerationEffect);
  42176. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  42177. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  42178. if (highlightLayerMesh) {
  42179. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  42180. }
  42181. else {
  42182. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  42183. }
  42184. // Alpha test
  42185. if (material && material.needAlphaTesting()) {
  42186. var alphaTexture = material.getAlphaTestTexture();
  42187. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  42188. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42189. }
  42190. // Glow emissive only
  42191. if (emissiveTexture) {
  42192. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  42193. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  42194. }
  42195. // Bones
  42196. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42197. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42198. }
  42199. // Draw
  42200. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  42201. }
  42202. else {
  42203. // Need to reset refresh rate of the shadowMap
  42204. _this._mainTexture.resetRefreshCounter();
  42205. }
  42206. };
  42207. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42208. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  42209. var index;
  42210. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42211. renderSubMesh(opaqueSubMeshes.data[index]);
  42212. }
  42213. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42214. renderSubMesh(alphaTestSubMeshes.data[index]);
  42215. }
  42216. for (index = 0; index < transparentSubMeshes.length; index++) {
  42217. renderSubMesh(transparentSubMeshes.data[index]);
  42218. }
  42219. };
  42220. this._mainTexture.onClearObservable.add(function (engine) {
  42221. engine.clear(HighlightLayer.neutralColor, true, true, true);
  42222. });
  42223. };
  42224. /**
  42225. * Checks for the readiness of the element composing the layer.
  42226. * @param subMesh the mesh to check for
  42227. * @param useInstances specify wether or not to use instances to render the mesh
  42228. * @param emissiveTexture the associated emissive texture used to generate the glow
  42229. * @return true if ready otherwise, false
  42230. */
  42231. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  42232. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  42233. return false;
  42234. }
  42235. var defines = [];
  42236. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42237. var mesh = subMesh.getMesh();
  42238. var material = subMesh.getMaterial();
  42239. var uv1 = false;
  42240. var uv2 = false;
  42241. // Alpha test
  42242. if (material && material.needAlphaTesting()) {
  42243. var alphaTexture = material.getAlphaTestTexture();
  42244. if (alphaTexture) {
  42245. defines.push("#define ALPHATEST");
  42246. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42247. alphaTexture.coordinatesIndex === 1) {
  42248. defines.push("#define DIFFUSEUV2");
  42249. uv2 = true;
  42250. }
  42251. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42252. defines.push("#define DIFFUSEUV1");
  42253. uv1 = true;
  42254. }
  42255. }
  42256. }
  42257. // Emissive
  42258. if (emissiveTexture) {
  42259. defines.push("#define EMISSIVE");
  42260. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42261. emissiveTexture.coordinatesIndex === 1) {
  42262. defines.push("#define EMISSIVEUV2");
  42263. uv2 = true;
  42264. }
  42265. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42266. defines.push("#define EMISSIVEUV1");
  42267. uv1 = true;
  42268. }
  42269. }
  42270. if (uv1) {
  42271. attribs.push(BABYLON.VertexBuffer.UVKind);
  42272. defines.push("#define UV1");
  42273. }
  42274. if (uv2) {
  42275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42276. defines.push("#define UV2");
  42277. }
  42278. // Bones
  42279. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42282. if (mesh.numBoneInfluencers > 4) {
  42283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42285. }
  42286. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42287. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42288. }
  42289. else {
  42290. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42291. }
  42292. // Instances
  42293. if (useInstances) {
  42294. defines.push("#define INSTANCES");
  42295. attribs.push("world0");
  42296. attribs.push("world1");
  42297. attribs.push("world2");
  42298. attribs.push("world3");
  42299. }
  42300. // Get correct effect
  42301. var join = defines.join("\n");
  42302. if (this._cachedDefines !== join) {
  42303. this._cachedDefines = join;
  42304. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  42305. }
  42306. return this._glowMapGenerationEffect.isReady();
  42307. };
  42308. /**
  42309. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  42310. */
  42311. HighlightLayer.prototype.render = function () {
  42312. var currentEffect = this._glowMapMergeEffect;
  42313. // Check
  42314. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  42315. return;
  42316. var engine = this._scene.getEngine();
  42317. this.onBeforeComposeObservable.notifyObservers(this);
  42318. // Render
  42319. engine.enableEffect(currentEffect);
  42320. engine.setState(false);
  42321. // Cache
  42322. var previousStencilBuffer = engine.getStencilBuffer();
  42323. var previousStencilFunction = engine.getStencilFunction();
  42324. var previousStencilMask = engine.getStencilMask();
  42325. var previousAlphaMode = engine.getAlphaMode();
  42326. // Texture
  42327. currentEffect.setTexture("textureSampler", this._blurTexture);
  42328. // VBOs
  42329. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  42330. // Draw order
  42331. engine.setAlphaMode(this._options.alphaBlendingMode);
  42332. engine.setStencilMask(0x00);
  42333. engine.setStencilBuffer(true);
  42334. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  42335. if (this.outerGlow) {
  42336. currentEffect.setFloat("offset", 0);
  42337. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  42338. engine.draw(true, 0, 6);
  42339. }
  42340. if (this.innerGlow) {
  42341. currentEffect.setFloat("offset", 1);
  42342. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  42343. engine.draw(true, 0, 6);
  42344. }
  42345. // Restore Cache
  42346. engine.setStencilFunction(previousStencilFunction);
  42347. engine.setStencilMask(previousStencilMask);
  42348. engine.setAlphaMode(previousAlphaMode);
  42349. engine.setStencilBuffer(previousStencilBuffer);
  42350. this.onAfterComposeObservable.notifyObservers(this);
  42351. // Handle size changes.
  42352. var size = this._mainTexture.getSize();
  42353. this.setMainTextureSize();
  42354. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  42355. // Recreate RTT and post processes on size change.
  42356. this.onSizeChangedObservable.notifyObservers(this);
  42357. this.disposeTextureAndPostProcesses();
  42358. this.createTextureAndPostProcesses();
  42359. }
  42360. };
  42361. /**
  42362. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  42363. * @param mesh The mesh to exclude from the highlight layer
  42364. */
  42365. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  42366. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42367. if (!meshExcluded) {
  42368. this._excludedMeshes[mesh.uniqueId] = {
  42369. mesh: mesh,
  42370. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  42371. mesh.getEngine().setStencilBuffer(false);
  42372. }),
  42373. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  42374. mesh.getEngine().setStencilBuffer(true);
  42375. }),
  42376. };
  42377. }
  42378. };
  42379. /**
  42380. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  42381. * @param mesh The mesh to highlight
  42382. */
  42383. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  42384. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42385. if (meshExcluded) {
  42386. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  42387. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  42388. }
  42389. this._excludedMeshes[mesh.uniqueId] = undefined;
  42390. };
  42391. /**
  42392. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  42393. * @param mesh The mesh to highlight
  42394. * @param color The color of the highlight
  42395. * @param glowEmissiveOnly Extract the glow from the emissive texture
  42396. */
  42397. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  42398. var _this = this;
  42399. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  42400. var meshHighlight = this._meshes[mesh.uniqueId];
  42401. if (meshHighlight) {
  42402. meshHighlight.color = color;
  42403. }
  42404. else {
  42405. this._meshes[mesh.uniqueId] = {
  42406. mesh: mesh,
  42407. color: color,
  42408. // Lambda required for capture due to Observable this context
  42409. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  42410. if (_this._excludedMeshes[mesh.uniqueId]) {
  42411. _this.defaultStencilReference(mesh);
  42412. }
  42413. else {
  42414. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  42415. }
  42416. }),
  42417. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  42418. glowEmissiveOnly: glowEmissiveOnly
  42419. };
  42420. }
  42421. this._shouldRender = true;
  42422. };
  42423. /**
  42424. * Remove a mesh from the highlight layer in order to make it stop glowing.
  42425. * @param mesh The mesh to highlight
  42426. */
  42427. HighlightLayer.prototype.removeMesh = function (mesh) {
  42428. var meshHighlight = this._meshes[mesh.uniqueId];
  42429. if (meshHighlight) {
  42430. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42431. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42432. }
  42433. this._meshes[mesh.uniqueId] = undefined;
  42434. this._shouldRender = false;
  42435. for (var meshHighlightToCheck in this._meshes) {
  42436. if (meshHighlightToCheck) {
  42437. this._shouldRender = true;
  42438. break;
  42439. }
  42440. }
  42441. };
  42442. /**
  42443. * Returns true if the layer contains information to display, otherwise false.
  42444. */
  42445. HighlightLayer.prototype.shouldRender = function () {
  42446. return this.isEnabled && this._shouldRender;
  42447. };
  42448. /**
  42449. * Sets the main texture desired size which is the closest power of two
  42450. * of the engine canvas size.
  42451. */
  42452. HighlightLayer.prototype.setMainTextureSize = function () {
  42453. if (this._options.mainTextureFixedSize) {
  42454. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  42455. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  42456. }
  42457. else {
  42458. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  42459. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  42460. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  42461. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  42462. }
  42463. };
  42464. /**
  42465. * Force the stencil to the normal expected value for none glowing parts
  42466. */
  42467. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  42468. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  42469. };
  42470. /**
  42471. * Dispose only the render target textures and post process.
  42472. */
  42473. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  42474. this._blurTexture.dispose();
  42475. this._mainTexture.dispose();
  42476. this._downSamplePostprocess.dispose();
  42477. this._horizontalBlurPostprocess.dispose();
  42478. this._verticalBlurPostprocess.dispose();
  42479. };
  42480. /**
  42481. * Dispose the highlight layer and free resources.
  42482. */
  42483. HighlightLayer.prototype.dispose = function () {
  42484. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  42485. if (vertexBuffer) {
  42486. vertexBuffer.dispose();
  42487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  42488. }
  42489. if (this._indexBuffer) {
  42490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42491. this._indexBuffer = null;
  42492. }
  42493. // Clean textures and post processes
  42494. this.disposeTextureAndPostProcesses();
  42495. // Clean mesh references
  42496. for (var id in this._meshes) {
  42497. var meshHighlight = this._meshes[id];
  42498. if (meshHighlight && meshHighlight.mesh) {
  42499. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42500. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42501. }
  42502. }
  42503. this._meshes = null;
  42504. for (var id in this._excludedMeshes) {
  42505. var meshHighlight = this._excludedMeshes[id];
  42506. if (meshHighlight) {
  42507. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  42508. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  42509. }
  42510. }
  42511. this._excludedMeshes = null;
  42512. // Remove from scene
  42513. var index = this._scene.highlightLayers.indexOf(this, 0);
  42514. if (index > -1) {
  42515. this._scene.highlightLayers.splice(index, 1);
  42516. }
  42517. // Callback
  42518. this.onDisposeObservable.notifyObservers(this);
  42519. this.onDisposeObservable.clear();
  42520. this.onBeforeRenderMainTextureObservable.clear();
  42521. this.onBeforeBlurObservable.clear();
  42522. this.onBeforeComposeObservable.clear();
  42523. this.onAfterComposeObservable.clear();
  42524. this.onSizeChangedObservable.clear();
  42525. };
  42526. return HighlightLayer;
  42527. }());
  42528. /**
  42529. * The neutral color used during the preparation of the glow effect.
  42530. * This is black by default as the blend operation is a blend operation.
  42531. */
  42532. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  42533. /**
  42534. * Stencil value used for glowing meshes.
  42535. */
  42536. HighlightLayer.glowingMeshStencilReference = 0x02;
  42537. /**
  42538. * Stencil value used for the other meshes in the scene.
  42539. */
  42540. HighlightLayer.normalMeshStencilReference = 0x01;
  42541. BABYLON.HighlightLayer = HighlightLayer;
  42542. })(BABYLON || (BABYLON = {}));
  42543. //# sourceMappingURL=babylon.highlightlayer.js.map
  42544. var BABYLON;
  42545. (function (BABYLON) {
  42546. var SIMDVector3 = (function () {
  42547. function SIMDVector3() {
  42548. }
  42549. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  42550. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  42551. };
  42552. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  42553. var m = transformation.m;
  42554. var m0 = SIMD.Float32x4.load(m, 0);
  42555. var m1 = SIMD.Float32x4.load(m, 4);
  42556. var m2 = SIMD.Float32x4.load(m, 8);
  42557. var m3 = SIMD.Float32x4.load(m, 12);
  42558. 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));
  42559. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  42560. result.x = SIMD.Float32x4.extractLane(r, 0);
  42561. result.y = SIMD.Float32x4.extractLane(r, 1);
  42562. result.z = SIMD.Float32x4.extractLane(r, 2);
  42563. };
  42564. return SIMDVector3;
  42565. }());
  42566. var SIMDMatrix = (function () {
  42567. function SIMDMatrix() {
  42568. }
  42569. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  42570. var tm = this.m;
  42571. var om = other.m;
  42572. var m0 = SIMD.Float32x4.load(om, 0);
  42573. var m1 = SIMD.Float32x4.load(om, 4);
  42574. var m2 = SIMD.Float32x4.load(om, 8);
  42575. var m3 = SIMD.Float32x4.load(om, 12);
  42576. for (var i = 0; i < 16; i += 4) {
  42577. 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)))));
  42578. }
  42579. return this;
  42580. };
  42581. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  42582. var src = this.m;
  42583. var dest = other.m;
  42584. // Load the 4 rows
  42585. var src0 = SIMD.Float32x4.load(src, 0);
  42586. var src1 = SIMD.Float32x4.load(src, 4);
  42587. var src2 = SIMD.Float32x4.load(src, 8);
  42588. var src3 = SIMD.Float32x4.load(src, 12);
  42589. // Transpose the source matrix. Sort of. Not a true transpose operation
  42590. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  42591. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  42592. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  42593. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  42594. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  42595. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  42596. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  42597. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  42598. // This is a true transposition, but it will lead to an incorrect result
  42599. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  42600. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  42601. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42602. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42603. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  42604. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  42605. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42606. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42607. // ----
  42608. tmp1 = SIMD.Float32x4.mul(row2, row3);
  42609. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42610. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  42611. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  42612. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42613. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  42614. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  42615. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  42616. // ----
  42617. tmp1 = SIMD.Float32x4.mul(row1, row2);
  42618. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42619. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  42620. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  42621. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42622. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  42623. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  42624. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  42625. // ----
  42626. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  42627. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42628. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  42629. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  42630. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  42631. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42632. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  42633. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  42634. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  42635. // ----
  42636. tmp1 = SIMD.Float32x4.mul(row0, row1);
  42637. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42638. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42639. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  42640. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42641. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42642. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  42643. // ----
  42644. tmp1 = SIMD.Float32x4.mul(row0, row3);
  42645. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42646. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  42647. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  42648. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42649. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  42650. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  42651. // ----
  42652. tmp1 = SIMD.Float32x4.mul(row0, row2);
  42653. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42654. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  42655. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  42656. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42657. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  42658. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  42659. // Compute determinant
  42660. var det = SIMD.Float32x4.mul(row0, minor0);
  42661. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  42662. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  42663. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  42664. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  42665. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  42666. // These shuffles aren't necessary if the faulty transposition is done
  42667. // up at the top of this function.
  42668. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  42669. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  42670. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  42671. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  42672. // Compute final values by multiplying with 1/det
  42673. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  42674. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  42675. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  42676. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  42677. return this;
  42678. };
  42679. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  42680. var out = result.m;
  42681. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  42682. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  42683. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  42684. // cc.kmVec3Subtract(f, pCenter, pEye);
  42685. var f = SIMD.Float32x4.sub(center, eye);
  42686. // cc.kmVec3Normalize(f, f);
  42687. var tmp = SIMD.Float32x4.mul(f, f);
  42688. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42689. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42690. // cc.kmVec3Assign(up, pUp);
  42691. // cc.kmVec3Normalize(up, up);
  42692. tmp = SIMD.Float32x4.mul(up, up);
  42693. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42694. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42695. // cc.kmVec3Cross(s, f, up);
  42696. 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)));
  42697. // cc.kmVec3Normalize(s, s);
  42698. tmp = SIMD.Float32x4.mul(s, s);
  42699. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42700. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42701. // cc.kmVec3Cross(u, s, f);
  42702. 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)));
  42703. // cc.kmVec3Normalize(s, s);
  42704. tmp = SIMD.Float32x4.mul(s, s);
  42705. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42706. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42707. var zero = SIMD.Float32x4.splat(0.0);
  42708. s = SIMD.Float32x4.neg(s);
  42709. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  42710. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  42711. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  42712. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  42713. 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);
  42714. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  42715. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  42716. 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)))));
  42717. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  42718. 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)))));
  42719. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  42720. 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)))));
  42721. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  42722. 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)))));
  42723. };
  42724. return SIMDMatrix;
  42725. }());
  42726. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  42727. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  42728. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  42729. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  42730. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  42731. var SIMDHelper = (function () {
  42732. function SIMDHelper() {
  42733. }
  42734. Object.defineProperty(SIMDHelper, "IsEnabled", {
  42735. get: function () {
  42736. return SIMDHelper._isEnabled;
  42737. },
  42738. enumerable: true,
  42739. configurable: true
  42740. });
  42741. SIMDHelper.DisableSIMD = function () {
  42742. // Replace functions
  42743. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  42744. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  42745. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  42746. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  42747. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  42748. SIMDHelper._isEnabled = false;
  42749. };
  42750. SIMDHelper.EnableSIMD = function () {
  42751. if (self.SIMD === undefined) {
  42752. return;
  42753. }
  42754. // check if polyfills needed
  42755. if (!self.Math.fround) {
  42756. self.Math.fround = (function (array) { return function (x) {
  42757. return array[0] = x, array[0];
  42758. }; })(new Float32Array(1));
  42759. }
  42760. if (!self.Math.imul) {
  42761. self.Math.imul = function (a, b) {
  42762. var ah = (a >>> 16) & 0xffff;
  42763. var al = a & 0xffff;
  42764. var bh = (b >>> 16) & 0xffff;
  42765. var bl = b & 0xffff;
  42766. // the shift by 0 fixes the sign on the high part
  42767. // the final |0 converts the unsigned value into a signed value
  42768. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  42769. };
  42770. }
  42771. // Replace functions
  42772. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  42773. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  42774. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  42775. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  42776. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  42777. SIMDHelper._isEnabled = true;
  42778. };
  42779. return SIMDHelper;
  42780. }());
  42781. SIMDHelper._isEnabled = false;
  42782. BABYLON.SIMDHelper = SIMDHelper;
  42783. })(BABYLON || (BABYLON = {}));
  42784. //# sourceMappingURL=babylon.math.SIMD.js.map
  42785. var BABYLON;
  42786. (function (BABYLON) {
  42787. /**
  42788. * This class describe a rectangle that were added to the map.
  42789. * You have access to its coordinates either in pixel or normalized (UV)
  42790. */
  42791. var PackedRect = (function () {
  42792. function PackedRect(root, parent, pos, size) {
  42793. this._pos = pos;
  42794. this._size = size;
  42795. this._root = root;
  42796. this._parent = parent;
  42797. this._contentSize = null;
  42798. this._bottomNode = null;
  42799. this._leftNode = null;
  42800. this._initialSize = null;
  42801. this._rightNode = null;
  42802. }
  42803. Object.defineProperty(PackedRect.prototype, "pos", {
  42804. /**
  42805. * @returns the position of this node into the map
  42806. */
  42807. get: function () {
  42808. return this._pos;
  42809. },
  42810. enumerable: true,
  42811. configurable: true
  42812. });
  42813. Object.defineProperty(PackedRect.prototype, "contentSize", {
  42814. /**
  42815. * @returns the size of the rectangle this node handles
  42816. */
  42817. get: function () {
  42818. return this._contentSize;
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(PackedRect.prototype, "UVs", {
  42824. /**
  42825. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  42826. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  42827. */
  42828. get: function () {
  42829. return this.getUVsForCustomSize(this._root._size);
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. /**
  42835. * 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.
  42836. * This method will return the UVs for this part by given the custom size of what you really use
  42837. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  42838. */
  42839. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  42840. var mainWidth = this._root._size.width;
  42841. var mainHeight = this._root._size.height;
  42842. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  42843. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  42844. var uvs = new Array();
  42845. uvs.push(topLeft);
  42846. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  42847. uvs.push(rightBottom);
  42848. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  42849. return uvs;
  42850. };
  42851. /**
  42852. * Free this rectangle from the map.
  42853. * Call this method when you no longer need the rectangle to be in the map.
  42854. */
  42855. PackedRect.prototype.freeContent = function () {
  42856. if (!this.contentSize) {
  42857. return;
  42858. }
  42859. this._contentSize = null;
  42860. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  42861. this.attemptDefrag();
  42862. };
  42863. Object.defineProperty(PackedRect.prototype, "isUsed", {
  42864. get: function () {
  42865. return this._contentSize != null || this._leftNode != null;
  42866. },
  42867. enumerable: true,
  42868. configurable: true
  42869. });
  42870. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  42871. var node = this.findNode(contentSize);
  42872. // Not enough space...
  42873. if (!node) {
  42874. return null;
  42875. }
  42876. node.splitNode(contentSize);
  42877. return node;
  42878. };
  42879. PackedRect.prototype.findNode = function (size) {
  42880. var resNode = null;
  42881. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  42882. if (this.isUsed) {
  42883. if (this._leftNode) {
  42884. resNode = this._leftNode.findNode(size);
  42885. }
  42886. if (!resNode && this._rightNode) {
  42887. resNode = this._rightNode.findNode(size);
  42888. }
  42889. if (!resNode && this._bottomNode) {
  42890. resNode = this._bottomNode.findNode(size);
  42891. }
  42892. }
  42893. else if (this._initialSize) {
  42894. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  42895. resNode = this;
  42896. }
  42897. else {
  42898. return null;
  42899. }
  42900. }
  42901. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  42902. resNode = this;
  42903. }
  42904. return resNode;
  42905. };
  42906. PackedRect.prototype.splitNode = function (contentSize) {
  42907. // 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)
  42908. if (!this._contentSize && this._initialSize) {
  42909. this._contentSize = contentSize.clone();
  42910. 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));
  42911. return this._leftNode.splitNode(contentSize);
  42912. }
  42913. else {
  42914. this._contentSize = contentSize.clone();
  42915. this._initialSize = contentSize.clone();
  42916. if (contentSize.width !== this._size.width) {
  42917. 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));
  42918. }
  42919. if (contentSize.height !== this._size.height) {
  42920. 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));
  42921. }
  42922. return this;
  42923. }
  42924. };
  42925. PackedRect.prototype.attemptDefrag = function () {
  42926. if (!this.isUsed && this.isRecursiveFree) {
  42927. this.clearNode();
  42928. if (this._parent) {
  42929. this._parent.attemptDefrag();
  42930. }
  42931. }
  42932. };
  42933. PackedRect.prototype.clearNode = function () {
  42934. this._initialSize = null;
  42935. this._rightNode = null;
  42936. this._bottomNode = null;
  42937. };
  42938. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  42939. get: function () {
  42940. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. PackedRect.prototype.evalFreeSize = function (size) {
  42946. var levelSize = 0;
  42947. if (!this.isUsed) {
  42948. if (this._initialSize) {
  42949. levelSize = this._initialSize.surface;
  42950. }
  42951. else {
  42952. levelSize = this._size.surface;
  42953. }
  42954. }
  42955. if (this._rightNode) {
  42956. levelSize += this._rightNode.evalFreeSize(0);
  42957. }
  42958. if (this._bottomNode) {
  42959. levelSize += this._bottomNode.evalFreeSize(0);
  42960. }
  42961. return levelSize + size;
  42962. };
  42963. return PackedRect;
  42964. }());
  42965. BABYLON.PackedRect = PackedRect;
  42966. /**
  42967. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  42968. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  42969. * 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.
  42970. */
  42971. var RectPackingMap = (function (_super) {
  42972. __extends(RectPackingMap, _super);
  42973. /**
  42974. * Create an instance of the object with a dimension using the given size
  42975. * @param size The dimension of the rectangle that will contain all the sub ones.
  42976. */
  42977. function RectPackingMap(size) {
  42978. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  42979. _this._root = _this;
  42980. return _this;
  42981. }
  42982. /**
  42983. * Add a rectangle, finding the best location to store it into the map
  42984. * @param size the dimension of the rectangle to store
  42985. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  42986. */
  42987. RectPackingMap.prototype.addRect = function (size) {
  42988. var node = this.findAndSplitNode(size);
  42989. return node;
  42990. };
  42991. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  42992. /**
  42993. * Return the current space free normalized between [0;1]
  42994. * @returns {}
  42995. */
  42996. get: function () {
  42997. var freeSize = 0;
  42998. freeSize = this.evalFreeSize(freeSize);
  42999. return freeSize / (this._size.width * this._size.height);
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. return RectPackingMap;
  43005. }(PackedRect));
  43006. BABYLON.RectPackingMap = RectPackingMap;
  43007. })(BABYLON || (BABYLON = {}));
  43008. //# sourceMappingURL=babylon.rectPackingMap.js.map
  43009. var BABYLON;
  43010. (function (BABYLON) {
  43011. var DynamicFloatArrayElementInfo = (function () {
  43012. function DynamicFloatArrayElementInfo() {
  43013. }
  43014. return DynamicFloatArrayElementInfo;
  43015. }());
  43016. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  43017. /**
  43018. * 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.
  43019. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  43020. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  43021. * 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.
  43022. * 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.
  43023. * 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".
  43024. */
  43025. var DynamicFloatArray = (function () {
  43026. /**
  43027. * Construct an instance of the dynamic float array
  43028. * @param stride size of one element in float (i.e. not bytes!)
  43029. * @param initialElementCount the number of available entries at construction
  43030. */
  43031. function DynamicFloatArray(stride, initialElementCount) {
  43032. this.compareValueOffset = null;
  43033. this.sortingAscending = true;
  43034. this._stride = stride;
  43035. this.buffer = new Float32Array(stride * initialElementCount);
  43036. this._lastUsed = 0;
  43037. this._firstFree = 0;
  43038. this._allEntries = new Array(initialElementCount);
  43039. this._freeEntries = new Array(initialElementCount);
  43040. for (var i = 0; i < initialElementCount; i++) {
  43041. var element = new DynamicFloatArrayElementInfo();
  43042. element.offset = i * stride;
  43043. this._allEntries[i] = element;
  43044. this._freeEntries[initialElementCount - i - 1] = element;
  43045. }
  43046. }
  43047. /**
  43048. * Allocate an element in the array.
  43049. * @return the element info instance that contains the offset into the main buffer of the element's location.
  43050. * Beware, this offset may change when you call pack()
  43051. */
  43052. DynamicFloatArray.prototype.allocElement = function () {
  43053. if (this._freeEntries.length === 0) {
  43054. this._growBuffer();
  43055. }
  43056. var el = this._freeEntries.pop();
  43057. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43058. if (el.offset === this._firstFree) {
  43059. if (this._freeEntries.length > 0) {
  43060. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43061. }
  43062. else {
  43063. this._firstFree += this._stride;
  43064. }
  43065. }
  43066. return el;
  43067. };
  43068. /**
  43069. * Free the element corresponding to the given element info
  43070. * @param elInfo the element that describe the allocated element
  43071. */
  43072. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43073. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43074. this._freeEntries.push(elInfo);
  43075. };
  43076. /**
  43077. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43078. * 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().
  43079. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43080. */
  43081. DynamicFloatArray.prototype.pack = function () {
  43082. // no free slot? no need to pack
  43083. if (this._freeEntries.length === 0) {
  43084. return this.buffer;
  43085. }
  43086. // If the buffer is already packed the last used will always be lower than the first free
  43087. // 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.
  43088. if (this._lastUsed < this._firstFree) {
  43089. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43090. return elementsBuffer_1;
  43091. }
  43092. var s = this._stride;
  43093. // 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
  43094. var lastFree = new DynamicFloatArrayElementInfo();
  43095. lastFree.offset = this.totalElementCount * s;
  43096. this._freeEntries.push(lastFree);
  43097. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43098. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43099. var firstFreeSlotOffset = sortedFree[0].offset;
  43100. var freeZoneSize = 1;
  43101. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43102. var prevOffset = sortedFree[0].offset;
  43103. for (var i = 1; i < sortedFree.length; i++) {
  43104. // 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
  43105. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43106. break;
  43107. }
  43108. var curFree = sortedFree[i];
  43109. var curOffset = curFree.offset;
  43110. // Compute the distance between this offset and the previous
  43111. var distance = curOffset - prevOffset;
  43112. // If the distance is the stride size, they are adjacent, it good, move to the next
  43113. if (distance === s) {
  43114. // Free zone is one element bigger
  43115. ++freeZoneSize;
  43116. // as we're about to iterate to the next, the cur becomes the previous...
  43117. prevOffset = curOffset;
  43118. continue;
  43119. }
  43120. // Distance is bigger, which means there's x element between the previous free and this one
  43121. var usedRange = (distance / s) - 1;
  43122. // Two cases the free zone is smaller than the data to move or bigger
  43123. // Copy what can fit in the free zone
  43124. var curMoveOffset = curOffset - s;
  43125. var copyCount = Math.min(freeZoneSize, usedRange);
  43126. for (var j = 0; j < copyCount; j++) {
  43127. var freeI = firstFreeSlotOffset / s;
  43128. var curI = curMoveOffset / s;
  43129. var moveEl = sortedAll[curI];
  43130. this._moveElement(moveEl, firstFreeSlotOffset);
  43131. var replacedEl = sortedAll[freeI];
  43132. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43133. replacedEl.offset = curMoveOffset;
  43134. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43135. sortedAll[freeI] = moveEl;
  43136. sortedAll[curI] = replacedEl;
  43137. curMoveOffset -= s;
  43138. firstFreeSlotOffset += s;
  43139. }
  43140. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43141. if (freeZoneSize <= usedRange) {
  43142. firstFreeSlotOffset = curMoveOffset + s;
  43143. freeZoneSize = 1 + copyCount;
  43144. }
  43145. else {
  43146. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43147. }
  43148. // as we're about to iterate to the next, the cur becomes the previous...
  43149. prevOffset = curOffset;
  43150. }
  43151. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43152. this._lastUsed = firstFreeSlotOffset - s;
  43153. this._firstFree = firstFreeSlotOffset;
  43154. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43155. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43156. this._allEntries = sortedAll;
  43157. return elementsBuffer;
  43158. };
  43159. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43160. for (var i = 0; i < this._stride; i++) {
  43161. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43162. }
  43163. element.offset = destOffset;
  43164. };
  43165. DynamicFloatArray.prototype._growBuffer = function () {
  43166. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43167. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43168. var newBuffer = new Float32Array(newElCount * this._stride);
  43169. newBuffer.set(this.buffer);
  43170. var curCount = this.totalElementCount;
  43171. var addedCount = newElCount - this.totalElementCount;
  43172. for (var i = 0; i < addedCount; i++) {
  43173. var element = new DynamicFloatArrayElementInfo();
  43174. element.offset = (curCount + i) * this.stride;
  43175. this._allEntries.push(element);
  43176. this._freeEntries[addedCount - i - 1] = element;
  43177. }
  43178. this._firstFree = curCount * this.stride;
  43179. this.buffer = newBuffer;
  43180. };
  43181. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43182. /**
  43183. * Get the total count of entries that can fit in the current buffer
  43184. * @returns the elements count
  43185. */
  43186. get: function () {
  43187. return this._allEntries.length;
  43188. },
  43189. enumerable: true,
  43190. configurable: true
  43191. });
  43192. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43193. /**
  43194. * Get the count of free entries that can still be allocated without resizing the buffer
  43195. * @returns the free elements count
  43196. */
  43197. get: function () {
  43198. return this._freeEntries.length;
  43199. },
  43200. enumerable: true,
  43201. configurable: true
  43202. });
  43203. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43204. /**
  43205. * Get the count of allocated elements
  43206. * @returns the allocated elements count
  43207. */
  43208. get: function () {
  43209. return this._allEntries.length - this._freeEntries.length;
  43210. },
  43211. enumerable: true,
  43212. configurable: true
  43213. });
  43214. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43215. /**
  43216. * Return the size of one element in float
  43217. * @returns the size in float
  43218. */
  43219. get: function () {
  43220. return this._stride;
  43221. },
  43222. enumerable: true,
  43223. configurable: true
  43224. });
  43225. DynamicFloatArray.prototype.sort = function () {
  43226. var _this = this;
  43227. if (!this.compareValueOffset) {
  43228. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43229. }
  43230. var count = this.usedElementCount;
  43231. // Do we have to (re)create the sort table?
  43232. if (!this._sortTable || this._sortTable.length < count) {
  43233. // 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...
  43234. var newCount = Math.min(this.totalElementCount, count * 2);
  43235. this._sortTable = new Array(newCount);
  43236. }
  43237. if (!this._sortedTable || this._sortedTable.length !== count) {
  43238. this._sortedTable = new Array(count);
  43239. }
  43240. // Because, you know...
  43241. this.pack();
  43242. //let stride = this.stride;
  43243. //for (let i = 0; i < count; i++) {
  43244. // let si = this._sortTable[i];
  43245. // if (!si) {
  43246. // si = new SortInfo();
  43247. // this._sortTable[i] = si;
  43248. // }
  43249. // si.entry = this._allEntries[i];
  43250. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43251. // si.swapedOffset = null;
  43252. // this._sortedTable[i] = si;
  43253. //}
  43254. var curOffset = 0;
  43255. var stride = this.stride;
  43256. for (var i = 0; i < count; i++, curOffset += stride) {
  43257. var si = this._sortTable[i];
  43258. if (!si) {
  43259. si = new SortInfo();
  43260. this._sortTable[i] = si;
  43261. }
  43262. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43263. si.offset = curOffset;
  43264. si.swapedOffset = null;
  43265. this._sortedTable[i] = si;
  43266. }
  43267. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43268. if (this.sortingAscending) {
  43269. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43270. }
  43271. else {
  43272. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43273. }
  43274. var swapElements = function (src, dst) {
  43275. for (var i = 0; i < stride; i++) {
  43276. var tps = _this.buffer[dst + i];
  43277. _this.buffer[dst + i] = _this.buffer[src + i];
  43278. _this.buffer[src + i] = tps;
  43279. }
  43280. };
  43281. // 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:
  43282. // 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),
  43283. // and I still want something with a good algorithm complexity.
  43284. // 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,
  43285. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43286. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43287. // 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
  43288. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43289. // 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
  43290. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43291. for (var i = 0; i < count; i++) {
  43292. // Get the element to move
  43293. var sourceSI = this._sortedTable[i];
  43294. var destSI = this._sortTable[i];
  43295. var sourceOff = sourceSI.offset;
  43296. // If the source changed location, find the new one
  43297. if (sourceSI.swapedOffset) {
  43298. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43299. var curSI = sourceSI;
  43300. while (curSI.swapedOffset) {
  43301. curSI = this._sortTable[curSI.swapedOffset / stride];
  43302. }
  43303. // Finally get the right location
  43304. sourceOff = curSI.offset;
  43305. }
  43306. // Tag the element being replaced with its new location
  43307. destSI.swapedOffset = sourceOff;
  43308. // Swap elements (only if needed)
  43309. if (sourceOff !== destSI.offset) {
  43310. swapElements(sourceOff, destSI.offset);
  43311. }
  43312. // Update the offset in the corresponding DFAE
  43313. //sourceSI.entry.offset = destSI.entry.offset;
  43314. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43315. }
  43316. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43317. return true;
  43318. };
  43319. return DynamicFloatArray;
  43320. }());
  43321. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43322. var SortInfo = (function () {
  43323. function SortInfo() {
  43324. this.compareData = this.offset = this.swapedOffset = null;
  43325. }
  43326. return SortInfo;
  43327. }());
  43328. })(BABYLON || (BABYLON = {}));
  43329. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43330. var BABYLON;
  43331. (function (BABYLON) {
  43332. var MapTexture = (function (_super) {
  43333. __extends(MapTexture, _super);
  43334. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  43335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43336. if (useMipMap === void 0) { useMipMap = false; }
  43337. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  43338. _this.name = name;
  43339. _this._size = size;
  43340. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43341. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43342. // Create the rectPackMap that will allocate portion of the texture
  43343. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  43344. // Create the texture that will store the content
  43345. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  43346. return _this;
  43347. }
  43348. /**
  43349. * Allocate a rectangle of a given size in the texture map
  43350. * @param size the size of the rectangle to allocation
  43351. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  43352. */
  43353. MapTexture.prototype.allocateRect = function (size) {
  43354. return this._rectPackingMap.addRect(size);
  43355. };
  43356. /**
  43357. * Free a given rectangle from the texture map
  43358. * @param rectInfo the instance corresponding to the rect to free.
  43359. */
  43360. MapTexture.prototype.freeRect = function (rectInfo) {
  43361. if (rectInfo) {
  43362. rectInfo.freeContent();
  43363. }
  43364. };
  43365. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  43366. /**
  43367. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  43368. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  43369. * @returns {}
  43370. */
  43371. get: function () {
  43372. return this._rectPackingMap.freeSpace;
  43373. },
  43374. enumerable: true,
  43375. configurable: true
  43376. });
  43377. /**
  43378. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  43379. * 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.
  43380. * Don't forget to call unbindTexture when you're done rendering
  43381. * @param rect the zone to render to
  43382. * @param clear true to clear the portion's color/depth data
  43383. */
  43384. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  43385. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  43386. };
  43387. /**
  43388. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  43389. * 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.
  43390. * Don't forget to call unbindTexture when you're done rendering
  43391. * @param pos the position into the texture
  43392. * @param size the portion to fit the clip space to
  43393. * @param clear true to clear the portion's color/depth data
  43394. */
  43395. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  43396. var engine = this.getScene().getEngine();
  43397. engine.bindFramebuffer(this._texture);
  43398. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  43399. if (clear) {
  43400. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  43401. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  43402. }
  43403. };
  43404. /**
  43405. * Unbind the texture map from the rendering engine.
  43406. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  43407. * @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.
  43408. */
  43409. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  43410. // Dump ?
  43411. if (dumpForDebug) {
  43412. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  43413. }
  43414. var engine = this.getScene().getEngine();
  43415. if (this._replacedViewport) {
  43416. engine.setViewport(this._replacedViewport);
  43417. this._replacedViewport = null;
  43418. }
  43419. engine.unBindFramebuffer(this._texture);
  43420. };
  43421. Object.defineProperty(MapTexture.prototype, "canRescale", {
  43422. get: function () {
  43423. return false;
  43424. },
  43425. enumerable: true,
  43426. configurable: true
  43427. });
  43428. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  43429. // Anyway, there's not much point to use this method for this kind of texture I guess
  43430. MapTexture.prototype.clone = function () {
  43431. return null;
  43432. };
  43433. return MapTexture;
  43434. }(BABYLON.Texture));
  43435. BABYLON.MapTexture = MapTexture;
  43436. })(BABYLON || (BABYLON = {}));
  43437. //# sourceMappingURL=babylon.mapTexture.js.map
  43438. var BABYLON;
  43439. (function (BABYLON) {
  43440. var ShaderMaterial = (function (_super) {
  43441. __extends(ShaderMaterial, _super);
  43442. function ShaderMaterial(name, scene, shaderPath, options) {
  43443. var _this = _super.call(this, name, scene) || this;
  43444. _this._textures = {};
  43445. _this._textureArrays = {};
  43446. _this._floats = {};
  43447. _this._floatsArrays = {};
  43448. _this._colors3 = {};
  43449. _this._colors4 = {};
  43450. _this._vectors2 = {};
  43451. _this._vectors3 = {};
  43452. _this._vectors4 = {};
  43453. _this._matrices = {};
  43454. _this._matrices3x3 = {};
  43455. _this._matrices2x2 = {};
  43456. _this._vectors3Arrays = {};
  43457. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43458. _this._shaderPath = shaderPath;
  43459. options.needAlphaBlending = options.needAlphaBlending || false;
  43460. options.needAlphaTesting = options.needAlphaTesting || false;
  43461. options.attributes = options.attributes || ["position", "normal", "uv"];
  43462. options.uniforms = options.uniforms || ["worldViewProjection"];
  43463. options.samplers = options.samplers || [];
  43464. options.defines = options.defines || [];
  43465. _this._options = options;
  43466. return _this;
  43467. }
  43468. ShaderMaterial.prototype.getClassName = function () {
  43469. return "ShaderMaterial";
  43470. };
  43471. ShaderMaterial.prototype.needAlphaBlending = function () {
  43472. return this._options.needAlphaBlending;
  43473. };
  43474. ShaderMaterial.prototype.needAlphaTesting = function () {
  43475. return this._options.needAlphaTesting;
  43476. };
  43477. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43478. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43479. this._options.uniforms.push(uniformName);
  43480. }
  43481. };
  43482. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43483. if (this._options.samplers.indexOf(name) === -1) {
  43484. this._options.samplers.push(name);
  43485. }
  43486. this._textures[name] = texture;
  43487. return this;
  43488. };
  43489. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43490. if (this._options.samplers.indexOf(name) === -1) {
  43491. this._options.samplers.push(name);
  43492. }
  43493. this._checkUniform(name);
  43494. this._textureArrays[name] = textures;
  43495. return this;
  43496. };
  43497. ShaderMaterial.prototype.setFloat = function (name, value) {
  43498. this._checkUniform(name);
  43499. this._floats[name] = value;
  43500. return this;
  43501. };
  43502. ShaderMaterial.prototype.setFloats = function (name, value) {
  43503. this._checkUniform(name);
  43504. this._floatsArrays[name] = value;
  43505. return this;
  43506. };
  43507. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43508. this._checkUniform(name);
  43509. this._colors3[name] = value;
  43510. return this;
  43511. };
  43512. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43513. this._checkUniform(name);
  43514. this._colors4[name] = value;
  43515. return this;
  43516. };
  43517. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43518. this._checkUniform(name);
  43519. this._vectors2[name] = value;
  43520. return this;
  43521. };
  43522. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43523. this._checkUniform(name);
  43524. this._vectors3[name] = value;
  43525. return this;
  43526. };
  43527. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43528. this._checkUniform(name);
  43529. this._vectors4[name] = value;
  43530. return this;
  43531. };
  43532. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43533. this._checkUniform(name);
  43534. this._matrices[name] = value;
  43535. return this;
  43536. };
  43537. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43538. this._checkUniform(name);
  43539. this._matrices3x3[name] = value;
  43540. return this;
  43541. };
  43542. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43543. this._checkUniform(name);
  43544. this._matrices2x2[name] = value;
  43545. return this;
  43546. };
  43547. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43548. this._checkUniform(name);
  43549. this._vectors3Arrays[name] = value;
  43550. return this;
  43551. };
  43552. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43553. if (!mesh) {
  43554. return true;
  43555. }
  43556. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43557. return false;
  43558. }
  43559. return false;
  43560. };
  43561. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43562. var scene = this.getScene();
  43563. var engine = scene.getEngine();
  43564. if (!this.checkReadyOnEveryCall) {
  43565. if (this._renderId === scene.getRenderId()) {
  43566. if (this._checkCache(scene, mesh, useInstances)) {
  43567. return true;
  43568. }
  43569. }
  43570. }
  43571. // Instances
  43572. var defines = [];
  43573. var fallbacks = new BABYLON.EffectFallbacks();
  43574. if (useInstances) {
  43575. defines.push("#define INSTANCES");
  43576. }
  43577. for (var index = 0; index < this._options.defines.length; index++) {
  43578. defines.push(this._options.defines[index]);
  43579. }
  43580. // Bones
  43581. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43582. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43583. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43584. fallbacks.addCPUSkinningFallback(0, mesh);
  43585. }
  43586. // Alpha test
  43587. if (engine.getAlphaTesting()) {
  43588. defines.push("#define ALPHATEST");
  43589. }
  43590. var previousEffect = this._effect;
  43591. var join = defines.join("\n");
  43592. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  43593. if (!this._effect.isReady()) {
  43594. return false;
  43595. }
  43596. if (previousEffect !== this._effect) {
  43597. scene.resetCachedMaterial();
  43598. }
  43599. this._renderId = scene.getRenderId();
  43600. return true;
  43601. };
  43602. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43603. var scene = this.getScene();
  43604. if (this._options.uniforms.indexOf("world") !== -1) {
  43605. this._effect.setMatrix("world", world);
  43606. }
  43607. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43608. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43609. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43610. }
  43611. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43612. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43613. }
  43614. };
  43615. ShaderMaterial.prototype.bind = function (world, mesh) {
  43616. // Std values
  43617. this.bindOnlyWorldMatrix(world);
  43618. if (this.getScene().getCachedMaterial() !== this) {
  43619. if (this._options.uniforms.indexOf("view") !== -1) {
  43620. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43621. }
  43622. if (this._options.uniforms.indexOf("projection") !== -1) {
  43623. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43624. }
  43625. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43626. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43627. }
  43628. // Bones
  43629. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43630. var name;
  43631. // Texture
  43632. for (name in this._textures) {
  43633. this._effect.setTexture(name, this._textures[name]);
  43634. }
  43635. // Texture arrays
  43636. for (name in this._textureArrays) {
  43637. this._effect.setTextureArray(name, this._textureArrays[name]);
  43638. }
  43639. // Float
  43640. for (name in this._floats) {
  43641. this._effect.setFloat(name, this._floats[name]);
  43642. }
  43643. // Float s
  43644. for (name in this._floatsArrays) {
  43645. this._effect.setArray(name, this._floatsArrays[name]);
  43646. }
  43647. // Color3
  43648. for (name in this._colors3) {
  43649. this._effect.setColor3(name, this._colors3[name]);
  43650. }
  43651. // Color4
  43652. for (name in this._colors4) {
  43653. var color = this._colors4[name];
  43654. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43655. }
  43656. // Vector2
  43657. for (name in this._vectors2) {
  43658. this._effect.setVector2(name, this._vectors2[name]);
  43659. }
  43660. // Vector3
  43661. for (name in this._vectors3) {
  43662. this._effect.setVector3(name, this._vectors3[name]);
  43663. }
  43664. // Vector4
  43665. for (name in this._vectors4) {
  43666. this._effect.setVector4(name, this._vectors4[name]);
  43667. }
  43668. // Matrix
  43669. for (name in this._matrices) {
  43670. this._effect.setMatrix(name, this._matrices[name]);
  43671. }
  43672. // Matrix 3x3
  43673. for (name in this._matrices3x3) {
  43674. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43675. }
  43676. // Matrix 2x2
  43677. for (name in this._matrices2x2) {
  43678. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43679. }
  43680. // Vector3Array
  43681. for (name in this._vectors3Arrays) {
  43682. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43683. }
  43684. }
  43685. _super.prototype.bind.call(this, world, mesh);
  43686. };
  43687. ShaderMaterial.prototype.clone = function (name) {
  43688. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43689. return newShaderMaterial;
  43690. };
  43691. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43692. if (forceDisposeTextures) {
  43693. var name;
  43694. for (name in this._textures) {
  43695. this._textures[name].dispose();
  43696. }
  43697. for (name in this._textureArrays) {
  43698. var array = this._textureArrays[name];
  43699. for (var index = 0; index < array.length; index++) {
  43700. array[index].dispose();
  43701. }
  43702. }
  43703. }
  43704. this._textures = {};
  43705. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43706. };
  43707. ShaderMaterial.prototype.serialize = function () {
  43708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43709. serializationObject.customType = "BABYLON.ShaderMaterial";
  43710. serializationObject.options = this._options;
  43711. serializationObject.shaderPath = this._shaderPath;
  43712. var name;
  43713. // Texture
  43714. serializationObject.textures = {};
  43715. for (name in this._textures) {
  43716. serializationObject.textures[name] = this._textures[name].serialize();
  43717. }
  43718. // Texture arrays
  43719. serializationObject.textureArrays = {};
  43720. for (name in this._textureArrays) {
  43721. serializationObject.textureArrays[name] = [];
  43722. var array = this._textureArrays[name];
  43723. for (var index = 0; index < array.length; index++) {
  43724. serializationObject.textureArrays[name].push(array[index].serialize());
  43725. }
  43726. }
  43727. // Float
  43728. serializationObject.floats = {};
  43729. for (name in this._floats) {
  43730. serializationObject.floats[name] = this._floats[name];
  43731. }
  43732. // Float s
  43733. serializationObject.floatArrays = {};
  43734. for (name in this._floatsArrays) {
  43735. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43736. }
  43737. // Color3
  43738. serializationObject.colors3 = {};
  43739. for (name in this._colors3) {
  43740. serializationObject.colors3[name] = this._colors3[name].asArray();
  43741. }
  43742. // Color4
  43743. serializationObject.colors4 = {};
  43744. for (name in this._colors4) {
  43745. serializationObject.colors4[name] = this._colors4[name].asArray();
  43746. }
  43747. // Vector2
  43748. serializationObject.vectors2 = {};
  43749. for (name in this._vectors2) {
  43750. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43751. }
  43752. // Vector3
  43753. serializationObject.vectors3 = {};
  43754. for (name in this._vectors3) {
  43755. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43756. }
  43757. // Vector4
  43758. serializationObject.vectors4 = {};
  43759. for (name in this._vectors4) {
  43760. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43761. }
  43762. // Matrix
  43763. serializationObject.matrices = {};
  43764. for (name in this._matrices) {
  43765. serializationObject.matrices[name] = this._matrices[name].asArray();
  43766. }
  43767. // Matrix 3x3
  43768. serializationObject.matrices3x3 = {};
  43769. for (name in this._matrices3x3) {
  43770. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43771. }
  43772. // Matrix 2x2
  43773. serializationObject.matrices2x2 = {};
  43774. for (name in this._matrices2x2) {
  43775. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43776. }
  43777. // Vector3Array
  43778. serializationObject.vectors3Arrays = {};
  43779. for (name in this._vectors3Arrays) {
  43780. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43781. }
  43782. return serializationObject;
  43783. };
  43784. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43785. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43786. var name;
  43787. // Texture
  43788. for (name in source.textures) {
  43789. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43790. }
  43791. // Texture arrays
  43792. for (name in source.textureArrays) {
  43793. var array = source.textureArrays[name];
  43794. var textureArray = new Array();
  43795. for (var index = 0; index < array.length; index++) {
  43796. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43797. }
  43798. material.setTextureArray(name, textureArray);
  43799. }
  43800. // Float
  43801. for (name in source.floats) {
  43802. material.setFloat(name, source.floats[name]);
  43803. }
  43804. // Float s
  43805. for (name in source.floatsArrays) {
  43806. material.setFloats(name, source.floatsArrays[name]);
  43807. }
  43808. // Color3
  43809. for (name in source.colors3) {
  43810. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43811. }
  43812. // Color4
  43813. for (name in source.colors4) {
  43814. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43815. }
  43816. // Vector2
  43817. for (name in source.vectors2) {
  43818. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43819. }
  43820. // Vector3
  43821. for (name in source.vectors3) {
  43822. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43823. }
  43824. // Vector4
  43825. for (name in source.vectors4) {
  43826. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43827. }
  43828. // Matrix
  43829. for (name in source.matrices) {
  43830. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43831. }
  43832. // Matrix 3x3
  43833. for (name in source.matrices3x3) {
  43834. material.setMatrix3x3(name, source.matrices3x3[name]);
  43835. }
  43836. // Matrix 2x2
  43837. for (name in source.matrices2x2) {
  43838. material.setMatrix2x2(name, source.matrices2x2[name]);
  43839. }
  43840. // Vector3Array
  43841. for (name in source.vectors3Arrays) {
  43842. material.setArray3(name, source.vectors3Arrays[name]);
  43843. }
  43844. return material;
  43845. };
  43846. return ShaderMaterial;
  43847. }(BABYLON.Material));
  43848. BABYLON.ShaderMaterial = ShaderMaterial;
  43849. })(BABYLON || (BABYLON = {}));
  43850. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43851. var BABYLON;
  43852. (function (BABYLON) {
  43853. var Internals;
  43854. (function (Internals) {
  43855. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  43856. // All values and structures referenced from:
  43857. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  43858. var DDS_MAGIC = 0x20534444;
  43859. 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;
  43860. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  43861. 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;
  43862. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  43863. function FourCCToInt32(value) {
  43864. return value.charCodeAt(0) +
  43865. (value.charCodeAt(1) << 8) +
  43866. (value.charCodeAt(2) << 16) +
  43867. (value.charCodeAt(3) << 24);
  43868. }
  43869. function Int32ToFourCC(value) {
  43870. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  43871. }
  43872. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  43873. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  43874. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  43875. var headerLengthInt = 31; // The header length in 32 bit ints
  43876. // Offsets into the header array
  43877. var off_magic = 0;
  43878. var off_size = 1;
  43879. var off_flags = 2;
  43880. var off_height = 3;
  43881. var off_width = 4;
  43882. var off_mipmapCount = 7;
  43883. var off_pfFlags = 20;
  43884. var off_pfFourCC = 21;
  43885. var off_RGBbpp = 22;
  43886. var off_RMask = 23;
  43887. var off_GMask = 24;
  43888. var off_BMask = 25;
  43889. var off_AMask = 26;
  43890. var off_caps1 = 27;
  43891. var off_caps2 = 28;
  43892. ;
  43893. var DDSTools = (function () {
  43894. function DDSTools() {
  43895. }
  43896. DDSTools.GetDDSInfo = function (arrayBuffer) {
  43897. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  43898. var mipmapCount = 1;
  43899. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  43900. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43901. }
  43902. return {
  43903. width: header[off_width],
  43904. height: header[off_height],
  43905. mipmapCount: mipmapCount,
  43906. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  43907. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  43908. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  43909. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  43910. };
  43911. };
  43912. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43913. var byteArray = new Uint8Array(dataLength);
  43914. var srcData = new Uint8Array(arrayBuffer);
  43915. var index = 0;
  43916. for (var y = height - 1; y >= 0; y--) {
  43917. for (var x = 0; x < width; x++) {
  43918. var srcPos = dataOffset + (x + y * width) * 4;
  43919. byteArray[index + 2] = srcData[srcPos];
  43920. byteArray[index + 1] = srcData[srcPos + 1];
  43921. byteArray[index] = srcData[srcPos + 2];
  43922. byteArray[index + 3] = srcData[srcPos + 3];
  43923. index += 4;
  43924. }
  43925. }
  43926. return byteArray;
  43927. };
  43928. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43929. var byteArray = new Uint8Array(dataLength);
  43930. var srcData = new Uint8Array(arrayBuffer);
  43931. var index = 0;
  43932. for (var y = height - 1; y >= 0; y--) {
  43933. for (var x = 0; x < width; x++) {
  43934. var srcPos = dataOffset + (x + y * width) * 3;
  43935. byteArray[index + 2] = srcData[srcPos];
  43936. byteArray[index + 1] = srcData[srcPos + 1];
  43937. byteArray[index] = srcData[srcPos + 2];
  43938. index += 3;
  43939. }
  43940. }
  43941. return byteArray;
  43942. };
  43943. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43944. var byteArray = new Uint8Array(dataLength);
  43945. var srcData = new Uint8Array(arrayBuffer);
  43946. var index = 0;
  43947. for (var y = height - 1; y >= 0; y--) {
  43948. for (var x = 0; x < width; x++) {
  43949. var srcPos = dataOffset + (x + y * width);
  43950. byteArray[index] = srcData[srcPos];
  43951. index++;
  43952. }
  43953. }
  43954. return byteArray;
  43955. };
  43956. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  43957. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  43958. if (header[off_magic] != DDS_MAGIC) {
  43959. BABYLON.Tools.Error("Invalid magic number in DDS header");
  43960. return;
  43961. }
  43962. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  43963. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  43964. return;
  43965. }
  43966. if (info.isFourCC) {
  43967. fourCC = header[off_pfFourCC];
  43968. switch (fourCC) {
  43969. case FOURCC_DXT1:
  43970. blockBytes = 8;
  43971. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43972. break;
  43973. case FOURCC_DXT3:
  43974. blockBytes = 16;
  43975. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43976. break;
  43977. case FOURCC_DXT5:
  43978. blockBytes = 16;
  43979. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43980. break;
  43981. default:
  43982. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  43983. return;
  43984. }
  43985. }
  43986. mipmapCount = 1;
  43987. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  43988. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43989. }
  43990. var bpp = header[off_RGBbpp];
  43991. for (var face = 0; face < faces; face++) {
  43992. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  43993. width = header[off_width];
  43994. height = header[off_height];
  43995. dataOffset = header[off_size] + 4;
  43996. for (i = 0; i < mipmapCount; ++i) {
  43997. if (info.isRGB) {
  43998. if (bpp === 24) {
  43999. dataLength = width * height * 3;
  44000. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44001. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  44002. }
  44003. else {
  44004. dataLength = width * height * 4;
  44005. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44006. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  44007. }
  44008. }
  44009. else if (info.isLuminance) {
  44010. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  44011. var unpaddedRowSize = width;
  44012. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  44013. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  44014. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44015. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  44016. }
  44017. else {
  44018. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  44019. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  44020. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  44021. }
  44022. dataOffset += dataLength;
  44023. width *= 0.5;
  44024. height *= 0.5;
  44025. width = Math.max(1.0, width);
  44026. height = Math.max(1.0, height);
  44027. }
  44028. }
  44029. };
  44030. return DDSTools;
  44031. }());
  44032. Internals.DDSTools = DDSTools;
  44033. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44034. })(BABYLON || (BABYLON = {}));
  44035. //# sourceMappingURL=babylon.tools.dds.js.map
  44036. var BABYLON;
  44037. (function (BABYLON) {
  44038. var Internals;
  44039. (function (Internals) {
  44040. /**
  44041. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  44042. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  44043. */
  44044. var KhronosTextureContainer = (function () {
  44045. /**
  44046. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  44047. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  44048. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  44049. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  44050. */
  44051. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  44052. this.arrayBuffer = arrayBuffer;
  44053. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  44054. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  44055. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  44056. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  44057. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  44058. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  44059. BABYLON.Tools.Error("texture missing KTX identifier");
  44060. return;
  44061. }
  44062. // load the reset of the header in native 32 bit int
  44063. var header = new Int32Array(this.arrayBuffer, 12, 13);
  44064. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  44065. var oppositeEndianess = header[0] === 0x01020304;
  44066. // read all the header elements in order they exist in the file, without modification (sans endainness)
  44067. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  44068. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  44069. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  44070. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  44071. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  44072. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  44073. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  44074. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  44075. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  44076. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  44077. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  44078. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  44079. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  44080. if (this.glType !== 0) {
  44081. BABYLON.Tools.Error("only compressed formats currently supported");
  44082. return;
  44083. }
  44084. else {
  44085. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  44086. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  44087. }
  44088. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  44089. BABYLON.Tools.Error("only 2D textures currently supported");
  44090. return;
  44091. }
  44092. if (this.numberOfArrayElements !== 0) {
  44093. BABYLON.Tools.Error("texture arrays not currently supported");
  44094. return;
  44095. }
  44096. if (this.numberOfFaces !== facesExpected) {
  44097. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  44098. return;
  44099. }
  44100. // we now have a completely validated file, so could use existence of loadType as success
  44101. // would need to make this more elaborate & adjust checks above to support more than one load type
  44102. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  44103. }
  44104. // not as fast hardware based, but will probably never need to use
  44105. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  44106. return ((val & 0xFF) << 24)
  44107. | ((val & 0xFF00) << 8)
  44108. | ((val >> 8) & 0xFF00)
  44109. | ((val >> 24) & 0xFF);
  44110. };
  44111. /**
  44112. * It is assumed that the texture has already been created & is currently bound
  44113. */
  44114. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  44115. switch (this.loadType) {
  44116. case KhronosTextureContainer.COMPRESSED_2D:
  44117. this._upload2DCompressedLevels(gl, loadMipmaps);
  44118. break;
  44119. case KhronosTextureContainer.TEX_2D:
  44120. case KhronosTextureContainer.COMPRESSED_3D:
  44121. case KhronosTextureContainer.TEX_3D:
  44122. }
  44123. };
  44124. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  44125. // initialize width & height for level 1
  44126. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  44127. var width = this.pixelWidth;
  44128. var height = this.pixelHeight;
  44129. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  44130. for (var level = 0; level < mipmapCount; level++) {
  44131. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  44132. for (var face = 0; face < this.numberOfFaces; face++) {
  44133. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44134. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  44135. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  44136. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  44137. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  44138. }
  44139. width = Math.max(1.0, width * 0.5);
  44140. height = Math.max(1.0, height * 0.5);
  44141. }
  44142. };
  44143. return KhronosTextureContainer;
  44144. }());
  44145. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  44146. // load types
  44147. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  44148. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  44149. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  44150. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  44151. Internals.KhronosTextureContainer = KhronosTextureContainer;
  44152. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44153. })(BABYLON || (BABYLON = {}));
  44154. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  44155. var BABYLON;
  44156. (function (BABYLON) {
  44157. var CannonJSPlugin = (function () {
  44158. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  44159. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  44160. if (iterations === void 0) { iterations = 10; }
  44161. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  44162. this.name = "CannonJSPlugin";
  44163. this._physicsMaterials = [];
  44164. this._fixedTimeStep = 1 / 60;
  44165. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44166. this._currentCollisionGroup = 2;
  44167. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  44168. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  44169. this._tmpPosition = BABYLON.Vector3.Zero();
  44170. this._tmpQuaternion = new BABYLON.Quaternion();
  44171. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  44172. this._tmpDeltaRotation = new BABYLON.Quaternion();
  44173. this._tmpUnityRotation = new BABYLON.Quaternion();
  44174. if (!this.isSupported()) {
  44175. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  44176. return;
  44177. }
  44178. this.world = new CANNON.World();
  44179. this.world.broadphase = new CANNON.NaiveBroadphase();
  44180. this.world.solver.iterations = iterations;
  44181. }
  44182. CannonJSPlugin.prototype.setGravity = function (gravity) {
  44183. this.world.gravity.copy(gravity);
  44184. };
  44185. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  44186. this._fixedTimeStep = timeStep;
  44187. };
  44188. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  44189. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  44190. };
  44191. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44192. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44193. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44194. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  44195. };
  44196. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44197. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44198. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44199. impostor.physicsBody.applyForce(impulse, worldPoint);
  44200. };
  44201. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44202. //parent-child relationship. Does this impostor has a parent impostor?
  44203. if (impostor.parent) {
  44204. if (impostor.physicsBody) {
  44205. this.removePhysicsBody(impostor);
  44206. //TODO is that needed?
  44207. impostor.forceUpdate();
  44208. }
  44209. return;
  44210. }
  44211. //should a new body be created for this impostor?
  44212. if (impostor.isBodyInitRequired()) {
  44213. var shape = this._createShape(impostor);
  44214. //unregister events, if body is being changed
  44215. var oldBody = impostor.physicsBody;
  44216. if (oldBody) {
  44217. this.removePhysicsBody(impostor);
  44218. }
  44219. //create the body and material
  44220. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  44221. var bodyCreationObject = {
  44222. mass: impostor.getParam("mass"),
  44223. material: material
  44224. };
  44225. // A simple extend, in case native options were used.
  44226. var nativeOptions = impostor.getParam("nativeOptions");
  44227. for (var key in nativeOptions) {
  44228. if (nativeOptions.hasOwnProperty(key)) {
  44229. bodyCreationObject[key] = nativeOptions[key];
  44230. }
  44231. }
  44232. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  44233. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  44234. this.world.addEventListener("preStep", impostor.beforeStep);
  44235. this.world.addEventListener("postStep", impostor.afterStep);
  44236. impostor.physicsBody.addShape(shape);
  44237. this.world.add(impostor.physicsBody);
  44238. //try to keep the body moving in the right direction by taking old properties.
  44239. //Should be tested!
  44240. if (oldBody) {
  44241. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  44242. impostor.physicsBody[param].copy(oldBody[param]);
  44243. });
  44244. }
  44245. this._processChildMeshes(impostor);
  44246. }
  44247. //now update the body's transformation
  44248. this._updatePhysicsBodyTransformation(impostor);
  44249. };
  44250. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  44251. var _this = this;
  44252. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  44253. if (meshChildren.length) {
  44254. var processMesh = function (localPosition, mesh) {
  44255. var childImpostor = mesh.getPhysicsImpostor();
  44256. if (childImpostor) {
  44257. var parent = childImpostor.parent;
  44258. if (parent !== mainImpostor) {
  44259. var localPosition = mesh.position;
  44260. if (childImpostor.physicsBody) {
  44261. _this.removePhysicsBody(childImpostor);
  44262. childImpostor.physicsBody = null;
  44263. }
  44264. childImpostor.parent = mainImpostor;
  44265. childImpostor.resetUpdateFlags();
  44266. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  44267. //Add the mass of the children.
  44268. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  44269. }
  44270. }
  44271. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  44272. };
  44273. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  44274. }
  44275. };
  44276. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44277. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  44278. this.world.removeEventListener("preStep", impostor.beforeStep);
  44279. this.world.removeEventListener("postStep", impostor.afterStep);
  44280. this.world.remove(impostor.physicsBody);
  44281. };
  44282. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44283. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44284. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44285. if (!mainBody || !connectedBody) {
  44286. return;
  44287. }
  44288. var constraint;
  44289. var jointData = impostorJoint.joint.jointData;
  44290. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44291. var constraintData = {
  44292. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  44293. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  44294. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  44295. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  44296. maxForce: jointData.nativeParams.maxForce,
  44297. collideConnected: !!jointData.collision
  44298. };
  44299. switch (impostorJoint.joint.type) {
  44300. case BABYLON.PhysicsJoint.HingeJoint:
  44301. case BABYLON.PhysicsJoint.Hinge2Joint:
  44302. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  44303. break;
  44304. case BABYLON.PhysicsJoint.DistanceJoint:
  44305. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  44306. break;
  44307. case BABYLON.PhysicsJoint.SpringJoint:
  44308. var springData = jointData;
  44309. constraint = new CANNON.Spring(mainBody, connectedBody, {
  44310. restLength: springData.length,
  44311. stiffness: springData.stiffness,
  44312. damping: springData.damping,
  44313. localAnchorA: constraintData.pivotA,
  44314. localAnchorB: constraintData.pivotB
  44315. });
  44316. break;
  44317. case BABYLON.PhysicsJoint.LockJoint:
  44318. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  44319. break;
  44320. case BABYLON.PhysicsJoint.PointToPointJoint:
  44321. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44322. default:
  44323. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  44324. break;
  44325. }
  44326. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  44327. constraint.collideConnected = !!jointData.collision;
  44328. impostorJoint.joint.physicsJoint = constraint;
  44329. //don't add spring as constraint, as it is not one.
  44330. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  44331. this.world.addConstraint(constraint);
  44332. }
  44333. else {
  44334. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  44335. constraint.applyForce();
  44336. });
  44337. }
  44338. };
  44339. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44340. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  44341. };
  44342. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  44343. var index;
  44344. var mat;
  44345. for (index = 0; index < this._physicsMaterials.length; index++) {
  44346. mat = this._physicsMaterials[index];
  44347. if (mat.friction === friction && mat.restitution === restitution) {
  44348. return mat;
  44349. }
  44350. }
  44351. var currentMat = new CANNON.Material(name);
  44352. currentMat.friction = friction;
  44353. currentMat.restitution = restitution;
  44354. this._physicsMaterials.push(currentMat);
  44355. return currentMat;
  44356. };
  44357. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  44358. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  44359. };
  44360. CannonJSPlugin.prototype._createShape = function (impostor) {
  44361. var object = impostor.object;
  44362. var returnValue;
  44363. var extendSize = impostor.getObjectExtendSize();
  44364. switch (impostor.type) {
  44365. case BABYLON.PhysicsEngine.SphereImpostor:
  44366. var radiusX = extendSize.x;
  44367. var radiusY = extendSize.y;
  44368. var radiusZ = extendSize.z;
  44369. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  44370. break;
  44371. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  44372. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44373. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  44374. break;
  44375. case BABYLON.PhysicsImpostor.BoxImpostor:
  44376. var box = extendSize.scale(0.5);
  44377. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  44378. break;
  44379. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44380. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  44381. returnValue = new CANNON.Plane();
  44382. break;
  44383. case BABYLON.PhysicsImpostor.MeshImpostor:
  44384. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  44385. var rawFaces = object.getIndices ? object.getIndices() : [];
  44386. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  44387. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  44388. break;
  44389. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  44390. returnValue = this._createHeightmap(object);
  44391. break;
  44392. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44393. returnValue = new CANNON.Particle();
  44394. break;
  44395. }
  44396. return returnValue;
  44397. };
  44398. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  44399. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44400. var matrix = [];
  44401. //For now pointDepth will not be used and will be automatically calculated.
  44402. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  44403. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  44404. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  44405. var elementSize = dim * 2 / arraySize;
  44406. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  44407. for (var i = 0; i < pos.length; i = i + 3) {
  44408. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  44409. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  44410. var y = pos[i + 1] + minY;
  44411. if (!matrix[x]) {
  44412. matrix[x] = [];
  44413. }
  44414. if (!matrix[x][z]) {
  44415. matrix[x][z] = y;
  44416. }
  44417. matrix[x][z] = Math.max(y, matrix[x][z]);
  44418. }
  44419. for (var x = 0; x <= arraySize; ++x) {
  44420. if (!matrix[x]) {
  44421. var loc = 1;
  44422. while (!matrix[(x + loc) % arraySize]) {
  44423. loc++;
  44424. }
  44425. matrix[x] = matrix[(x + loc) % arraySize].slice();
  44426. }
  44427. for (var z = 0; z <= arraySize; ++z) {
  44428. if (!matrix[x][z]) {
  44429. var loc = 1;
  44430. var newValue;
  44431. while (newValue === undefined) {
  44432. newValue = matrix[x][(z + loc++) % arraySize];
  44433. }
  44434. matrix[x][z] = newValue;
  44435. }
  44436. }
  44437. }
  44438. var shape = new CANNON.Heightfield(matrix, {
  44439. elementSize: elementSize
  44440. });
  44441. //For future reference, needed for body transformation
  44442. shape.minY = minY;
  44443. return shape;
  44444. };
  44445. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  44446. var object = impostor.object;
  44447. //make sure it is updated...
  44448. object.computeWorldMatrix && object.computeWorldMatrix(true);
  44449. // The delta between the mesh position and the mesh bounding box center
  44450. var center = impostor.getObjectCenter();
  44451. var extendSize = impostor.getObjectExtendSize();
  44452. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  44453. this._tmpPosition.copyFrom(center);
  44454. var quaternion = object.rotationQuaternion;
  44455. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  44456. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  44457. //-90 DEG in X, precalculated
  44458. quaternion = quaternion.multiply(this._minus90X);
  44459. //Invert! (Precalculated, 90 deg in X)
  44460. //No need to clone. this will never change.
  44461. impostor.setDeltaRotation(this._plus90X);
  44462. }
  44463. //If it is a heightfield, if should be centered.
  44464. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  44465. var mesh = object;
  44466. //calculate the correct body position:
  44467. var rotationQuaternion = mesh.rotationQuaternion;
  44468. mesh.rotationQuaternion = this._tmpUnityRotation;
  44469. mesh.computeWorldMatrix(true);
  44470. //get original center with no rotation
  44471. var c = center.clone();
  44472. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  44473. //rotation is back
  44474. mesh.rotationQuaternion = rotationQuaternion;
  44475. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  44476. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  44477. mesh.setPivotMatrix(p);
  44478. mesh.computeWorldMatrix(true);
  44479. //calculate the translation
  44480. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  44481. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  44482. //add it inverted to the delta
  44483. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  44484. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  44485. mesh.setPivotMatrix(oldPivot);
  44486. mesh.computeWorldMatrix(true);
  44487. }
  44488. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  44489. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  44490. this._tmpPosition.copyFrom(object.position);
  44491. }
  44492. impostor.setDeltaPosition(this._tmpDeltaPosition);
  44493. //Now update the impostor object
  44494. impostor.physicsBody.position.copy(this._tmpPosition);
  44495. impostor.physicsBody.quaternion.copy(quaternion);
  44496. };
  44497. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44498. impostor.object.position.copyFrom(impostor.physicsBody.position);
  44499. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  44500. };
  44501. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44502. impostor.physicsBody.position.copy(newPosition);
  44503. impostor.physicsBody.quaternion.copy(newRotation);
  44504. };
  44505. CannonJSPlugin.prototype.isSupported = function () {
  44506. return window.CANNON !== undefined;
  44507. };
  44508. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44509. impostor.physicsBody.velocity.copy(velocity);
  44510. };
  44511. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44512. impostor.physicsBody.angularVelocity.copy(velocity);
  44513. };
  44514. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44515. var v = impostor.physicsBody.velocity;
  44516. if (!v)
  44517. return null;
  44518. return new BABYLON.Vector3(v.x, v.y, v.z);
  44519. };
  44520. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44521. var v = impostor.physicsBody.angularVelocity;
  44522. if (!v)
  44523. return null;
  44524. return new BABYLON.Vector3(v.x, v.y, v.z);
  44525. };
  44526. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44527. impostor.physicsBody.mass = mass;
  44528. impostor.physicsBody.updateMassProperties();
  44529. };
  44530. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  44531. impostor.physicsBody.sleep();
  44532. };
  44533. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  44534. impostor.physicsBody.wakeUp();
  44535. };
  44536. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44537. joint.physicsJoint.distance = maxDistance;
  44538. };
  44539. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  44540. if (!motorIndex) {
  44541. joint.physicsJoint.enableMotor();
  44542. }
  44543. };
  44544. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  44545. if (!motorIndex) {
  44546. joint.physicsJoint.disableMotor();
  44547. }
  44548. };
  44549. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44550. if (!motorIndex) {
  44551. joint.physicsJoint.enableMotor();
  44552. joint.physicsJoint.setMotorSpeed(speed);
  44553. if (maxForce) {
  44554. this.setLimit(joint, maxForce);
  44555. }
  44556. }
  44557. };
  44558. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  44559. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  44560. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  44561. };
  44562. CannonJSPlugin.prototype.dispose = function () {
  44563. //nothing to do, actually.
  44564. };
  44565. return CannonJSPlugin;
  44566. }());
  44567. BABYLON.CannonJSPlugin = CannonJSPlugin;
  44568. })(BABYLON || (BABYLON = {}));
  44569. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  44570. var BABYLON;
  44571. (function (BABYLON) {
  44572. var OimoJSPlugin = (function () {
  44573. function OimoJSPlugin(iterations) {
  44574. this.name = "OimoJSPlugin";
  44575. this._tmpImpostorsArray = [];
  44576. this._tmpPositionVector = BABYLON.Vector3.Zero();
  44577. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  44578. this.world.worldscale(1);
  44579. this.world.clear();
  44580. //making sure no stats are calculated
  44581. this.world.isNoStat = true;
  44582. }
  44583. OimoJSPlugin.prototype.setGravity = function (gravity) {
  44584. this.world.gravity.copy(gravity);
  44585. };
  44586. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  44587. this.world.timeStep = timeStep;
  44588. };
  44589. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  44590. var _this = this;
  44591. impostors.forEach(function (impostor) {
  44592. impostor.beforeStep();
  44593. });
  44594. this.world.step();
  44595. impostors.forEach(function (impostor) {
  44596. impostor.afterStep();
  44597. //update the ordered impostors array
  44598. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44599. });
  44600. //check for collisions
  44601. var contact = this.world.contacts;
  44602. while (contact !== null) {
  44603. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  44604. contact = contact.next;
  44605. continue;
  44606. }
  44607. //is this body colliding with any other? get the impostor
  44608. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  44609. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  44610. if (!mainImpostor || !collidingImpostor) {
  44611. contact = contact.next;
  44612. continue;
  44613. }
  44614. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  44615. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  44616. contact = contact.next;
  44617. }
  44618. };
  44619. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44620. var mass = impostor.physicsBody.massInfo.mass;
  44621. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  44622. };
  44623. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44624. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  44625. this.applyImpulse(impostor, force, contactPoint);
  44626. };
  44627. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44628. var _this = this;
  44629. //parent-child relationship. Does this impostor has a parent impostor?
  44630. if (impostor.parent) {
  44631. if (impostor.physicsBody) {
  44632. this.removePhysicsBody(impostor);
  44633. //TODO is that needed?
  44634. impostor.forceUpdate();
  44635. }
  44636. return;
  44637. }
  44638. if (impostor.isBodyInitRequired()) {
  44639. var bodyConfig = {
  44640. name: impostor.uniqueId,
  44641. //Oimo must have mass, also for static objects.
  44642. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  44643. size: [],
  44644. type: [],
  44645. pos: [],
  44646. rot: [],
  44647. move: impostor.getParam("mass") !== 0,
  44648. //Supporting older versions of Oimo
  44649. world: this.world
  44650. };
  44651. var impostors = [impostor];
  44652. var addToArray = function (parent) {
  44653. if (!parent.getChildMeshes)
  44654. return;
  44655. parent.getChildMeshes().forEach(function (m) {
  44656. if (m.physicsImpostor) {
  44657. impostors.push(m.physicsImpostor);
  44658. m.physicsImpostor._init();
  44659. }
  44660. });
  44661. };
  44662. addToArray(impostor.object);
  44663. var checkWithEpsilon_1 = function (value) {
  44664. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  44665. };
  44666. impostors.forEach(function (i) {
  44667. //get the correct bounding box
  44668. var oldQuaternion = i.object.rotationQuaternion;
  44669. var rot = new OIMO.Euler().setFromQuaternion({
  44670. x: impostor.object.rotationQuaternion.x,
  44671. y: impostor.object.rotationQuaternion.y,
  44672. z: impostor.object.rotationQuaternion.z,
  44673. s: impostor.object.rotationQuaternion.w
  44674. });
  44675. var extendSize = i.getObjectExtendSize();
  44676. if (i === impostor) {
  44677. var center = impostor.getObjectCenter();
  44678. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  44679. //Can also use Array.prototype.push.apply
  44680. bodyConfig.pos.push(center.x);
  44681. bodyConfig.pos.push(center.y);
  44682. bodyConfig.pos.push(center.z);
  44683. //tmp solution
  44684. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  44685. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  44686. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  44687. }
  44688. else {
  44689. bodyConfig.pos.push(i.object.position.x);
  44690. bodyConfig.pos.push(i.object.position.y);
  44691. bodyConfig.pos.push(i.object.position.z);
  44692. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  44693. bodyConfig.rot.push(0);
  44694. bodyConfig.rot.push(0);
  44695. bodyConfig.rot.push(0);
  44696. }
  44697. // register mesh
  44698. switch (i.type) {
  44699. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44700. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  44701. case BABYLON.PhysicsImpostor.SphereImpostor:
  44702. var radiusX = extendSize.x;
  44703. var radiusY = extendSize.y;
  44704. var radiusZ = extendSize.z;
  44705. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  44706. bodyConfig.type.push('sphere');
  44707. //due to the way oimo works with compounds, add 3 times
  44708. bodyConfig.size.push(size);
  44709. bodyConfig.size.push(size);
  44710. bodyConfig.size.push(size);
  44711. break;
  44712. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44713. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  44714. var sizeY = checkWithEpsilon_1(extendSize.y);
  44715. bodyConfig.type.push('cylinder');
  44716. bodyConfig.size.push(sizeX);
  44717. bodyConfig.size.push(sizeY);
  44718. //due to the way oimo works with compounds, add one more value.
  44719. bodyConfig.size.push(sizeY);
  44720. break;
  44721. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44722. case BABYLON.PhysicsImpostor.BoxImpostor:
  44723. default:
  44724. var sizeX = checkWithEpsilon_1(extendSize.x);
  44725. var sizeY = checkWithEpsilon_1(extendSize.y);
  44726. var sizeZ = checkWithEpsilon_1(extendSize.z);
  44727. bodyConfig.type.push('box');
  44728. bodyConfig.size.push(sizeX);
  44729. bodyConfig.size.push(sizeY);
  44730. bodyConfig.size.push(sizeZ);
  44731. break;
  44732. }
  44733. //actually not needed, but hey...
  44734. i.object.rotationQuaternion = oldQuaternion;
  44735. });
  44736. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  44737. }
  44738. else {
  44739. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  44740. }
  44741. impostor.setDeltaPosition(this._tmpPositionVector);
  44742. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  44743. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  44744. };
  44745. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44746. //impostor.physicsBody.dispose();
  44747. //Same as : (older oimo versions)
  44748. this.world.removeRigidBody(impostor.physicsBody);
  44749. };
  44750. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44751. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44752. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44753. if (!mainBody || !connectedBody) {
  44754. return;
  44755. }
  44756. var jointData = impostorJoint.joint.jointData;
  44757. var options = jointData.nativeParams || {};
  44758. var type;
  44759. var nativeJointData = {
  44760. body1: mainBody,
  44761. body2: connectedBody,
  44762. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  44763. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  44764. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  44765. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  44766. min: options.min,
  44767. max: options.max,
  44768. collision: options.collision || jointData.collision,
  44769. spring: options.spring,
  44770. //supporting older version of Oimo
  44771. world: this.world
  44772. };
  44773. switch (impostorJoint.joint.type) {
  44774. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44775. type = "jointBall";
  44776. break;
  44777. case BABYLON.PhysicsJoint.SpringJoint:
  44778. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  44779. var springData = jointData;
  44780. nativeJointData.min = springData.length || nativeJointData.min;
  44781. //Max should also be set, just make sure it is at least min
  44782. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  44783. case BABYLON.PhysicsJoint.DistanceJoint:
  44784. type = "jointDistance";
  44785. nativeJointData.max = jointData.maxDistance;
  44786. break;
  44787. case BABYLON.PhysicsJoint.PrismaticJoint:
  44788. type = "jointPrisme";
  44789. break;
  44790. case BABYLON.PhysicsJoint.SliderJoint:
  44791. type = "jointSlide";
  44792. break;
  44793. case BABYLON.PhysicsJoint.WheelJoint:
  44794. type = "jointWheel";
  44795. break;
  44796. case BABYLON.PhysicsJoint.HingeJoint:
  44797. default:
  44798. type = "jointHinge";
  44799. break;
  44800. }
  44801. nativeJointData.type = type;
  44802. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  44803. };
  44804. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44805. //Bug in Oimo prevents us from disposing a joint in the playground
  44806. //joint.joint.physicsJoint.dispose();
  44807. //So we will bruteforce it!
  44808. try {
  44809. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  44810. }
  44811. catch (e) {
  44812. BABYLON.Tools.Warn(e);
  44813. }
  44814. };
  44815. OimoJSPlugin.prototype.isSupported = function () {
  44816. return OIMO !== undefined;
  44817. };
  44818. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44819. if (!impostor.physicsBody.sleeping) {
  44820. //TODO check that
  44821. if (impostor.physicsBody.shapes.next) {
  44822. var parentShape = this._getLastShape(impostor.physicsBody);
  44823. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  44824. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  44825. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  44826. }
  44827. else {
  44828. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  44829. }
  44830. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  44831. impostor.object.rotationQuaternion.normalize();
  44832. }
  44833. };
  44834. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44835. var body = impostor.physicsBody;
  44836. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  44837. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  44838. body.syncShapes();
  44839. body.awake();
  44840. };
  44841. OimoJSPlugin.prototype._getLastShape = function (body) {
  44842. var lastShape = body.shapes;
  44843. while (lastShape.next) {
  44844. lastShape = lastShape.next;
  44845. }
  44846. return lastShape;
  44847. };
  44848. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44849. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  44850. };
  44851. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44852. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  44853. };
  44854. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44855. var v = impostor.physicsBody.linearVelocity;
  44856. if (!v)
  44857. return null;
  44858. return new BABYLON.Vector3(v.x, v.y, v.z);
  44859. };
  44860. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44861. var v = impostor.physicsBody.angularVelocity;
  44862. if (!v)
  44863. return null;
  44864. return new BABYLON.Vector3(v.x, v.y, v.z);
  44865. };
  44866. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44867. var staticBody = mass === 0;
  44868. //this will actually set the body's density and not its mass.
  44869. //But this is how oimo treats the mass variable.
  44870. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  44871. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  44872. };
  44873. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  44874. impostor.physicsBody.sleep();
  44875. };
  44876. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  44877. impostor.physicsBody.awake();
  44878. };
  44879. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44880. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  44881. if (minDistance !== void 0) {
  44882. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  44883. }
  44884. };
  44885. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44886. //TODO separate rotational and transational motors.
  44887. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44888. if (motor) {
  44889. motor.setMotor(speed, maxForce);
  44890. }
  44891. };
  44892. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  44893. //TODO separate rotational and transational motors.
  44894. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44895. if (motor) {
  44896. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  44897. }
  44898. };
  44899. OimoJSPlugin.prototype.dispose = function () {
  44900. this.world.clear();
  44901. };
  44902. return OimoJSPlugin;
  44903. }());
  44904. BABYLON.OimoJSPlugin = OimoJSPlugin;
  44905. })(BABYLON || (BABYLON = {}));
  44906. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  44907. var BABYLON;
  44908. (function (BABYLON) {
  44909. var DisplayPassPostProcess = (function (_super) {
  44910. __extends(DisplayPassPostProcess, _super);
  44911. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44912. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  44913. }
  44914. return DisplayPassPostProcess;
  44915. }(BABYLON.PostProcess));
  44916. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  44917. })(BABYLON || (BABYLON = {}));
  44918. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  44919. var BABYLON;
  44920. (function (BABYLON) {
  44921. var SimplificationSettings = (function () {
  44922. function SimplificationSettings(quality, distance, optimizeMesh) {
  44923. this.quality = quality;
  44924. this.distance = distance;
  44925. this.optimizeMesh = optimizeMesh;
  44926. }
  44927. return SimplificationSettings;
  44928. }());
  44929. BABYLON.SimplificationSettings = SimplificationSettings;
  44930. var SimplificationQueue = (function () {
  44931. function SimplificationQueue() {
  44932. this.running = false;
  44933. this._simplificationArray = [];
  44934. }
  44935. SimplificationQueue.prototype.addTask = function (task) {
  44936. this._simplificationArray.push(task);
  44937. };
  44938. SimplificationQueue.prototype.executeNext = function () {
  44939. var task = this._simplificationArray.pop();
  44940. if (task) {
  44941. this.running = true;
  44942. this.runSimplification(task);
  44943. }
  44944. else {
  44945. this.running = false;
  44946. }
  44947. };
  44948. SimplificationQueue.prototype.runSimplification = function (task) {
  44949. var _this = this;
  44950. if (task.parallelProcessing) {
  44951. //parallel simplifier
  44952. task.settings.forEach(function (setting) {
  44953. var simplifier = _this.getSimplifier(task);
  44954. simplifier.simplify(setting, function (newMesh) {
  44955. task.mesh.addLODLevel(setting.distance, newMesh);
  44956. newMesh.isVisible = true;
  44957. //check if it is the last
  44958. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  44959. //all done, run the success callback.
  44960. task.successCallback();
  44961. }
  44962. _this.executeNext();
  44963. });
  44964. });
  44965. }
  44966. else {
  44967. //single simplifier.
  44968. var simplifier = this.getSimplifier(task);
  44969. var runDecimation = function (setting, callback) {
  44970. simplifier.simplify(setting, function (newMesh) {
  44971. task.mesh.addLODLevel(setting.distance, newMesh);
  44972. newMesh.isVisible = true;
  44973. //run the next quality level
  44974. callback();
  44975. });
  44976. };
  44977. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  44978. runDecimation(task.settings[loop.index], function () {
  44979. loop.executeNext();
  44980. });
  44981. }, function () {
  44982. //execution ended, run the success callback.
  44983. if (task.successCallback) {
  44984. task.successCallback();
  44985. }
  44986. _this.executeNext();
  44987. });
  44988. }
  44989. };
  44990. SimplificationQueue.prototype.getSimplifier = function (task) {
  44991. switch (task.simplificationType) {
  44992. case SimplificationType.QUADRATIC:
  44993. default:
  44994. return new QuadraticErrorSimplification(task.mesh);
  44995. }
  44996. };
  44997. return SimplificationQueue;
  44998. }());
  44999. BABYLON.SimplificationQueue = SimplificationQueue;
  45000. /**
  45001. * The implemented types of simplification.
  45002. * At the moment only Quadratic Error Decimation is implemented.
  45003. */
  45004. var SimplificationType;
  45005. (function (SimplificationType) {
  45006. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  45007. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  45008. var DecimationTriangle = (function () {
  45009. function DecimationTriangle(vertices) {
  45010. this.vertices = vertices;
  45011. this.error = new Array(4);
  45012. this.deleted = false;
  45013. this.isDirty = false;
  45014. this.deletePending = false;
  45015. this.borderFactor = 0;
  45016. }
  45017. return DecimationTriangle;
  45018. }());
  45019. BABYLON.DecimationTriangle = DecimationTriangle;
  45020. var DecimationVertex = (function () {
  45021. function DecimationVertex(position, id) {
  45022. this.position = position;
  45023. this.id = id;
  45024. this.isBorder = true;
  45025. this.q = new QuadraticMatrix();
  45026. this.triangleCount = 0;
  45027. this.triangleStart = 0;
  45028. this.originalOffsets = [];
  45029. }
  45030. DecimationVertex.prototype.updatePosition = function (newPosition) {
  45031. this.position.copyFrom(newPosition);
  45032. };
  45033. return DecimationVertex;
  45034. }());
  45035. BABYLON.DecimationVertex = DecimationVertex;
  45036. var QuadraticMatrix = (function () {
  45037. function QuadraticMatrix(data) {
  45038. this.data = new Array(10);
  45039. for (var i = 0; i < 10; ++i) {
  45040. if (data && data[i]) {
  45041. this.data[i] = data[i];
  45042. }
  45043. else {
  45044. this.data[i] = 0;
  45045. }
  45046. }
  45047. }
  45048. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  45049. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  45050. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  45051. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  45052. return det;
  45053. };
  45054. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  45055. for (var i = 0; i < 10; ++i) {
  45056. this.data[i] += matrix.data[i];
  45057. }
  45058. };
  45059. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  45060. for (var i = 0; i < 10; ++i) {
  45061. this.data[i] += data[i];
  45062. }
  45063. };
  45064. QuadraticMatrix.prototype.add = function (matrix) {
  45065. var m = new QuadraticMatrix();
  45066. for (var i = 0; i < 10; ++i) {
  45067. m.data[i] = this.data[i] + matrix.data[i];
  45068. }
  45069. return m;
  45070. };
  45071. QuadraticMatrix.FromData = function (a, b, c, d) {
  45072. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  45073. };
  45074. //returning an array to avoid garbage collection
  45075. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  45076. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  45077. };
  45078. return QuadraticMatrix;
  45079. }());
  45080. BABYLON.QuadraticMatrix = QuadraticMatrix;
  45081. var Reference = (function () {
  45082. function Reference(vertexId, triangleId) {
  45083. this.vertexId = vertexId;
  45084. this.triangleId = triangleId;
  45085. }
  45086. return Reference;
  45087. }());
  45088. BABYLON.Reference = Reference;
  45089. /**
  45090. * An implementation of the Quadratic Error simplification algorithm.
  45091. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  45092. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  45093. * @author RaananW
  45094. */
  45095. var QuadraticErrorSimplification = (function () {
  45096. function QuadraticErrorSimplification(_mesh) {
  45097. this._mesh = _mesh;
  45098. this.initialized = false;
  45099. this.syncIterations = 5000;
  45100. this.aggressiveness = 7;
  45101. this.decimationIterations = 100;
  45102. this.boundingBoxEpsilon = BABYLON.Epsilon;
  45103. }
  45104. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  45105. var _this = this;
  45106. this.initDecimatedMesh();
  45107. //iterating through the submeshes array, one after the other.
  45108. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  45109. _this.initWithMesh(loop.index, function () {
  45110. _this.runDecimation(settings, loop.index, function () {
  45111. loop.executeNext();
  45112. });
  45113. }, settings.optimizeMesh);
  45114. }, function () {
  45115. setTimeout(function () {
  45116. successCallback(_this._reconstructedMesh);
  45117. }, 0);
  45118. });
  45119. };
  45120. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  45121. var _this = this;
  45122. var gCount = 0;
  45123. triangle.vertices.forEach(function (vertex) {
  45124. var count = 0;
  45125. var vPos = vertex.position;
  45126. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  45127. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  45128. ++count;
  45129. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  45130. ++count;
  45131. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  45132. ++count;
  45133. if (count > 1) {
  45134. ++gCount;
  45135. }
  45136. ;
  45137. });
  45138. if (gCount > 1) {
  45139. console.log(triangle, gCount);
  45140. }
  45141. return gCount > 1;
  45142. };
  45143. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  45144. var _this = this;
  45145. var targetCount = ~~(this.triangles.length * settings.quality);
  45146. var deletedTriangles = 0;
  45147. var triangleCount = this.triangles.length;
  45148. var iterationFunction = function (iteration, callback) {
  45149. setTimeout(function () {
  45150. if (iteration % 5 === 0) {
  45151. _this.updateMesh(iteration === 0);
  45152. }
  45153. for (var i = 0; i < _this.triangles.length; ++i) {
  45154. _this.triangles[i].isDirty = false;
  45155. }
  45156. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  45157. var trianglesIterator = function (i) {
  45158. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  45159. var t = _this.triangles[tIdx];
  45160. if (!t)
  45161. return;
  45162. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  45163. return;
  45164. }
  45165. for (var j = 0; j < 3; ++j) {
  45166. if (t.error[j] < threshold) {
  45167. var deleted0 = [];
  45168. var deleted1 = [];
  45169. var v0 = t.vertices[j];
  45170. var v1 = t.vertices[(j + 1) % 3];
  45171. if (v0.isBorder || v1.isBorder)
  45172. continue;
  45173. var p = BABYLON.Vector3.Zero();
  45174. var n = BABYLON.Vector3.Zero();
  45175. var uv = BABYLON.Vector2.Zero();
  45176. var color = new BABYLON.Color4(0, 0, 0, 1);
  45177. _this.calculateError(v0, v1, p, n, uv, color);
  45178. var delTr = [];
  45179. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  45180. continue;
  45181. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  45182. continue;
  45183. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  45184. continue;
  45185. var uniqueArray = [];
  45186. delTr.forEach(function (deletedT) {
  45187. if (uniqueArray.indexOf(deletedT) === -1) {
  45188. deletedT.deletePending = true;
  45189. uniqueArray.push(deletedT);
  45190. }
  45191. });
  45192. if (uniqueArray.length % 2 !== 0) {
  45193. continue;
  45194. }
  45195. v0.q = v1.q.add(v0.q);
  45196. v0.updatePosition(p);
  45197. var tStart = _this.references.length;
  45198. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  45199. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  45200. var tCount = _this.references.length - tStart;
  45201. if (tCount <= v0.triangleCount) {
  45202. if (tCount) {
  45203. for (var c = 0; c < tCount; c++) {
  45204. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  45205. }
  45206. }
  45207. }
  45208. else {
  45209. v0.triangleStart = tStart;
  45210. }
  45211. v0.triangleCount = tCount;
  45212. break;
  45213. }
  45214. }
  45215. };
  45216. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  45217. }, 0);
  45218. };
  45219. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  45220. if (triangleCount - deletedTriangles <= targetCount)
  45221. loop.breakLoop();
  45222. else {
  45223. iterationFunction(loop.index, function () {
  45224. loop.executeNext();
  45225. });
  45226. }
  45227. }, function () {
  45228. setTimeout(function () {
  45229. //reconstruct this part of the mesh
  45230. _this.reconstructMesh(submeshIndex);
  45231. successCallback();
  45232. }, 0);
  45233. });
  45234. };
  45235. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  45236. var _this = this;
  45237. this.vertices = [];
  45238. this.triangles = [];
  45239. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45240. var indices = this._mesh.getIndices();
  45241. var submesh = this._mesh.subMeshes[submeshIndex];
  45242. var findInVertices = function (positionToSearch) {
  45243. if (optimizeMesh) {
  45244. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  45245. if (_this.vertices[ii].position.equals(positionToSearch)) {
  45246. return _this.vertices[ii];
  45247. }
  45248. }
  45249. }
  45250. return null;
  45251. };
  45252. var vertexReferences = [];
  45253. var vertexInit = function (i) {
  45254. var offset = i + submesh.verticesStart;
  45255. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  45256. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  45257. vertex.originalOffsets.push(offset);
  45258. if (vertex.id === _this.vertices.length) {
  45259. _this.vertices.push(vertex);
  45260. }
  45261. vertexReferences.push(vertex.id);
  45262. };
  45263. //var totalVertices = mesh.getTotalVertices();
  45264. var totalVertices = submesh.verticesCount;
  45265. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  45266. var indicesInit = function (i) {
  45267. var offset = (submesh.indexStart / 3) + i;
  45268. var pos = (offset * 3);
  45269. var i0 = indices[pos + 0];
  45270. var i1 = indices[pos + 1];
  45271. var i2 = indices[pos + 2];
  45272. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  45273. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  45274. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  45275. var triangle = new DecimationTriangle([v0, v1, v2]);
  45276. triangle.originalOffset = pos;
  45277. _this.triangles.push(triangle);
  45278. };
  45279. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  45280. _this.init(callback);
  45281. });
  45282. });
  45283. };
  45284. QuadraticErrorSimplification.prototype.init = function (callback) {
  45285. var _this = this;
  45286. var triangleInit1 = function (i) {
  45287. var t = _this.triangles[i];
  45288. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  45289. for (var j = 0; j < 3; j++) {
  45290. 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))));
  45291. }
  45292. };
  45293. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  45294. var triangleInit2 = function (i) {
  45295. var t = _this.triangles[i];
  45296. for (var j = 0; j < 3; ++j) {
  45297. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  45298. }
  45299. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45300. };
  45301. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  45302. _this.initialized = true;
  45303. callback();
  45304. });
  45305. });
  45306. };
  45307. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  45308. var newTriangles = [];
  45309. var i;
  45310. for (i = 0; i < this.vertices.length; ++i) {
  45311. this.vertices[i].triangleCount = 0;
  45312. }
  45313. var t;
  45314. var j;
  45315. for (i = 0; i < this.triangles.length; ++i) {
  45316. if (!this.triangles[i].deleted) {
  45317. t = this.triangles[i];
  45318. for (j = 0; j < 3; ++j) {
  45319. t.vertices[j].triangleCount = 1;
  45320. }
  45321. newTriangles.push(t);
  45322. }
  45323. }
  45324. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  45325. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  45326. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  45327. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  45328. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45329. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45330. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45331. var vertexCount = 0;
  45332. for (i = 0; i < this.vertices.length; ++i) {
  45333. var vertex = this.vertices[i];
  45334. vertex.id = vertexCount;
  45335. if (vertex.triangleCount) {
  45336. vertex.originalOffsets.forEach(function (originalOffset) {
  45337. newPositionData.push(vertex.position.x);
  45338. newPositionData.push(vertex.position.y);
  45339. newPositionData.push(vertex.position.z);
  45340. newNormalData.push(normalData[originalOffset * 3]);
  45341. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  45342. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  45343. if (uvs && uvs.length) {
  45344. newUVsData.push(uvs[(originalOffset * 2)]);
  45345. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  45346. }
  45347. else if (colorsData && colorsData.length) {
  45348. newColorsData.push(colorsData[(originalOffset * 4)]);
  45349. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  45350. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  45351. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  45352. }
  45353. ++vertexCount;
  45354. });
  45355. }
  45356. }
  45357. var startingIndex = this._reconstructedMesh.getTotalIndices();
  45358. var startingVertex = this._reconstructedMesh.getTotalVertices();
  45359. var submeshesArray = this._reconstructedMesh.subMeshes;
  45360. this._reconstructedMesh.subMeshes = [];
  45361. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  45362. var originalIndices = this._mesh.getIndices();
  45363. for (i = 0; i < newTriangles.length; ++i) {
  45364. t = newTriangles[i]; //now get the new referencing point for each vertex
  45365. [0, 1, 2].forEach(function (idx) {
  45366. var id = originalIndices[t.originalOffset + idx];
  45367. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  45368. if (offset < 0)
  45369. offset = 0;
  45370. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  45371. });
  45372. }
  45373. //overwriting the old vertex buffers and indices.
  45374. this._reconstructedMesh.setIndices(newIndicesArray);
  45375. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  45376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  45377. if (newUVsData.length > 0)
  45378. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  45379. if (newColorsData.length > 0)
  45380. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  45381. //create submesh
  45382. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  45383. if (submeshIndex > 0) {
  45384. this._reconstructedMesh.subMeshes = [];
  45385. submeshesArray.forEach(function (submesh) {
  45386. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  45387. });
  45388. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  45389. }
  45390. };
  45391. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  45392. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  45393. this._reconstructedMesh.material = this._mesh.material;
  45394. this._reconstructedMesh.parent = this._mesh.parent;
  45395. this._reconstructedMesh.isVisible = false;
  45396. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  45397. };
  45398. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  45399. for (var i = 0; i < vertex1.triangleCount; ++i) {
  45400. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  45401. if (t.deleted)
  45402. continue;
  45403. var s = this.references[vertex1.triangleStart + i].vertexId;
  45404. var v1 = t.vertices[(s + 1) % 3];
  45405. var v2 = t.vertices[(s + 2) % 3];
  45406. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  45407. deletedArray[i] = true;
  45408. delTr.push(t);
  45409. continue;
  45410. }
  45411. var d1 = v1.position.subtract(point);
  45412. d1 = d1.normalize();
  45413. var d2 = v2.position.subtract(point);
  45414. d2 = d2.normalize();
  45415. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  45416. return true;
  45417. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  45418. deletedArray[i] = false;
  45419. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  45420. return true;
  45421. }
  45422. return false;
  45423. };
  45424. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  45425. var newDeleted = deletedTriangles;
  45426. for (var i = 0; i < vertex.triangleCount; ++i) {
  45427. var ref = this.references[vertex.triangleStart + i];
  45428. var t = this.triangles[ref.triangleId];
  45429. if (t.deleted)
  45430. continue;
  45431. if (deletedArray[i] && t.deletePending) {
  45432. t.deleted = true;
  45433. newDeleted++;
  45434. continue;
  45435. }
  45436. t.vertices[ref.vertexId] = origVertex;
  45437. t.isDirty = true;
  45438. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  45439. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  45440. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  45441. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45442. this.references.push(ref);
  45443. }
  45444. return newDeleted;
  45445. };
  45446. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  45447. for (var i = 0; i < this.vertices.length; ++i) {
  45448. var vCount = [];
  45449. var vId = [];
  45450. var v = this.vertices[i];
  45451. var j;
  45452. for (j = 0; j < v.triangleCount; ++j) {
  45453. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  45454. for (var ii = 0; ii < 3; ii++) {
  45455. var ofs = 0;
  45456. var vv = triangle.vertices[ii];
  45457. while (ofs < vCount.length) {
  45458. if (vId[ofs] === vv.id)
  45459. break;
  45460. ++ofs;
  45461. }
  45462. if (ofs === vCount.length) {
  45463. vCount.push(1);
  45464. vId.push(vv.id);
  45465. }
  45466. else {
  45467. vCount[ofs]++;
  45468. }
  45469. }
  45470. }
  45471. for (j = 0; j < vCount.length; ++j) {
  45472. if (vCount[j] === 1) {
  45473. this.vertices[vId[j]].isBorder = true;
  45474. }
  45475. else {
  45476. this.vertices[vId[j]].isBorder = false;
  45477. }
  45478. }
  45479. }
  45480. };
  45481. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  45482. if (identifyBorders === void 0) { identifyBorders = false; }
  45483. var i;
  45484. if (!identifyBorders) {
  45485. var newTrianglesVector = [];
  45486. for (i = 0; i < this.triangles.length; ++i) {
  45487. if (!this.triangles[i].deleted) {
  45488. newTrianglesVector.push(this.triangles[i]);
  45489. }
  45490. }
  45491. this.triangles = newTrianglesVector;
  45492. }
  45493. for (i = 0; i < this.vertices.length; ++i) {
  45494. this.vertices[i].triangleCount = 0;
  45495. this.vertices[i].triangleStart = 0;
  45496. }
  45497. var t;
  45498. var j;
  45499. var v;
  45500. for (i = 0; i < this.triangles.length; ++i) {
  45501. t = this.triangles[i];
  45502. for (j = 0; j < 3; ++j) {
  45503. v = t.vertices[j];
  45504. v.triangleCount++;
  45505. }
  45506. }
  45507. var tStart = 0;
  45508. for (i = 0; i < this.vertices.length; ++i) {
  45509. this.vertices[i].triangleStart = tStart;
  45510. tStart += this.vertices[i].triangleCount;
  45511. this.vertices[i].triangleCount = 0;
  45512. }
  45513. var newReferences = new Array(this.triangles.length * 3);
  45514. for (i = 0; i < this.triangles.length; ++i) {
  45515. t = this.triangles[i];
  45516. for (j = 0; j < 3; ++j) {
  45517. v = t.vertices[j];
  45518. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  45519. v.triangleCount++;
  45520. }
  45521. }
  45522. this.references = newReferences;
  45523. if (identifyBorders) {
  45524. this.identifyBorder();
  45525. }
  45526. };
  45527. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  45528. var x = point.x;
  45529. var y = point.y;
  45530. var z = point.z;
  45531. 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
  45532. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  45533. };
  45534. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  45535. var q = vertex1.q.add(vertex2.q);
  45536. var border = vertex1.isBorder && vertex2.isBorder;
  45537. var error = 0;
  45538. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  45539. if (qDet !== 0 && !border) {
  45540. if (!pointResult) {
  45541. pointResult = BABYLON.Vector3.Zero();
  45542. }
  45543. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  45544. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  45545. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  45546. error = this.vertexError(q, pointResult);
  45547. }
  45548. else {
  45549. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  45550. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  45551. var error1 = this.vertexError(q, vertex1.position);
  45552. var error2 = this.vertexError(q, vertex2.position);
  45553. var error3 = this.vertexError(q, p3);
  45554. error = Math.min(error1, error2, error3);
  45555. if (error === error1) {
  45556. if (pointResult) {
  45557. pointResult.copyFrom(vertex1.position);
  45558. }
  45559. }
  45560. else if (error === error2) {
  45561. if (pointResult) {
  45562. pointResult.copyFrom(vertex2.position);
  45563. }
  45564. }
  45565. else {
  45566. if (pointResult) {
  45567. pointResult.copyFrom(p3);
  45568. }
  45569. }
  45570. }
  45571. return error;
  45572. };
  45573. return QuadraticErrorSimplification;
  45574. }());
  45575. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  45576. })(BABYLON || (BABYLON = {}));
  45577. //# sourceMappingURL=babylon.meshSimplification.js.map
  45578. var BABYLON;
  45579. (function (BABYLON) {
  45580. var serializedGeometries = [];
  45581. var serializeGeometry = function (geometry, serializationGeometries) {
  45582. if (serializedGeometries[geometry.id]) {
  45583. return;
  45584. }
  45585. if (geometry.doNotSerialize) {
  45586. return;
  45587. }
  45588. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  45589. serializationGeometries.boxes.push(geometry.serialize());
  45590. }
  45591. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  45592. serializationGeometries.spheres.push(geometry.serialize());
  45593. }
  45594. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  45595. serializationGeometries.cylinders.push(geometry.serialize());
  45596. }
  45597. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  45598. serializationGeometries.toruses.push(geometry.serialize());
  45599. }
  45600. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  45601. serializationGeometries.grounds.push(geometry.serialize());
  45602. }
  45603. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  45604. serializationGeometries.planes.push(geometry.serialize());
  45605. }
  45606. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  45607. serializationGeometries.torusKnots.push(geometry.serialize());
  45608. }
  45609. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  45610. throw new Error("Unknown primitive type");
  45611. }
  45612. else {
  45613. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  45614. }
  45615. serializedGeometries[geometry.id] = true;
  45616. };
  45617. var serializeMesh = function (mesh, serializationScene) {
  45618. var serializationObject = {};
  45619. serializationObject.name = mesh.name;
  45620. serializationObject.id = mesh.id;
  45621. if (BABYLON.Tags.HasTags(mesh)) {
  45622. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  45623. }
  45624. serializationObject.position = mesh.position.asArray();
  45625. if (mesh.rotationQuaternion) {
  45626. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  45627. }
  45628. else if (mesh.rotation) {
  45629. serializationObject.rotation = mesh.rotation.asArray();
  45630. }
  45631. serializationObject.scaling = mesh.scaling.asArray();
  45632. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  45633. serializationObject.isEnabled = mesh.isEnabled();
  45634. serializationObject.isVisible = mesh.isVisible;
  45635. serializationObject.infiniteDistance = mesh.infiniteDistance;
  45636. serializationObject.pickable = mesh.isPickable;
  45637. serializationObject.receiveShadows = mesh.receiveShadows;
  45638. serializationObject.billboardMode = mesh.billboardMode;
  45639. serializationObject.visibility = mesh.visibility;
  45640. serializationObject.checkCollisions = mesh.checkCollisions;
  45641. serializationObject.isBlocker = mesh.isBlocker;
  45642. // Parent
  45643. if (mesh.parent) {
  45644. serializationObject.parentId = mesh.parent.id;
  45645. }
  45646. // Geometry
  45647. var geometry = mesh._geometry;
  45648. if (geometry) {
  45649. var geometryId = geometry.id;
  45650. serializationObject.geometryId = geometryId;
  45651. if (!mesh.getScene().getGeometryByID(geometryId)) {
  45652. // 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
  45653. serializeGeometry(geometry, serializationScene.geometries);
  45654. }
  45655. // SubMeshes
  45656. serializationObject.subMeshes = [];
  45657. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45658. var subMesh = mesh.subMeshes[subIndex];
  45659. serializationObject.subMeshes.push({
  45660. materialIndex: subMesh.materialIndex,
  45661. verticesStart: subMesh.verticesStart,
  45662. verticesCount: subMesh.verticesCount,
  45663. indexStart: subMesh.indexStart,
  45664. indexCount: subMesh.indexCount
  45665. });
  45666. }
  45667. }
  45668. // Material
  45669. if (mesh.material) {
  45670. serializationObject.materialId = mesh.material.id;
  45671. }
  45672. else {
  45673. mesh.material = null;
  45674. }
  45675. // Skeleton
  45676. if (mesh.skeleton) {
  45677. serializationObject.skeletonId = mesh.skeleton.id;
  45678. }
  45679. // Physics
  45680. //TODO implement correct serialization for physics impostors.
  45681. if (mesh.getPhysicsImpostor()) {
  45682. serializationObject.physicsMass = mesh.getPhysicsMass();
  45683. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  45684. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  45685. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  45686. }
  45687. // Metadata
  45688. if (mesh.metadata) {
  45689. serializationObject.metadata = mesh.metadata;
  45690. }
  45691. // Instances
  45692. serializationObject.instances = [];
  45693. for (var index = 0; index < mesh.instances.length; index++) {
  45694. var instance = mesh.instances[index];
  45695. var serializationInstance = {
  45696. name: instance.name,
  45697. position: instance.position.asArray(),
  45698. scaling: instance.scaling.asArray()
  45699. };
  45700. if (instance.rotationQuaternion) {
  45701. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  45702. }
  45703. else if (instance.rotation) {
  45704. serializationInstance.rotation = instance.rotation.asArray();
  45705. }
  45706. serializationObject.instances.push(serializationInstance);
  45707. // Animations
  45708. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  45709. serializationInstance.ranges = instance.serializeAnimationRanges();
  45710. }
  45711. // Animations
  45712. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  45713. serializationObject.ranges = mesh.serializeAnimationRanges();
  45714. // Layer mask
  45715. serializationObject.layerMask = mesh.layerMask;
  45716. // Alpha
  45717. serializationObject.alphaIndex = mesh.alphaIndex;
  45718. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  45719. // Overlay
  45720. serializationObject.overlayAlpha = mesh.overlayAlpha;
  45721. serializationObject.overlayColor = mesh.overlayColor.asArray();
  45722. serializationObject.renderOverlay = mesh.renderOverlay;
  45723. // Fog
  45724. serializationObject.applyFog = mesh.applyFog;
  45725. // Action Manager
  45726. if (mesh.actionManager) {
  45727. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  45728. }
  45729. return serializationObject;
  45730. };
  45731. var finalizeSingleMesh = function (mesh, serializationObject) {
  45732. //only works if the mesh is already loaded
  45733. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45734. //serialize material
  45735. if (mesh.material) {
  45736. if (mesh.material instanceof BABYLON.StandardMaterial) {
  45737. serializationObject.materials = serializationObject.materials || [];
  45738. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45739. serializationObject.materials.push(mesh.material.serialize());
  45740. }
  45741. }
  45742. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  45743. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  45744. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45745. serializationObject.multiMaterials.push(mesh.material.serialize());
  45746. }
  45747. }
  45748. }
  45749. //serialize geometry
  45750. var geometry = mesh._geometry;
  45751. if (geometry) {
  45752. if (!serializationObject.geometries) {
  45753. serializationObject.geometries = {};
  45754. serializationObject.geometries.boxes = [];
  45755. serializationObject.geometries.spheres = [];
  45756. serializationObject.geometries.cylinders = [];
  45757. serializationObject.geometries.toruses = [];
  45758. serializationObject.geometries.grounds = [];
  45759. serializationObject.geometries.planes = [];
  45760. serializationObject.geometries.torusKnots = [];
  45761. serializationObject.geometries.vertexData = [];
  45762. }
  45763. serializeGeometry(geometry, serializationObject.geometries);
  45764. }
  45765. // Skeletons
  45766. if (mesh.skeleton) {
  45767. serializationObject.skeletons = serializationObject.skeletons || [];
  45768. serializationObject.skeletons.push(mesh.skeleton.serialize());
  45769. }
  45770. //serialize the actual mesh
  45771. serializationObject.meshes = serializationObject.meshes || [];
  45772. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45773. }
  45774. };
  45775. var SceneSerializer = (function () {
  45776. function SceneSerializer() {
  45777. }
  45778. SceneSerializer.ClearCache = function () {
  45779. serializedGeometries = [];
  45780. };
  45781. SceneSerializer.Serialize = function (scene) {
  45782. var serializationObject = {};
  45783. // Scene
  45784. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  45785. serializationObject.autoClear = scene.autoClear;
  45786. serializationObject.clearColor = scene.clearColor.asArray();
  45787. serializationObject.ambientColor = scene.ambientColor.asArray();
  45788. serializationObject.gravity = scene.gravity.asArray();
  45789. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  45790. serializationObject.workerCollisions = scene.workerCollisions;
  45791. // Fog
  45792. if (scene.fogMode && scene.fogMode !== 0) {
  45793. serializationObject.fogMode = scene.fogMode;
  45794. serializationObject.fogColor = scene.fogColor.asArray();
  45795. serializationObject.fogStart = scene.fogStart;
  45796. serializationObject.fogEnd = scene.fogEnd;
  45797. serializationObject.fogDensity = scene.fogDensity;
  45798. }
  45799. //Physics
  45800. if (scene.isPhysicsEnabled()) {
  45801. serializationObject.physicsEnabled = true;
  45802. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  45803. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  45804. }
  45805. // Metadata
  45806. if (scene.metadata) {
  45807. serializationObject.metadata = scene.metadata;
  45808. }
  45809. // Lights
  45810. serializationObject.lights = [];
  45811. var index;
  45812. var light;
  45813. for (index = 0; index < scene.lights.length; index++) {
  45814. light = scene.lights[index];
  45815. if (!light.doNotSerialize) {
  45816. serializationObject.lights.push(light.serialize());
  45817. }
  45818. }
  45819. // Cameras
  45820. serializationObject.cameras = [];
  45821. for (index = 0; index < scene.cameras.length; index++) {
  45822. var camera = scene.cameras[index];
  45823. if (!camera.doNotSerialize) {
  45824. serializationObject.cameras.push(camera.serialize());
  45825. }
  45826. }
  45827. if (scene.activeCamera) {
  45828. serializationObject.activeCameraID = scene.activeCamera.id;
  45829. }
  45830. // Animations
  45831. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  45832. // Materials
  45833. serializationObject.materials = [];
  45834. serializationObject.multiMaterials = [];
  45835. var material;
  45836. for (index = 0; index < scene.materials.length; index++) {
  45837. material = scene.materials[index];
  45838. if (!material.doNotSerialize) {
  45839. serializationObject.materials.push(material.serialize());
  45840. }
  45841. }
  45842. // MultiMaterials
  45843. serializationObject.multiMaterials = [];
  45844. for (index = 0; index < scene.multiMaterials.length; index++) {
  45845. var multiMaterial = scene.multiMaterials[index];
  45846. serializationObject.multiMaterials.push(multiMaterial.serialize());
  45847. }
  45848. // Skeletons
  45849. serializationObject.skeletons = [];
  45850. for (index = 0; index < scene.skeletons.length; index++) {
  45851. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  45852. }
  45853. // Geometries
  45854. serializationObject.geometries = {};
  45855. serializationObject.geometries.boxes = [];
  45856. serializationObject.geometries.spheres = [];
  45857. serializationObject.geometries.cylinders = [];
  45858. serializationObject.geometries.toruses = [];
  45859. serializationObject.geometries.grounds = [];
  45860. serializationObject.geometries.planes = [];
  45861. serializationObject.geometries.torusKnots = [];
  45862. serializationObject.geometries.vertexData = [];
  45863. serializedGeometries = [];
  45864. var geometries = scene.getGeometries();
  45865. for (index = 0; index < geometries.length; index++) {
  45866. var geometry = geometries[index];
  45867. if (geometry.isReady()) {
  45868. serializeGeometry(geometry, serializationObject.geometries);
  45869. }
  45870. }
  45871. // Meshes
  45872. serializationObject.meshes = [];
  45873. for (index = 0; index < scene.meshes.length; index++) {
  45874. var abstractMesh = scene.meshes[index];
  45875. if (abstractMesh instanceof BABYLON.Mesh) {
  45876. var mesh = abstractMesh;
  45877. if (!mesh.doNotSerialize) {
  45878. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45879. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45880. }
  45881. }
  45882. }
  45883. }
  45884. // Particles Systems
  45885. serializationObject.particleSystems = [];
  45886. for (index = 0; index < scene.particleSystems.length; index++) {
  45887. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  45888. }
  45889. // Lens flares
  45890. serializationObject.lensFlareSystems = [];
  45891. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  45892. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  45893. }
  45894. // Shadows
  45895. serializationObject.shadowGenerators = [];
  45896. for (index = 0; index < scene.lights.length; index++) {
  45897. light = scene.lights[index];
  45898. var shadowGenerator = light.getShadowGenerator();
  45899. // Only support serialization for official generator so far.
  45900. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  45901. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  45902. }
  45903. }
  45904. // Action Manager
  45905. if (scene.actionManager) {
  45906. serializationObject.actions = scene.actionManager.serialize("scene");
  45907. }
  45908. // Audio
  45909. serializationObject.sounds = [];
  45910. for (index = 0; index < scene.soundTracks.length; index++) {
  45911. var soundtrack = scene.soundTracks[index];
  45912. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  45913. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  45914. }
  45915. }
  45916. return serializationObject;
  45917. };
  45918. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  45919. if (withParents === void 0) { withParents = false; }
  45920. if (withChildren === void 0) { withChildren = false; }
  45921. var serializationObject = {};
  45922. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  45923. if (withParents || withChildren) {
  45924. //deliberate for loop! not for each, appended should be processed as well.
  45925. for (var i = 0; i < toSerialize.length; ++i) {
  45926. if (withChildren) {
  45927. toSerialize[i].getDescendants().forEach(function (node) {
  45928. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  45929. toSerialize.push(node);
  45930. }
  45931. });
  45932. }
  45933. //make sure the array doesn't contain the object already
  45934. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  45935. toSerialize.push(toSerialize[i].parent);
  45936. }
  45937. }
  45938. }
  45939. toSerialize.forEach(function (mesh) {
  45940. finalizeSingleMesh(mesh, serializationObject);
  45941. });
  45942. return serializationObject;
  45943. };
  45944. return SceneSerializer;
  45945. }());
  45946. BABYLON.SceneSerializer = SceneSerializer;
  45947. })(BABYLON || (BABYLON = {}));
  45948. //# sourceMappingURL=babylon.sceneSerializer.js.map
  45949. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  45950. // Huge respect for a such great lib.
  45951. // Earcut license:
  45952. // Copyright (c) 2016, Mapbox
  45953. //
  45954. // Permission to use, copy, modify, and/or distribute this software for any purpose
  45955. // with or without fee is hereby granted, provided that the above copyright notice
  45956. // and this permission notice appear in all copies.
  45957. //
  45958. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  45959. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  45960. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  45961. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  45962. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  45963. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  45964. // THIS SOFTWARE.
  45965. var Earcut;
  45966. (function (Earcut) {
  45967. /**
  45968. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  45969. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  45970. * @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).
  45971. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  45972. */
  45973. function earcut(data, holeIndices, dim) {
  45974. dim = dim || 2;
  45975. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  45976. if (!outerNode)
  45977. return triangles;
  45978. var minX, minY, maxX, maxY, x, y, size;
  45979. if (hasHoles)
  45980. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  45981. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  45982. if (data.length > 80 * dim) {
  45983. minX = maxX = data[0];
  45984. minY = maxY = data[1];
  45985. for (var i = dim; i < outerLen; i += dim) {
  45986. x = data[i];
  45987. y = data[i + 1];
  45988. if (x < minX)
  45989. minX = x;
  45990. if (y < minY)
  45991. minY = y;
  45992. if (x > maxX)
  45993. maxX = x;
  45994. if (y > maxY)
  45995. maxY = y;
  45996. }
  45997. // minX, minY and size are later used to transform coords into integers for z-order calculation
  45998. size = Math.max(maxX - minX, maxY - minY);
  45999. }
  46000. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  46001. return triangles;
  46002. }
  46003. Earcut.earcut = earcut;
  46004. // create a circular doubly linked list from polygon points in the specified winding order
  46005. function linkedList(data, start, end, dim, clockwise) {
  46006. var i, last;
  46007. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  46008. for (i = start; i < end; i += dim)
  46009. last = insertNode(i, data[i], data[i + 1], last);
  46010. }
  46011. else {
  46012. for (i = end - dim; i >= start; i -= dim)
  46013. last = insertNode(i, data[i], data[i + 1], last);
  46014. }
  46015. if (last && equals(last, last.next)) {
  46016. removeNode(last);
  46017. last = last.next;
  46018. }
  46019. return last;
  46020. }
  46021. // eliminate colinear or duplicate points
  46022. function filterPoints(start, end) {
  46023. if (!start)
  46024. return start;
  46025. if (!end)
  46026. end = start;
  46027. var p = start, again;
  46028. do {
  46029. again = false;
  46030. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  46031. removeNode(p);
  46032. p = end = p.prev;
  46033. if (p === p.next)
  46034. return null;
  46035. again = true;
  46036. }
  46037. else {
  46038. p = p.next;
  46039. }
  46040. } while (again || p !== end);
  46041. return end;
  46042. }
  46043. // main ear slicing loop which triangulates a polygon (given as a linked list)
  46044. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  46045. if (!ear)
  46046. return;
  46047. // interlink polygon nodes in z-order
  46048. if (!pass && size)
  46049. indexCurve(ear, minX, minY, size);
  46050. var stop = ear, prev, next;
  46051. // iterate through ears, slicing them one by one
  46052. while (ear.prev !== ear.next) {
  46053. prev = ear.prev;
  46054. next = ear.next;
  46055. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  46056. // cut off the triangle
  46057. triangles.push(prev.i / dim);
  46058. triangles.push(ear.i / dim);
  46059. triangles.push(next.i / dim);
  46060. removeNode(ear);
  46061. // skipping the next vertice leads to less sliver triangles
  46062. ear = next.next;
  46063. stop = next.next;
  46064. continue;
  46065. }
  46066. ear = next;
  46067. // if we looped through the whole remaining polygon and can't find any more ears
  46068. if (ear === stop) {
  46069. // try filtering points and slicing again
  46070. if (!pass) {
  46071. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  46072. }
  46073. else if (pass === 1) {
  46074. ear = cureLocalIntersections(ear, triangles, dim);
  46075. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  46076. }
  46077. else if (pass === 2) {
  46078. splitEarcut(ear, triangles, dim, minX, minY, size);
  46079. }
  46080. break;
  46081. }
  46082. }
  46083. }
  46084. // check whether a polygon node forms a valid ear with adjacent nodes
  46085. function isEar(ear) {
  46086. var a = ear.prev, b = ear, c = ear.next;
  46087. if (area(a, b, c) >= 0)
  46088. return false; // reflex, can't be an ear
  46089. // now make sure we don't have other points inside the potential ear
  46090. var p = ear.next.next;
  46091. while (p !== ear.prev) {
  46092. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46093. area(p.prev, p, p.next) >= 0)
  46094. return false;
  46095. p = p.next;
  46096. }
  46097. return true;
  46098. }
  46099. function isEarHashed(ear, minX, minY, size) {
  46100. var a = ear.prev, b = ear, c = ear.next;
  46101. if (area(a, b, c) >= 0)
  46102. return false; // reflex, can't be an ear
  46103. // triangle bbox; min & max are calculated like this for speed
  46104. 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);
  46105. // z-order range for the current triangle bbox;
  46106. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  46107. // first look for points inside the triangle in increasing z-order
  46108. var p = ear.nextZ;
  46109. while (p && p.z <= maxZ) {
  46110. if (p !== ear.prev &&
  46111. p !== ear.next &&
  46112. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46113. area(p.prev, p, p.next) >= 0)
  46114. return false;
  46115. p = p.nextZ;
  46116. }
  46117. // then look for points in decreasing z-order
  46118. p = ear.prevZ;
  46119. while (p && p.z >= minZ) {
  46120. if (p !== ear.prev &&
  46121. p !== ear.next &&
  46122. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46123. area(p.prev, p, p.next) >= 0)
  46124. return false;
  46125. p = p.prevZ;
  46126. }
  46127. return true;
  46128. }
  46129. // go through all polygon nodes and cure small local self-intersections
  46130. function cureLocalIntersections(start, triangles, dim) {
  46131. var p = start;
  46132. do {
  46133. var a = p.prev, b = p.next.next;
  46134. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  46135. triangles.push(a.i / dim);
  46136. triangles.push(p.i / dim);
  46137. triangles.push(b.i / dim);
  46138. // remove two nodes involved
  46139. removeNode(p);
  46140. removeNode(p.next);
  46141. p = start = b;
  46142. }
  46143. p = p.next;
  46144. } while (p !== start);
  46145. return p;
  46146. }
  46147. // try splitting polygon into two and triangulate them independently
  46148. function splitEarcut(start, triangles, dim, minX, minY, size) {
  46149. // look for a valid diagonal that divides the polygon into two
  46150. var a = start;
  46151. do {
  46152. var b = a.next.next;
  46153. while (b !== a.prev) {
  46154. if (a.i !== b.i && isValidDiagonal(a, b)) {
  46155. // split the polygon in two by the diagonal
  46156. var c = splitPolygon(a, b);
  46157. // filter colinear points around the cuts
  46158. a = filterPoints(a, a.next);
  46159. c = filterPoints(c, c.next);
  46160. // run earcut on each half
  46161. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  46162. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  46163. return;
  46164. }
  46165. b = b.next;
  46166. }
  46167. a = a.next;
  46168. } while (a !== start);
  46169. }
  46170. // link every hole into the outer loop, producing a single-ring polygon without holes
  46171. function eliminateHoles(data, holeIndices, outerNode, dim) {
  46172. var queue = [], i, len, start, end, list;
  46173. for (i = 0, len = holeIndices.length; i < len; i++) {
  46174. start = holeIndices[i] * dim;
  46175. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46176. list = linkedList(data, start, end, dim, false);
  46177. if (list === list.next)
  46178. list.steiner = true;
  46179. queue.push(getLeftmost(list));
  46180. }
  46181. queue.sort(compareX);
  46182. // process holes from left to right
  46183. for (i = 0; i < queue.length; i++) {
  46184. eliminateHole(queue[i], outerNode);
  46185. outerNode = filterPoints(outerNode, outerNode.next);
  46186. }
  46187. return outerNode;
  46188. }
  46189. function compareX(a, b) {
  46190. return a.x - b.x;
  46191. }
  46192. // find a bridge between vertices that connects hole with an outer ring and and link it
  46193. function eliminateHole(hole, outerNode) {
  46194. outerNode = findHoleBridge(hole, outerNode);
  46195. if (outerNode) {
  46196. var b = splitPolygon(outerNode, hole);
  46197. filterPoints(b, b.next);
  46198. }
  46199. }
  46200. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  46201. function findHoleBridge(hole, outerNode) {
  46202. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  46203. // find a segment intersected by a ray from the hole's leftmost point to the left;
  46204. // segment's endpoint with lesser x will be potential connection point
  46205. do {
  46206. if (hy <= p.y && hy >= p.next.y) {
  46207. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  46208. if (x <= hx && x > qx) {
  46209. qx = x;
  46210. if (x === hx) {
  46211. if (hy === p.y)
  46212. return p;
  46213. if (hy === p.next.y)
  46214. return p.next;
  46215. }
  46216. m = p.x < p.next.x ? p : p.next;
  46217. }
  46218. }
  46219. p = p.next;
  46220. } while (p !== outerNode);
  46221. if (!m)
  46222. return null;
  46223. if (hx === qx)
  46224. return m.prev; // hole touches outer segment; pick lower endpoint
  46225. // look for points inside the triangle of hole point, segment intersection and endpoint;
  46226. // if there are no points found, we have a valid connection;
  46227. // otherwise choose the point of the minimum angle with the ray as connection point
  46228. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  46229. p = m.next;
  46230. while (p !== stop) {
  46231. if (hx >= p.x &&
  46232. p.x >= mx &&
  46233. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  46234. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  46235. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  46236. m = p;
  46237. tanMin = tan;
  46238. }
  46239. }
  46240. p = p.next;
  46241. }
  46242. return m;
  46243. }
  46244. // interlink polygon nodes in z-order
  46245. function indexCurve(start, minX, minY, size) {
  46246. var p = start;
  46247. do {
  46248. if (p.z === null)
  46249. p.z = zOrder(p.x, p.y, minX, minY, size);
  46250. p.prevZ = p.prev;
  46251. p.nextZ = p.next;
  46252. p = p.next;
  46253. } while (p !== start);
  46254. p.prevZ.nextZ = null;
  46255. p.prevZ = null;
  46256. sortLinked(p);
  46257. }
  46258. // Simon Tatham's linked list merge sort algorithm
  46259. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  46260. function sortLinked(list) {
  46261. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  46262. do {
  46263. p = list;
  46264. list = null;
  46265. tail = null;
  46266. numMerges = 0;
  46267. while (p) {
  46268. numMerges++;
  46269. q = p;
  46270. pSize = 0;
  46271. for (i = 0; i < inSize; i++) {
  46272. pSize++;
  46273. q = q.nextZ;
  46274. if (!q)
  46275. break;
  46276. }
  46277. qSize = inSize;
  46278. while (pSize > 0 || (qSize > 0 && q)) {
  46279. if (pSize === 0) {
  46280. e = q;
  46281. q = q.nextZ;
  46282. qSize--;
  46283. }
  46284. else if (qSize === 0 || !q) {
  46285. e = p;
  46286. p = p.nextZ;
  46287. pSize--;
  46288. }
  46289. else if (p.z <= q.z) {
  46290. e = p;
  46291. p = p.nextZ;
  46292. pSize--;
  46293. }
  46294. else {
  46295. e = q;
  46296. q = q.nextZ;
  46297. qSize--;
  46298. }
  46299. if (tail)
  46300. tail.nextZ = e;
  46301. else
  46302. list = e;
  46303. e.prevZ = tail;
  46304. tail = e;
  46305. }
  46306. p = q;
  46307. }
  46308. tail.nextZ = null;
  46309. inSize *= 2;
  46310. } while (numMerges > 1);
  46311. return list;
  46312. }
  46313. // z-order of a point given coords and size of the data bounding box
  46314. function zOrder(x, y, minX, minY, size) {
  46315. // coords are transformed into non-negative 15-bit integer range
  46316. x = 32767 * (x - minX) / size;
  46317. y = 32767 * (y - minY) / size;
  46318. x = (x | (x << 8)) & 0x00FF00FF;
  46319. x = (x | (x << 4)) & 0x0F0F0F0F;
  46320. x = (x | (x << 2)) & 0x33333333;
  46321. x = (x | (x << 1)) & 0x55555555;
  46322. y = (y | (y << 8)) & 0x00FF00FF;
  46323. y = (y | (y << 4)) & 0x0F0F0F0F;
  46324. y = (y | (y << 2)) & 0x33333333;
  46325. y = (y | (y << 1)) & 0x55555555;
  46326. return x | (y << 1);
  46327. }
  46328. // find the leftmost node of a polygon ring
  46329. function getLeftmost(start) {
  46330. var p = start, leftmost = start;
  46331. do {
  46332. if (p.x < leftmost.x)
  46333. leftmost = p;
  46334. p = p.next;
  46335. } while (p !== start);
  46336. return leftmost;
  46337. }
  46338. // check if a point lies within a convex triangle
  46339. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  46340. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  46341. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  46342. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  46343. }
  46344. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  46345. function isValidDiagonal(a, b) {
  46346. return a.next.i !== b.i &&
  46347. a.prev.i !== b.i &&
  46348. !intersectsPolygon(a, b) &&
  46349. locallyInside(a, b) &&
  46350. locallyInside(b, a) &&
  46351. middleInside(a, b);
  46352. }
  46353. // signed area of a triangle
  46354. function area(p, q, r) {
  46355. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  46356. }
  46357. // check if two points are equal
  46358. function equals(p1, p2) {
  46359. return p1.x === p2.x && p1.y === p2.y;
  46360. }
  46361. // check if two segments intersect
  46362. function intersects(p1, q1, p2, q2) {
  46363. if ((equals(p1, q1) && equals(p2, q2)) ||
  46364. (equals(p1, q2) && equals(p2, q1)))
  46365. return true;
  46366. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  46367. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  46368. }
  46369. // check if a polygon diagonal intersects any polygon segments
  46370. function intersectsPolygon(a, b) {
  46371. var p = a;
  46372. do {
  46373. if (p.i !== a.i &&
  46374. p.next.i !== a.i &&
  46375. p.i !== b.i &&
  46376. p.next.i !== b.i &&
  46377. intersects(p, p.next, a, b))
  46378. return true;
  46379. p = p.next;
  46380. } while (p !== a);
  46381. return false;
  46382. }
  46383. // check if a polygon diagonal is locally inside the polygon
  46384. function locallyInside(a, b) {
  46385. return area(a.prev, a, a.next) < 0
  46386. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  46387. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  46388. }
  46389. // check if the middle point of a polygon diagonal is inside the polygon
  46390. function middleInside(a, b) {
  46391. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  46392. do {
  46393. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  46394. inside = !inside;
  46395. p = p.next;
  46396. } while (p !== a);
  46397. return inside;
  46398. }
  46399. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  46400. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  46401. function splitPolygon(a, b) {
  46402. 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;
  46403. a.next = b;
  46404. b.prev = a;
  46405. a2.next = an;
  46406. an.prev = a2;
  46407. b2.next = a2;
  46408. a2.prev = b2;
  46409. bp.next = b2;
  46410. b2.prev = bp;
  46411. return b2;
  46412. }
  46413. // create a node and optionally link it with previous one (in a circular doubly linked list)
  46414. function insertNode(i, x, y, last) {
  46415. var p = new Node(i, x, y);
  46416. if (!last) {
  46417. p.prev = p;
  46418. p.next = p;
  46419. }
  46420. else {
  46421. p.next = last.next;
  46422. p.prev = last;
  46423. last.next.prev = p;
  46424. last.next = p;
  46425. }
  46426. return p;
  46427. }
  46428. function removeNode(p) {
  46429. p.next.prev = p.prev;
  46430. p.prev.next = p.next;
  46431. if (p.prevZ)
  46432. p.prevZ.nextZ = p.nextZ;
  46433. if (p.nextZ)
  46434. p.nextZ.prevZ = p.prevZ;
  46435. }
  46436. function Node(i, x, y) {
  46437. // vertice index in coordinates array
  46438. this.i = i;
  46439. // vertex coordinates
  46440. this.x = x;
  46441. this.y = y;
  46442. // previous and next vertice nodes in a polygon ring
  46443. this.prev = null;
  46444. this.next = null;
  46445. // z-order curve value
  46446. this.z = null;
  46447. // previous and next nodes in z-order
  46448. this.prevZ = null;
  46449. this.nextZ = null;
  46450. // indicates whether this is a steiner point
  46451. this.steiner = false;
  46452. }
  46453. /**
  46454. * return a percentage difference between the polygon area and its triangulation area;
  46455. * used to verify correctness of triangulation
  46456. */
  46457. function deviation(data, holeIndices, dim, triangles) {
  46458. var hasHoles = holeIndices && holeIndices.length;
  46459. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  46460. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  46461. if (hasHoles) {
  46462. for (var i = 0, len = holeIndices.length; i < len; i++) {
  46463. var start = holeIndices[i] * dim;
  46464. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46465. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  46466. }
  46467. }
  46468. var trianglesArea = 0;
  46469. for (i = 0; i < triangles.length; i += 3) {
  46470. var a = triangles[i] * dim;
  46471. var b = triangles[i + 1] * dim;
  46472. var c = triangles[i + 2] * dim;
  46473. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  46474. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  46475. }
  46476. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  46477. }
  46478. Earcut.deviation = deviation;
  46479. ;
  46480. function signedArea(data, start, end, dim) {
  46481. var sum = 0;
  46482. for (var i = start, j = end - dim; i < end; i += dim) {
  46483. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  46484. j = i;
  46485. }
  46486. return sum;
  46487. }
  46488. /**
  46489. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  46490. */
  46491. function flatten(data) {
  46492. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  46493. for (var i = 0; i < data.length; i++) {
  46494. for (var j = 0; j < data[i].length; j++) {
  46495. for (var d = 0; d < dim; d++)
  46496. result.vertices.push(data[i][j][d]);
  46497. }
  46498. if (i > 0) {
  46499. holeIndex += data[i - 1].length;
  46500. result.holes.push(holeIndex);
  46501. }
  46502. }
  46503. return result;
  46504. }
  46505. Earcut.flatten = flatten;
  46506. ;
  46507. })(Earcut || (Earcut = {}));
  46508. //# sourceMappingURL=babylon.earcut.js.map
  46509. var BABYLON;
  46510. (function (BABYLON) {
  46511. // Unique ID when we import meshes from Babylon to CSG
  46512. var currentCSGMeshId = 0;
  46513. // # class Vertex
  46514. // Represents a vertex of a polygon. Use your own vertex class instead of this
  46515. // one to provide additional features like texture coordinates and vertex
  46516. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  46517. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  46518. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  46519. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  46520. // is not used anywhere else.
  46521. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  46522. var Vertex = (function () {
  46523. function Vertex(pos, normal, uv) {
  46524. this.pos = pos;
  46525. this.normal = normal;
  46526. this.uv = uv;
  46527. }
  46528. Vertex.prototype.clone = function () {
  46529. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  46530. };
  46531. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  46532. // orientation of a polygon is flipped.
  46533. Vertex.prototype.flip = function () {
  46534. this.normal = this.normal.scale(-1);
  46535. };
  46536. // Create a new vertex between this vertex and `other` by linearly
  46537. // interpolating all properties using a parameter of `t`. Subclasses should
  46538. // override this to interpolate additional properties.
  46539. Vertex.prototype.interpolate = function (other, t) {
  46540. 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));
  46541. };
  46542. return Vertex;
  46543. }());
  46544. // # class Plane
  46545. // Represents a plane in 3D space.
  46546. var Plane = (function () {
  46547. function Plane(normal, w) {
  46548. this.normal = normal;
  46549. this.w = w;
  46550. }
  46551. Plane.FromPoints = function (a, b, c) {
  46552. var v0 = c.subtract(a);
  46553. var v1 = b.subtract(a);
  46554. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  46555. return null;
  46556. }
  46557. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  46558. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  46559. };
  46560. Plane.prototype.clone = function () {
  46561. return new Plane(this.normal.clone(), this.w);
  46562. };
  46563. Plane.prototype.flip = function () {
  46564. this.normal.scaleInPlace(-1);
  46565. this.w = -this.w;
  46566. };
  46567. // Split `polygon` by this plane if needed, then put the polygon or polygon
  46568. // fragments in the appropriate lists. Coplanar polygons go into either
  46569. // `coplanarFront` or `coplanarBack` depending on their orientation with
  46570. // respect to this plane. Polygons in front or in back of this plane go into
  46571. // either `front` or `back`.
  46572. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  46573. var COPLANAR = 0;
  46574. var FRONT = 1;
  46575. var BACK = 2;
  46576. var SPANNING = 3;
  46577. // Classify each point as well as the entire polygon into one of the above
  46578. // four classes.
  46579. var polygonType = 0;
  46580. var types = [];
  46581. var i;
  46582. var t;
  46583. for (i = 0; i < polygon.vertices.length; i++) {
  46584. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  46585. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  46586. polygonType |= type;
  46587. types.push(type);
  46588. }
  46589. // Put the polygon in the correct list, splitting it when necessary.
  46590. switch (polygonType) {
  46591. case COPLANAR:
  46592. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  46593. break;
  46594. case FRONT:
  46595. front.push(polygon);
  46596. break;
  46597. case BACK:
  46598. back.push(polygon);
  46599. break;
  46600. case SPANNING:
  46601. var f = [], b = [];
  46602. for (i = 0; i < polygon.vertices.length; i++) {
  46603. var j = (i + 1) % polygon.vertices.length;
  46604. var ti = types[i], tj = types[j];
  46605. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  46606. if (ti !== BACK)
  46607. f.push(vi);
  46608. if (ti !== FRONT)
  46609. b.push(ti !== BACK ? vi.clone() : vi);
  46610. if ((ti | tj) === SPANNING) {
  46611. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  46612. var v = vi.interpolate(vj, t);
  46613. f.push(v);
  46614. b.push(v.clone());
  46615. }
  46616. }
  46617. var poly;
  46618. if (f.length >= 3) {
  46619. poly = new Polygon(f, polygon.shared);
  46620. if (poly.plane)
  46621. front.push(poly);
  46622. }
  46623. if (b.length >= 3) {
  46624. poly = new Polygon(b, polygon.shared);
  46625. if (poly.plane)
  46626. back.push(poly);
  46627. }
  46628. break;
  46629. }
  46630. };
  46631. return Plane;
  46632. }());
  46633. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  46634. // point is on the plane.
  46635. Plane.EPSILON = 1e-5;
  46636. // # class Polygon
  46637. // Represents a convex polygon. The vertices used to initialize a polygon must
  46638. // be coplanar and form a convex loop.
  46639. //
  46640. // Each convex polygon has a `shared` property, which is shared between all
  46641. // polygons that are clones of each other or were split from the same polygon.
  46642. // This can be used to define per-polygon properties (such as surface color).
  46643. var Polygon = (function () {
  46644. function Polygon(vertices, shared) {
  46645. this.vertices = vertices;
  46646. this.shared = shared;
  46647. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  46648. }
  46649. Polygon.prototype.clone = function () {
  46650. var vertices = this.vertices.map(function (v) { return v.clone(); });
  46651. return new Polygon(vertices, this.shared);
  46652. };
  46653. Polygon.prototype.flip = function () {
  46654. this.vertices.reverse().map(function (v) { v.flip(); });
  46655. this.plane.flip();
  46656. };
  46657. return Polygon;
  46658. }());
  46659. // # class Node
  46660. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  46661. // by picking a polygon to split along. That polygon (and all other coplanar
  46662. // polygons) are added directly to that node and the other polygons are added to
  46663. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  46664. // no distinction between internal and leaf nodes.
  46665. var Node = (function () {
  46666. function Node(polygons) {
  46667. this.plane = null;
  46668. this.front = null;
  46669. this.back = null;
  46670. this.polygons = [];
  46671. if (polygons) {
  46672. this.build(polygons);
  46673. }
  46674. }
  46675. Node.prototype.clone = function () {
  46676. var node = new Node();
  46677. node.plane = this.plane && this.plane.clone();
  46678. node.front = this.front && this.front.clone();
  46679. node.back = this.back && this.back.clone();
  46680. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  46681. return node;
  46682. };
  46683. // Convert solid space to empty space and empty space to solid space.
  46684. Node.prototype.invert = function () {
  46685. for (var i = 0; i < this.polygons.length; i++) {
  46686. this.polygons[i].flip();
  46687. }
  46688. if (this.plane) {
  46689. this.plane.flip();
  46690. }
  46691. if (this.front) {
  46692. this.front.invert();
  46693. }
  46694. if (this.back) {
  46695. this.back.invert();
  46696. }
  46697. var temp = this.front;
  46698. this.front = this.back;
  46699. this.back = temp;
  46700. };
  46701. // Recursively remove all polygons in `polygons` that are inside this BSP
  46702. // tree.
  46703. Node.prototype.clipPolygons = function (polygons) {
  46704. if (!this.plane)
  46705. return polygons.slice();
  46706. var front = [], back = [];
  46707. for (var i = 0; i < polygons.length; i++) {
  46708. this.plane.splitPolygon(polygons[i], front, back, front, back);
  46709. }
  46710. if (this.front) {
  46711. front = this.front.clipPolygons(front);
  46712. }
  46713. if (this.back) {
  46714. back = this.back.clipPolygons(back);
  46715. }
  46716. else {
  46717. back = [];
  46718. }
  46719. return front.concat(back);
  46720. };
  46721. // Remove all polygons in this BSP tree that are inside the other BSP tree
  46722. // `bsp`.
  46723. Node.prototype.clipTo = function (bsp) {
  46724. this.polygons = bsp.clipPolygons(this.polygons);
  46725. if (this.front)
  46726. this.front.clipTo(bsp);
  46727. if (this.back)
  46728. this.back.clipTo(bsp);
  46729. };
  46730. // Return a list of all polygons in this BSP tree.
  46731. Node.prototype.allPolygons = function () {
  46732. var polygons = this.polygons.slice();
  46733. if (this.front)
  46734. polygons = polygons.concat(this.front.allPolygons());
  46735. if (this.back)
  46736. polygons = polygons.concat(this.back.allPolygons());
  46737. return polygons;
  46738. };
  46739. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  46740. // new polygons are filtered down to the bottom of the tree and become new
  46741. // nodes there. Each set of polygons is partitioned using the first polygon
  46742. // (no heuristic is used to pick a good split).
  46743. Node.prototype.build = function (polygons) {
  46744. if (!polygons.length)
  46745. return;
  46746. if (!this.plane)
  46747. this.plane = polygons[0].plane.clone();
  46748. var front = [], back = [];
  46749. for (var i = 0; i < polygons.length; i++) {
  46750. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  46751. }
  46752. if (front.length) {
  46753. if (!this.front)
  46754. this.front = new Node();
  46755. this.front.build(front);
  46756. }
  46757. if (back.length) {
  46758. if (!this.back)
  46759. this.back = new Node();
  46760. this.back.build(back);
  46761. }
  46762. };
  46763. return Node;
  46764. }());
  46765. var CSG = (function () {
  46766. function CSG() {
  46767. this.polygons = new Array();
  46768. }
  46769. // Convert BABYLON.Mesh to BABYLON.CSG
  46770. CSG.FromMesh = function (mesh) {
  46771. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  46772. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  46773. if (mesh instanceof BABYLON.Mesh) {
  46774. mesh.computeWorldMatrix(true);
  46775. matrix = mesh.getWorldMatrix();
  46776. meshPosition = mesh.position.clone();
  46777. meshRotation = mesh.rotation.clone();
  46778. if (mesh.rotationQuaternion) {
  46779. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  46780. }
  46781. meshScaling = mesh.scaling.clone();
  46782. }
  46783. else {
  46784. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  46785. }
  46786. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46787. var subMeshes = mesh.subMeshes;
  46788. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  46789. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  46790. vertices = [];
  46791. for (var j = 0; j < 3; j++) {
  46792. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  46793. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  46794. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  46795. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  46796. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  46797. vertex = new Vertex(position, normal, uv);
  46798. vertices.push(vertex);
  46799. }
  46800. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  46801. // To handle the case of degenerated triangle
  46802. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  46803. if (polygon.plane)
  46804. polygons.push(polygon);
  46805. }
  46806. }
  46807. var csg = CSG.FromPolygons(polygons);
  46808. csg.matrix = matrix;
  46809. csg.position = meshPosition;
  46810. csg.rotation = meshRotation;
  46811. csg.scaling = meshScaling;
  46812. csg.rotationQuaternion = meshRotationQuaternion;
  46813. currentCSGMeshId++;
  46814. return csg;
  46815. };
  46816. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  46817. CSG.FromPolygons = function (polygons) {
  46818. var csg = new CSG();
  46819. csg.polygons = polygons;
  46820. return csg;
  46821. };
  46822. CSG.prototype.clone = function () {
  46823. var csg = new CSG();
  46824. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  46825. csg.copyTransformAttributes(this);
  46826. return csg;
  46827. };
  46828. CSG.prototype.toPolygons = function () {
  46829. return this.polygons;
  46830. };
  46831. CSG.prototype.union = function (csg) {
  46832. var a = new Node(this.clone().polygons);
  46833. var b = new Node(csg.clone().polygons);
  46834. a.clipTo(b);
  46835. b.clipTo(a);
  46836. b.invert();
  46837. b.clipTo(a);
  46838. b.invert();
  46839. a.build(b.allPolygons());
  46840. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46841. };
  46842. CSG.prototype.unionInPlace = function (csg) {
  46843. var a = new Node(this.polygons);
  46844. var b = new Node(csg.polygons);
  46845. a.clipTo(b);
  46846. b.clipTo(a);
  46847. b.invert();
  46848. b.clipTo(a);
  46849. b.invert();
  46850. a.build(b.allPolygons());
  46851. this.polygons = a.allPolygons();
  46852. };
  46853. CSG.prototype.subtract = function (csg) {
  46854. var a = new Node(this.clone().polygons);
  46855. var b = new Node(csg.clone().polygons);
  46856. a.invert();
  46857. a.clipTo(b);
  46858. b.clipTo(a);
  46859. b.invert();
  46860. b.clipTo(a);
  46861. b.invert();
  46862. a.build(b.allPolygons());
  46863. a.invert();
  46864. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46865. };
  46866. CSG.prototype.subtractInPlace = function (csg) {
  46867. var a = new Node(this.polygons);
  46868. var b = new Node(csg.polygons);
  46869. a.invert();
  46870. a.clipTo(b);
  46871. b.clipTo(a);
  46872. b.invert();
  46873. b.clipTo(a);
  46874. b.invert();
  46875. a.build(b.allPolygons());
  46876. a.invert();
  46877. this.polygons = a.allPolygons();
  46878. };
  46879. CSG.prototype.intersect = function (csg) {
  46880. var a = new Node(this.clone().polygons);
  46881. var b = new Node(csg.clone().polygons);
  46882. a.invert();
  46883. b.clipTo(a);
  46884. b.invert();
  46885. a.clipTo(b);
  46886. b.clipTo(a);
  46887. a.build(b.allPolygons());
  46888. a.invert();
  46889. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46890. };
  46891. CSG.prototype.intersectInPlace = function (csg) {
  46892. var a = new Node(this.polygons);
  46893. var b = new Node(csg.polygons);
  46894. a.invert();
  46895. b.clipTo(a);
  46896. b.invert();
  46897. a.clipTo(b);
  46898. b.clipTo(a);
  46899. a.build(b.allPolygons());
  46900. a.invert();
  46901. this.polygons = a.allPolygons();
  46902. };
  46903. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  46904. // not modified.
  46905. CSG.prototype.inverse = function () {
  46906. var csg = this.clone();
  46907. csg.inverseInPlace();
  46908. return csg;
  46909. };
  46910. CSG.prototype.inverseInPlace = function () {
  46911. this.polygons.map(function (p) { p.flip(); });
  46912. };
  46913. // This is used to keep meshes transformations so they can be restored
  46914. // when we build back a Babylon Mesh
  46915. // NB : All CSG operations are performed in world coordinates
  46916. CSG.prototype.copyTransformAttributes = function (csg) {
  46917. this.matrix = csg.matrix;
  46918. this.position = csg.position;
  46919. this.rotation = csg.rotation;
  46920. this.scaling = csg.scaling;
  46921. this.rotationQuaternion = csg.rotationQuaternion;
  46922. return this;
  46923. };
  46924. // Build Raw mesh from CSG
  46925. // Coordinates here are in world space
  46926. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  46927. var matrix = this.matrix.clone();
  46928. matrix.invert();
  46929. 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;
  46930. if (keepSubMeshes) {
  46931. // Sort Polygons, since subMeshes are indices range
  46932. polygons.sort(function (a, b) {
  46933. if (a.shared.meshId === b.shared.meshId) {
  46934. return a.shared.subMeshId - b.shared.subMeshId;
  46935. }
  46936. else {
  46937. return a.shared.meshId - b.shared.meshId;
  46938. }
  46939. });
  46940. }
  46941. for (var i = 0, il = polygons.length; i < il; i++) {
  46942. polygon = polygons[i];
  46943. // Building SubMeshes
  46944. if (!subMesh_dict[polygon.shared.meshId]) {
  46945. subMesh_dict[polygon.shared.meshId] = {};
  46946. }
  46947. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  46948. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  46949. indexStart: +Infinity,
  46950. indexEnd: -Infinity,
  46951. materialIndex: polygon.shared.materialIndex
  46952. };
  46953. }
  46954. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  46955. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  46956. polygonIndices[0] = 0;
  46957. polygonIndices[1] = j - 1;
  46958. polygonIndices[2] = j;
  46959. for (var k = 0; k < 3; k++) {
  46960. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  46961. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  46962. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  46963. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  46964. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  46965. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  46966. // Check if 2 points can be merged
  46967. if (!(typeof vertex_idx !== 'undefined' &&
  46968. normals[vertex_idx * 3] === localNormal.x &&
  46969. normals[vertex_idx * 3 + 1] === localNormal.y &&
  46970. normals[vertex_idx * 3 + 2] === localNormal.z &&
  46971. uvs[vertex_idx * 2] === uv.x &&
  46972. uvs[vertex_idx * 2 + 1] === uv.y)) {
  46973. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  46974. uvs.push(uv.x, uv.y);
  46975. normals.push(normal.x, normal.y, normal.z);
  46976. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  46977. }
  46978. indices.push(vertex_idx);
  46979. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  46980. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  46981. currentIndex++;
  46982. }
  46983. }
  46984. }
  46985. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  46986. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  46987. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  46988. mesh.setIndices(indices);
  46989. if (keepSubMeshes) {
  46990. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  46991. var materialIndexOffset = 0, materialMaxIndex;
  46992. mesh.subMeshes = new Array();
  46993. for (var m in subMesh_dict) {
  46994. materialMaxIndex = -1;
  46995. for (var sm in subMesh_dict[m]) {
  46996. subMesh_obj = subMesh_dict[m][sm];
  46997. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  46998. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  46999. }
  47000. materialIndexOffset += ++materialMaxIndex;
  47001. }
  47002. }
  47003. return mesh;
  47004. };
  47005. // Build Mesh from CSG taking material and transforms into account
  47006. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  47007. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  47008. mesh.material = material;
  47009. mesh.position.copyFrom(this.position);
  47010. mesh.rotation.copyFrom(this.rotation);
  47011. if (this.rotationQuaternion) {
  47012. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  47013. }
  47014. mesh.scaling.copyFrom(this.scaling);
  47015. mesh.computeWorldMatrix(true);
  47016. return mesh;
  47017. };
  47018. return CSG;
  47019. }());
  47020. BABYLON.CSG = CSG;
  47021. })(BABYLON || (BABYLON = {}));
  47022. //# sourceMappingURL=babylon.csg.js.map
  47023. var BABYLON;
  47024. (function (BABYLON) {
  47025. var VRDistortionCorrectionPostProcess = (function (_super) {
  47026. __extends(VRDistortionCorrectionPostProcess, _super);
  47027. //ANY
  47028. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  47029. var _this = _super.call(this, name, "vrDistortionCorrection", [
  47030. 'LensCenter',
  47031. 'Scale',
  47032. 'ScaleIn',
  47033. 'HmdWarpParam'
  47034. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  47035. _this._isRightEye = isRightEye;
  47036. _this._distortionFactors = vrMetrics.distortionK;
  47037. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  47038. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  47039. _this.onSizeChangedObservable.add(function () {
  47040. _this.aspectRatio = _this.width * .5 / _this.height;
  47041. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  47042. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  47043. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  47044. });
  47045. _this.onApplyObservable.add(function (effect) {
  47046. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  47047. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  47048. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  47049. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  47050. });
  47051. return _this;
  47052. }
  47053. return VRDistortionCorrectionPostProcess;
  47054. }(BABYLON.PostProcess));
  47055. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  47056. })(BABYLON || (BABYLON = {}));
  47057. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  47058. // Mainly based on these 2 articles :
  47059. // 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
  47060. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  47061. var BABYLON;
  47062. (function (BABYLON) {
  47063. var JoystickAxis;
  47064. (function (JoystickAxis) {
  47065. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  47066. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  47067. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  47068. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  47069. var VirtualJoystick = (function () {
  47070. function VirtualJoystick(leftJoystick) {
  47071. var _this = this;
  47072. if (leftJoystick) {
  47073. this._leftJoystick = true;
  47074. }
  47075. else {
  47076. this._leftJoystick = false;
  47077. }
  47078. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  47079. VirtualJoystick._globalJoystickIndex++;
  47080. // By default left & right arrow keys are moving the X
  47081. // and up & down keys are moving the Y
  47082. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47083. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47084. this.reverseLeftRight = false;
  47085. this.reverseUpDown = false;
  47086. // collections of pointers
  47087. this._touches = new BABYLON.StringDictionary();
  47088. this.deltaPosition = BABYLON.Vector3.Zero();
  47089. this._joystickSensibility = 25;
  47090. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47091. this._rotationSpeed = 25;
  47092. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  47093. this._rotateOnAxisRelativeToMesh = false;
  47094. this._onResize = function (evt) {
  47095. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47096. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47097. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  47098. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  47099. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  47100. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  47101. };
  47102. // injecting a canvas element on top of the canvas 3D game
  47103. if (!VirtualJoystick.vjCanvas) {
  47104. window.addEventListener("resize", this._onResize, false);
  47105. VirtualJoystick.vjCanvas = document.createElement("canvas");
  47106. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47107. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47108. VirtualJoystick.vjCanvas.width = window.innerWidth;
  47109. VirtualJoystick.vjCanvas.height = window.innerHeight;
  47110. VirtualJoystick.vjCanvas.style.width = "100%";
  47111. VirtualJoystick.vjCanvas.style.height = "100%";
  47112. VirtualJoystick.vjCanvas.style.position = "absolute";
  47113. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  47114. VirtualJoystick.vjCanvas.style.top = "0px";
  47115. VirtualJoystick.vjCanvas.style.left = "0px";
  47116. VirtualJoystick.vjCanvas.style.zIndex = "5";
  47117. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  47118. // Support for jQuery PEP polyfill
  47119. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  47120. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  47121. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  47122. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47123. document.body.appendChild(VirtualJoystick.vjCanvas);
  47124. }
  47125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  47126. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  47127. this.pressed = false;
  47128. // default joystick color
  47129. this._joystickColor = "cyan";
  47130. this._joystickPointerID = -1;
  47131. // current joystick position
  47132. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  47133. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  47134. // origin joystick position
  47135. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  47136. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  47137. this._onPointerDownHandlerRef = function (evt) {
  47138. _this._onPointerDown(evt);
  47139. };
  47140. this._onPointerMoveHandlerRef = function (evt) {
  47141. _this._onPointerMove(evt);
  47142. };
  47143. this._onPointerOutHandlerRef = function (evt) {
  47144. _this._onPointerUp(evt);
  47145. };
  47146. this._onPointerUpHandlerRef = function (evt) {
  47147. _this._onPointerUp(evt);
  47148. };
  47149. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  47150. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  47151. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  47152. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  47153. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  47154. evt.preventDefault(); // Disables system menu
  47155. }, false);
  47156. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47157. }
  47158. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  47159. this._joystickSensibility = newJoystickSensibility;
  47160. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47161. };
  47162. VirtualJoystick.prototype._onPointerDown = function (e) {
  47163. var positionOnScreenCondition;
  47164. e.preventDefault();
  47165. if (this._leftJoystick === true) {
  47166. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  47167. }
  47168. else {
  47169. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  47170. }
  47171. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  47172. // First contact will be dedicated to the virtual joystick
  47173. this._joystickPointerID = e.pointerId;
  47174. this._joystickPointerStartPos.x = e.clientX;
  47175. this._joystickPointerStartPos.y = e.clientY;
  47176. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  47177. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  47178. this._deltaJoystickVector.x = 0;
  47179. this._deltaJoystickVector.y = 0;
  47180. this.pressed = true;
  47181. this._touches.add(e.pointerId.toString(), e);
  47182. }
  47183. else {
  47184. // You can only trigger the action buttons with a joystick declared
  47185. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  47186. this._action();
  47187. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  47188. }
  47189. }
  47190. };
  47191. VirtualJoystick.prototype._onPointerMove = function (e) {
  47192. // If the current pointer is the one associated to the joystick (first touch contact)
  47193. if (this._joystickPointerID == e.pointerId) {
  47194. this._joystickPointerPos.x = e.clientX;
  47195. this._joystickPointerPos.y = e.clientY;
  47196. this._deltaJoystickVector = this._joystickPointerPos.clone();
  47197. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  47198. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  47199. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  47200. switch (this._axisTargetedByLeftAndRight) {
  47201. case JoystickAxis.X:
  47202. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  47203. break;
  47204. case JoystickAxis.Y:
  47205. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  47206. break;
  47207. case JoystickAxis.Z:
  47208. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  47209. break;
  47210. }
  47211. var directionUpDown = this.reverseUpDown ? 1 : -1;
  47212. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  47213. switch (this._axisTargetedByUpAndDown) {
  47214. case JoystickAxis.X:
  47215. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  47216. break;
  47217. case JoystickAxis.Y:
  47218. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  47219. break;
  47220. case JoystickAxis.Z:
  47221. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  47222. break;
  47223. }
  47224. }
  47225. else {
  47226. var data = this._touches.get(e.pointerId.toString());
  47227. if (data) {
  47228. data.x = e.clientX;
  47229. data.y = e.clientY;
  47230. }
  47231. }
  47232. };
  47233. VirtualJoystick.prototype._onPointerUp = function (e) {
  47234. if (this._joystickPointerID == e.pointerId) {
  47235. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  47236. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  47237. this._joystickPointerID = -1;
  47238. this.pressed = false;
  47239. }
  47240. else {
  47241. var touch = this._touches.get(e.pointerId.toString());
  47242. if (touch) {
  47243. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47244. }
  47245. }
  47246. this._deltaJoystickVector.x = 0;
  47247. this._deltaJoystickVector.y = 0;
  47248. this._touches.remove(e.pointerId.toString());
  47249. };
  47250. /**
  47251. * Change the color of the virtual joystick
  47252. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  47253. */
  47254. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  47255. this._joystickColor = newColor;
  47256. };
  47257. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  47258. this._action = action;
  47259. };
  47260. // Define which axis you'd like to control for left & right
  47261. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  47262. switch (axis) {
  47263. case JoystickAxis.X:
  47264. case JoystickAxis.Y:
  47265. case JoystickAxis.Z:
  47266. this._axisTargetedByLeftAndRight = axis;
  47267. break;
  47268. default:
  47269. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47270. break;
  47271. }
  47272. };
  47273. // Define which axis you'd like to control for up & down
  47274. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  47275. switch (axis) {
  47276. case JoystickAxis.X:
  47277. case JoystickAxis.Y:
  47278. case JoystickAxis.Z:
  47279. this._axisTargetedByUpAndDown = axis;
  47280. break;
  47281. default:
  47282. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47283. break;
  47284. }
  47285. };
  47286. VirtualJoystick.prototype._clearCanvas = function () {
  47287. if (this._leftJoystick) {
  47288. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  47289. }
  47290. else {
  47291. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  47292. }
  47293. };
  47294. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  47295. var _this = this;
  47296. if (this.pressed) {
  47297. this._touches.forEach(function (key, touch) {
  47298. if (touch.pointerId === _this._joystickPointerID) {
  47299. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  47300. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  47301. VirtualJoystick.vjCanvasContext.beginPath();
  47302. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47303. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47304. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  47305. VirtualJoystick.vjCanvasContext.stroke();
  47306. VirtualJoystick.vjCanvasContext.closePath();
  47307. VirtualJoystick.vjCanvasContext.beginPath();
  47308. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47309. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47310. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  47311. VirtualJoystick.vjCanvasContext.stroke();
  47312. VirtualJoystick.vjCanvasContext.closePath();
  47313. VirtualJoystick.vjCanvasContext.beginPath();
  47314. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47315. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  47316. VirtualJoystick.vjCanvasContext.stroke();
  47317. VirtualJoystick.vjCanvasContext.closePath();
  47318. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  47319. }
  47320. else {
  47321. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47322. VirtualJoystick.vjCanvasContext.beginPath();
  47323. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  47324. VirtualJoystick.vjCanvasContext.beginPath();
  47325. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  47326. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47327. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  47328. VirtualJoystick.vjCanvasContext.stroke();
  47329. VirtualJoystick.vjCanvasContext.closePath();
  47330. touch.prevX = touch.x;
  47331. touch.prevY = touch.y;
  47332. }
  47333. ;
  47334. });
  47335. }
  47336. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47337. };
  47338. VirtualJoystick.prototype.releaseCanvas = function () {
  47339. if (VirtualJoystick.vjCanvas) {
  47340. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  47341. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  47342. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  47343. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  47344. window.removeEventListener("resize", this._onResize);
  47345. document.body.removeChild(VirtualJoystick.vjCanvas);
  47346. VirtualJoystick.vjCanvas = null;
  47347. }
  47348. };
  47349. return VirtualJoystick;
  47350. }());
  47351. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  47352. VirtualJoystick._globalJoystickIndex = 0;
  47353. BABYLON.VirtualJoystick = VirtualJoystick;
  47354. })(BABYLON || (BABYLON = {}));
  47355. //# sourceMappingURL=babylon.virtualJoystick.js.map
  47356. var BABYLON;
  47357. (function (BABYLON) {
  47358. // We're mainly based on the logic defined into the FreeCamera code
  47359. var VirtualJoysticksCamera = (function (_super) {
  47360. __extends(VirtualJoysticksCamera, _super);
  47361. function VirtualJoysticksCamera(name, position, scene) {
  47362. var _this = _super.call(this, name, position, scene) || this;
  47363. _this.inputs.addVirtualJoystick();
  47364. return _this;
  47365. }
  47366. VirtualJoysticksCamera.prototype.getClassName = function () {
  47367. return "VirtualJoysticksCamera";
  47368. };
  47369. return VirtualJoysticksCamera;
  47370. }(BABYLON.FreeCamera));
  47371. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  47372. })(BABYLON || (BABYLON = {}));
  47373. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  47374. var BABYLON;
  47375. (function (BABYLON) {
  47376. var FreeCameraVirtualJoystickInput = (function () {
  47377. function FreeCameraVirtualJoystickInput() {
  47378. }
  47379. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  47380. return this._leftjoystick;
  47381. };
  47382. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  47383. return this._rightjoystick;
  47384. };
  47385. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  47386. if (this._leftjoystick) {
  47387. var camera = this.camera;
  47388. var speed = camera._computeLocalCameraSpeed() * 50;
  47389. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  47390. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  47391. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  47392. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  47393. if (!this._leftjoystick.pressed) {
  47394. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  47395. }
  47396. if (!this._rightjoystick.pressed) {
  47397. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  47398. }
  47399. }
  47400. };
  47401. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  47402. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  47403. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  47404. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  47405. this._leftjoystick.setJoystickSensibility(0.15);
  47406. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  47407. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  47408. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  47409. this._rightjoystick.reverseUpDown = true;
  47410. this._rightjoystick.setJoystickSensibility(0.05);
  47411. this._rightjoystick.setJoystickColor("yellow");
  47412. };
  47413. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  47414. this._leftjoystick.releaseCanvas();
  47415. this._rightjoystick.releaseCanvas();
  47416. };
  47417. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  47418. return "FreeCameraVirtualJoystickInput";
  47419. };
  47420. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  47421. return "virtualJoystick";
  47422. };
  47423. return FreeCameraVirtualJoystickInput;
  47424. }());
  47425. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  47426. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  47427. })(BABYLON || (BABYLON = {}));
  47428. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  47429. var BABYLON;
  47430. (function (BABYLON) {
  47431. var AnaglyphPostProcess = (function (_super) {
  47432. __extends(AnaglyphPostProcess, _super);
  47433. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  47434. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  47435. _this._passedProcess = rigCameras[0]._rigPostProcess;
  47436. _this.onApplyObservable.add(function (effect) {
  47437. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  47438. });
  47439. return _this;
  47440. }
  47441. return AnaglyphPostProcess;
  47442. }(BABYLON.PostProcess));
  47443. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  47444. })(BABYLON || (BABYLON = {}));
  47445. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  47446. var BABYLON;
  47447. (function (BABYLON) {
  47448. var OutlineRenderer = (function () {
  47449. function OutlineRenderer(scene) {
  47450. this._scene = scene;
  47451. }
  47452. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  47453. var _this = this;
  47454. if (useOverlay === void 0) { useOverlay = false; }
  47455. var scene = this._scene;
  47456. var engine = this._scene.getEngine();
  47457. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47458. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  47459. return;
  47460. }
  47461. var mesh = subMesh.getRenderingMesh();
  47462. var material = subMesh.getMaterial();
  47463. engine.enableEffect(this._effect);
  47464. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  47465. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  47466. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47467. // Bones
  47468. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47469. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47470. }
  47471. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47472. // Alpha test
  47473. if (material && material.needAlphaTesting()) {
  47474. var alphaTexture = material.getAlphaTestTexture();
  47475. this._effect.setTexture("diffuseSampler", alphaTexture);
  47476. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47477. }
  47478. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  47479. };
  47480. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  47481. var defines = [];
  47482. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  47483. var mesh = subMesh.getMesh();
  47484. var material = subMesh.getMaterial();
  47485. // Alpha test
  47486. if (material && material.needAlphaTesting()) {
  47487. defines.push("#define ALPHATEST");
  47488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47489. attribs.push(BABYLON.VertexBuffer.UVKind);
  47490. defines.push("#define UV1");
  47491. }
  47492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47493. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47494. defines.push("#define UV2");
  47495. }
  47496. }
  47497. // Bones
  47498. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47499. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47500. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47501. if (mesh.numBoneInfluencers > 4) {
  47502. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47503. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47504. }
  47505. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47506. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47507. }
  47508. else {
  47509. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47510. }
  47511. // Instances
  47512. if (useInstances) {
  47513. defines.push("#define INSTANCES");
  47514. attribs.push("world0");
  47515. attribs.push("world1");
  47516. attribs.push("world2");
  47517. attribs.push("world3");
  47518. }
  47519. // Get correct effect
  47520. var join = defines.join("\n");
  47521. if (this._cachedDefines !== join) {
  47522. this._cachedDefines = join;
  47523. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  47524. }
  47525. return this._effect.isReady();
  47526. };
  47527. return OutlineRenderer;
  47528. }());
  47529. BABYLON.OutlineRenderer = OutlineRenderer;
  47530. })(BABYLON || (BABYLON = {}));
  47531. //# sourceMappingURL=babylon.outlineRenderer.js.map
  47532. var BABYLON;
  47533. (function (BABYLON) {
  47534. var MeshAssetTask = (function () {
  47535. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  47536. this.name = name;
  47537. this.meshesNames = meshesNames;
  47538. this.rootUrl = rootUrl;
  47539. this.sceneFilename = sceneFilename;
  47540. this.isCompleted = false;
  47541. }
  47542. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47543. var _this = this;
  47544. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  47545. _this.loadedMeshes = meshes;
  47546. _this.loadedParticleSystems = particleSystems;
  47547. _this.loadedSkeletons = skeletons;
  47548. _this.isCompleted = true;
  47549. if (_this.onSuccess) {
  47550. _this.onSuccess(_this);
  47551. }
  47552. onSuccess();
  47553. }, null, function () {
  47554. if (_this.onError) {
  47555. _this.onError(_this);
  47556. }
  47557. onError();
  47558. });
  47559. };
  47560. return MeshAssetTask;
  47561. }());
  47562. BABYLON.MeshAssetTask = MeshAssetTask;
  47563. var TextFileAssetTask = (function () {
  47564. function TextFileAssetTask(name, url) {
  47565. this.name = name;
  47566. this.url = url;
  47567. this.isCompleted = false;
  47568. }
  47569. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47570. var _this = this;
  47571. BABYLON.Tools.LoadFile(this.url, function (data) {
  47572. _this.text = data;
  47573. _this.isCompleted = true;
  47574. if (_this.onSuccess) {
  47575. _this.onSuccess(_this);
  47576. }
  47577. onSuccess();
  47578. }, null, scene.database, false, function () {
  47579. if (_this.onError) {
  47580. _this.onError(_this);
  47581. }
  47582. onError();
  47583. });
  47584. };
  47585. return TextFileAssetTask;
  47586. }());
  47587. BABYLON.TextFileAssetTask = TextFileAssetTask;
  47588. var BinaryFileAssetTask = (function () {
  47589. function BinaryFileAssetTask(name, url) {
  47590. this.name = name;
  47591. this.url = url;
  47592. this.isCompleted = false;
  47593. }
  47594. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47595. var _this = this;
  47596. BABYLON.Tools.LoadFile(this.url, function (data) {
  47597. _this.data = data;
  47598. _this.isCompleted = true;
  47599. if (_this.onSuccess) {
  47600. _this.onSuccess(_this);
  47601. }
  47602. onSuccess();
  47603. }, null, scene.database, true, function () {
  47604. if (_this.onError) {
  47605. _this.onError(_this);
  47606. }
  47607. onError();
  47608. });
  47609. };
  47610. return BinaryFileAssetTask;
  47611. }());
  47612. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  47613. var ImageAssetTask = (function () {
  47614. function ImageAssetTask(name, url) {
  47615. this.name = name;
  47616. this.url = url;
  47617. this.isCompleted = false;
  47618. }
  47619. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47620. var _this = this;
  47621. var img = new Image();
  47622. BABYLON.Tools.SetCorsBehavior(this.url, img);
  47623. img.onload = function () {
  47624. _this.image = img;
  47625. _this.isCompleted = true;
  47626. if (_this.onSuccess) {
  47627. _this.onSuccess(_this);
  47628. }
  47629. onSuccess();
  47630. };
  47631. img.onerror = function () {
  47632. if (_this.onError) {
  47633. _this.onError(_this);
  47634. }
  47635. onError();
  47636. };
  47637. img.src = this.url;
  47638. };
  47639. return ImageAssetTask;
  47640. }());
  47641. BABYLON.ImageAssetTask = ImageAssetTask;
  47642. var TextureAssetTask = (function () {
  47643. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  47644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47645. this.name = name;
  47646. this.url = url;
  47647. this.noMipmap = noMipmap;
  47648. this.invertY = invertY;
  47649. this.samplingMode = samplingMode;
  47650. this.isCompleted = false;
  47651. }
  47652. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47653. var _this = this;
  47654. var onload = function () {
  47655. _this.isCompleted = true;
  47656. if (_this.onSuccess) {
  47657. _this.onSuccess(_this);
  47658. }
  47659. onSuccess();
  47660. };
  47661. var onerror = function () {
  47662. if (_this.onError) {
  47663. _this.onError(_this);
  47664. }
  47665. onError();
  47666. };
  47667. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  47668. };
  47669. return TextureAssetTask;
  47670. }());
  47671. BABYLON.TextureAssetTask = TextureAssetTask;
  47672. var CubeTextureAssetTask = (function () {
  47673. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  47674. this.name = name;
  47675. this.url = url;
  47676. this.extensions = extensions;
  47677. this.noMipmap = noMipmap;
  47678. this.files = files;
  47679. this.isCompleted = false;
  47680. }
  47681. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47682. var _this = this;
  47683. var onload = function () {
  47684. _this.isCompleted = true;
  47685. if (_this.onSuccess) {
  47686. _this.onSuccess(_this);
  47687. }
  47688. onSuccess();
  47689. };
  47690. var onerror = function () {
  47691. if (_this.onError) {
  47692. _this.onError(_this);
  47693. }
  47694. onError();
  47695. };
  47696. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  47697. };
  47698. return CubeTextureAssetTask;
  47699. }());
  47700. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  47701. var HDRCubeTextureAssetTask = (function () {
  47702. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  47703. if (noMipmap === void 0) { noMipmap = false; }
  47704. if (generateHarmonics === void 0) { generateHarmonics = true; }
  47705. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  47706. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  47707. this.name = name;
  47708. this.url = url;
  47709. this.size = size;
  47710. this.noMipmap = noMipmap;
  47711. this.generateHarmonics = generateHarmonics;
  47712. this.useInGammaSpace = useInGammaSpace;
  47713. this.usePMREMGenerator = usePMREMGenerator;
  47714. this.isCompleted = false;
  47715. }
  47716. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47717. var _this = this;
  47718. var onload = function () {
  47719. _this.isCompleted = true;
  47720. if (_this.onSuccess) {
  47721. _this.onSuccess(_this);
  47722. }
  47723. onSuccess();
  47724. };
  47725. var onerror = function () {
  47726. if (_this.onError) {
  47727. _this.onError(_this);
  47728. }
  47729. onError();
  47730. };
  47731. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  47732. };
  47733. return HDRCubeTextureAssetTask;
  47734. }());
  47735. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  47736. var AssetsManager = (function () {
  47737. function AssetsManager(scene) {
  47738. this.tasks = new Array();
  47739. this.waitingTasksCount = 0;
  47740. this.useDefaultLoadingScreen = true;
  47741. this._scene = scene;
  47742. }
  47743. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  47744. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  47745. this.tasks.push(task);
  47746. return task;
  47747. };
  47748. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  47749. var task = new TextFileAssetTask(taskName, url);
  47750. this.tasks.push(task);
  47751. return task;
  47752. };
  47753. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  47754. var task = new BinaryFileAssetTask(taskName, url);
  47755. this.tasks.push(task);
  47756. return task;
  47757. };
  47758. AssetsManager.prototype.addImageTask = function (taskName, url) {
  47759. var task = new ImageAssetTask(taskName, url);
  47760. this.tasks.push(task);
  47761. return task;
  47762. };
  47763. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  47764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47765. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  47766. this.tasks.push(task);
  47767. return task;
  47768. };
  47769. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  47770. this.waitingTasksCount--;
  47771. if (this.waitingTasksCount === 0) {
  47772. if (this.onFinish) {
  47773. this.onFinish(this.tasks);
  47774. }
  47775. this._scene.getEngine().hideLoadingUI();
  47776. }
  47777. };
  47778. AssetsManager.prototype._runTask = function (task) {
  47779. var _this = this;
  47780. task.run(this._scene, function () {
  47781. if (_this.onTaskSuccess) {
  47782. _this.onTaskSuccess(task);
  47783. }
  47784. _this._decreaseWaitingTasksCount();
  47785. }, function () {
  47786. if (_this.onTaskError) {
  47787. _this.onTaskError(task);
  47788. }
  47789. _this._decreaseWaitingTasksCount();
  47790. });
  47791. };
  47792. AssetsManager.prototype.reset = function () {
  47793. this.tasks = new Array();
  47794. return this;
  47795. };
  47796. AssetsManager.prototype.load = function () {
  47797. this.waitingTasksCount = this.tasks.length;
  47798. if (this.waitingTasksCount === 0) {
  47799. if (this.onFinish) {
  47800. this.onFinish(this.tasks);
  47801. }
  47802. return this;
  47803. }
  47804. if (this.useDefaultLoadingScreen) {
  47805. this._scene.getEngine().displayLoadingUI();
  47806. }
  47807. for (var index = 0; index < this.tasks.length; index++) {
  47808. var task = this.tasks[index];
  47809. this._runTask(task);
  47810. }
  47811. return this;
  47812. };
  47813. return AssetsManager;
  47814. }());
  47815. BABYLON.AssetsManager = AssetsManager;
  47816. })(BABYLON || (BABYLON = {}));
  47817. //# sourceMappingURL=babylon.assetsManager.js.map
  47818. var BABYLON;
  47819. (function (BABYLON) {
  47820. var VRCameraMetrics = (function () {
  47821. function VRCameraMetrics() {
  47822. this.compensateDistortion = true;
  47823. }
  47824. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  47825. get: function () {
  47826. return this.hResolution / (2 * this.vResolution);
  47827. },
  47828. enumerable: true,
  47829. configurable: true
  47830. });
  47831. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  47832. get: function () {
  47833. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  47834. },
  47835. enumerable: true,
  47836. configurable: true
  47837. });
  47838. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  47839. get: function () {
  47840. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47841. var h = (4 * meters) / this.hScreenSize;
  47842. return BABYLON.Matrix.Translation(h, 0, 0);
  47843. },
  47844. enumerable: true,
  47845. configurable: true
  47846. });
  47847. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  47848. get: function () {
  47849. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47850. var h = (4 * meters) / this.hScreenSize;
  47851. return BABYLON.Matrix.Translation(-h, 0, 0);
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  47857. get: function () {
  47858. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  47864. get: function () {
  47865. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  47866. },
  47867. enumerable: true,
  47868. configurable: true
  47869. });
  47870. VRCameraMetrics.GetDefault = function () {
  47871. var result = new VRCameraMetrics();
  47872. result.hResolution = 1280;
  47873. result.vResolution = 800;
  47874. result.hScreenSize = 0.149759993;
  47875. result.vScreenSize = 0.0935999975;
  47876. result.vScreenCenter = 0.0467999987;
  47877. result.eyeToScreenDistance = 0.0410000011;
  47878. result.lensSeparationDistance = 0.0635000020;
  47879. result.interpupillaryDistance = 0.0640000030;
  47880. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  47881. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  47882. result.postProcessScaleFactor = 1.714605507808412;
  47883. result.lensCenterOffset = 0.151976421;
  47884. return result;
  47885. };
  47886. return VRCameraMetrics;
  47887. }());
  47888. BABYLON.VRCameraMetrics = VRCameraMetrics;
  47889. })(BABYLON || (BABYLON = {}));
  47890. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  47891. var BABYLON;
  47892. (function (BABYLON) {
  47893. var WebVRFreeCamera = (function (_super) {
  47894. __extends(WebVRFreeCamera, _super);
  47895. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  47896. if (compensateDistortion === void 0) { compensateDistortion = false; }
  47897. if (webVROptions === void 0) { webVROptions = {}; }
  47898. var _this = _super.call(this, name, position, scene) || this;
  47899. _this.webVROptions = webVROptions;
  47900. _this._vrDevice = null;
  47901. _this._cacheState = null;
  47902. _this._vrEnabled = false;
  47903. _this._attached = false;
  47904. //using the position provided as the current position offset
  47905. _this._positionOffset = position;
  47906. //enable VR
  47907. _this.getEngine().initWebVR();
  47908. if (!_this.getEngine().vrDisplaysPromise) {
  47909. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  47910. }
  47911. else {
  47912. //TODO get the metrics updated using the device's eye parameters!
  47913. //TODO also check that the device has the right capabilities!
  47914. _this._frameData = new VRFrameData();
  47915. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  47916. if (devices.length > 0) {
  47917. _this._vrEnabled = true;
  47918. if (_this.webVROptions.displayName) {
  47919. var found = devices.some(function (device) {
  47920. if (device.displayName === _this.webVROptions.displayName) {
  47921. _this._vrDevice = device;
  47922. return true;
  47923. }
  47924. else {
  47925. return false;
  47926. }
  47927. });
  47928. if (!found) {
  47929. _this._vrDevice = devices[0];
  47930. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  47931. }
  47932. }
  47933. else {
  47934. //choose the first one
  47935. _this._vrDevice = devices[0];
  47936. }
  47937. //reset the rig parameters.
  47938. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  47939. if (_this._attached) {
  47940. _this.getEngine().enableVR(_this._vrDevice);
  47941. }
  47942. }
  47943. else {
  47944. BABYLON.Tools.Error("No WebVR devices found!");
  47945. }
  47946. });
  47947. }
  47948. _this.rotationQuaternion = new BABYLON.Quaternion();
  47949. _this._quaternionCache = new BABYLON.Quaternion();
  47950. return _this;
  47951. }
  47952. WebVRFreeCamera.prototype._checkInputs = function () {
  47953. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  47954. var currentPost = this._frameData.pose;
  47955. //make sure we have data
  47956. if (currentPost && currentPost.orientation) {
  47957. this._cacheState = currentPost;
  47958. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  47959. if (this.webVROptions.trackPosition && this._cacheState.position) {
  47960. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  47961. //scale the position accordingly
  47962. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  47963. //add the position offset
  47964. this.position.addInPlace(this._positionOffset);
  47965. }
  47966. }
  47967. }
  47968. _super.prototype._checkInputs.call(this);
  47969. };
  47970. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47971. _super.prototype.attachControl.call(this, element, noPreventDefault);
  47972. this._attached = true;
  47973. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47974. if (this._vrEnabled) {
  47975. this.getEngine().enableVR(this._vrDevice);
  47976. }
  47977. };
  47978. WebVRFreeCamera.prototype.detachControl = function (element) {
  47979. _super.prototype.detachControl.call(this, element);
  47980. this._vrEnabled = false;
  47981. this._attached = false;
  47982. this.getEngine().disableVR();
  47983. };
  47984. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  47985. //Backwards comp.
  47986. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  47987. //this.getEngine().switchFullscreen(requestPointerlock);
  47988. };
  47989. WebVRFreeCamera.prototype.getClassName = function () {
  47990. return "WebVRFreeCamera";
  47991. };
  47992. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  47993. //uses the vrDisplay's "resetPose()".
  47994. //pitch and roll won't be affected.
  47995. this._vrDevice.resetPose();
  47996. };
  47997. /**
  47998. *
  47999. * Set the position offset of the VR camera
  48000. * The offset will be added to the WebVR pose, after scaling it (if set).
  48001. *
  48002. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  48003. *
  48004. * @memberOf WebVRFreeCamera
  48005. */
  48006. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  48007. if (newPosition) {
  48008. this._positionOffset = newPosition;
  48009. }
  48010. else {
  48011. this._positionOffset.copyFrom(this.position);
  48012. }
  48013. };
  48014. return WebVRFreeCamera;
  48015. }(BABYLON.FreeCamera));
  48016. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  48017. var WebVRGamepadCamera = (function (_super) {
  48018. __extends(WebVRGamepadCamera, _super);
  48019. function WebVRGamepadCamera(name, position, scene, compensateDistortion, webVROptions) {
  48020. if (compensateDistortion === void 0) { compensateDistortion = false; }
  48021. if (webVROptions === void 0) { webVROptions = {}; }
  48022. var _this = _super.call(this, name, position, scene, compensateDistortion, webVROptions) || this;
  48023. _this.inputs.addGamepad();
  48024. return _this;
  48025. }
  48026. WebVRGamepadCamera.prototype.getClassName = function () {
  48027. return "WebVRGamepadCamera";
  48028. };
  48029. return WebVRGamepadCamera;
  48030. }(WebVRFreeCamera));
  48031. BABYLON.WebVRGamepadCamera = WebVRGamepadCamera;
  48032. })(BABYLON || (BABYLON = {}));
  48033. //# sourceMappingURL=babylon.webVRCamera.js.map
  48034. var BABYLON;
  48035. (function (BABYLON) {
  48036. // Standard optimizations
  48037. var SceneOptimization = (function () {
  48038. function SceneOptimization(priority) {
  48039. if (priority === void 0) { priority = 0; }
  48040. this.priority = priority;
  48041. this.apply = function (scene) {
  48042. return true; // Return true if everything that can be done was applied
  48043. };
  48044. }
  48045. return SceneOptimization;
  48046. }());
  48047. BABYLON.SceneOptimization = SceneOptimization;
  48048. var TextureOptimization = (function (_super) {
  48049. __extends(TextureOptimization, _super);
  48050. function TextureOptimization(priority, maximumSize) {
  48051. if (priority === void 0) { priority = 0; }
  48052. if (maximumSize === void 0) { maximumSize = 1024; }
  48053. var _this = _super.call(this, priority) || this;
  48054. _this.priority = priority;
  48055. _this.maximumSize = maximumSize;
  48056. _this.apply = function (scene) {
  48057. var allDone = true;
  48058. for (var index = 0; index < scene.textures.length; index++) {
  48059. var texture = scene.textures[index];
  48060. if (!texture.canRescale) {
  48061. continue;
  48062. }
  48063. var currentSize = texture.getSize();
  48064. var maxDimension = Math.max(currentSize.width, currentSize.height);
  48065. if (maxDimension > _this.maximumSize) {
  48066. texture.scale(0.5);
  48067. allDone = false;
  48068. }
  48069. }
  48070. return allDone;
  48071. };
  48072. return _this;
  48073. }
  48074. return TextureOptimization;
  48075. }(SceneOptimization));
  48076. BABYLON.TextureOptimization = TextureOptimization;
  48077. var HardwareScalingOptimization = (function (_super) {
  48078. __extends(HardwareScalingOptimization, _super);
  48079. function HardwareScalingOptimization(priority, maximumScale) {
  48080. if (priority === void 0) { priority = 0; }
  48081. if (maximumScale === void 0) { maximumScale = 2; }
  48082. var _this = _super.call(this, priority) || this;
  48083. _this.priority = priority;
  48084. _this.maximumScale = maximumScale;
  48085. _this._currentScale = 1;
  48086. _this.apply = function (scene) {
  48087. _this._currentScale++;
  48088. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  48089. return _this._currentScale >= _this.maximumScale;
  48090. };
  48091. return _this;
  48092. }
  48093. return HardwareScalingOptimization;
  48094. }(SceneOptimization));
  48095. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  48096. var ShadowsOptimization = (function (_super) {
  48097. __extends(ShadowsOptimization, _super);
  48098. function ShadowsOptimization() {
  48099. var _this = _super.apply(this, arguments) || this;
  48100. _this.apply = function (scene) {
  48101. scene.shadowsEnabled = false;
  48102. return true;
  48103. };
  48104. return _this;
  48105. }
  48106. return ShadowsOptimization;
  48107. }(SceneOptimization));
  48108. BABYLON.ShadowsOptimization = ShadowsOptimization;
  48109. var PostProcessesOptimization = (function (_super) {
  48110. __extends(PostProcessesOptimization, _super);
  48111. function PostProcessesOptimization() {
  48112. var _this = _super.apply(this, arguments) || this;
  48113. _this.apply = function (scene) {
  48114. scene.postProcessesEnabled = false;
  48115. return true;
  48116. };
  48117. return _this;
  48118. }
  48119. return PostProcessesOptimization;
  48120. }(SceneOptimization));
  48121. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  48122. var LensFlaresOptimization = (function (_super) {
  48123. __extends(LensFlaresOptimization, _super);
  48124. function LensFlaresOptimization() {
  48125. var _this = _super.apply(this, arguments) || this;
  48126. _this.apply = function (scene) {
  48127. scene.lensFlaresEnabled = false;
  48128. return true;
  48129. };
  48130. return _this;
  48131. }
  48132. return LensFlaresOptimization;
  48133. }(SceneOptimization));
  48134. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  48135. var ParticlesOptimization = (function (_super) {
  48136. __extends(ParticlesOptimization, _super);
  48137. function ParticlesOptimization() {
  48138. var _this = _super.apply(this, arguments) || this;
  48139. _this.apply = function (scene) {
  48140. scene.particlesEnabled = false;
  48141. return true;
  48142. };
  48143. return _this;
  48144. }
  48145. return ParticlesOptimization;
  48146. }(SceneOptimization));
  48147. BABYLON.ParticlesOptimization = ParticlesOptimization;
  48148. var RenderTargetsOptimization = (function (_super) {
  48149. __extends(RenderTargetsOptimization, _super);
  48150. function RenderTargetsOptimization() {
  48151. var _this = _super.apply(this, arguments) || this;
  48152. _this.apply = function (scene) {
  48153. scene.renderTargetsEnabled = false;
  48154. return true;
  48155. };
  48156. return _this;
  48157. }
  48158. return RenderTargetsOptimization;
  48159. }(SceneOptimization));
  48160. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  48161. var MergeMeshesOptimization = (function (_super) {
  48162. __extends(MergeMeshesOptimization, _super);
  48163. function MergeMeshesOptimization() {
  48164. var _this = _super.apply(this, arguments) || this;
  48165. _this._canBeMerged = function (abstractMesh) {
  48166. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  48167. return false;
  48168. }
  48169. var mesh = abstractMesh;
  48170. if (!mesh.isVisible || !mesh.isEnabled()) {
  48171. return false;
  48172. }
  48173. if (mesh.instances.length > 0) {
  48174. return false;
  48175. }
  48176. if (mesh.skeleton || mesh.hasLODLevels) {
  48177. return false;
  48178. }
  48179. if (mesh.parent) {
  48180. return false;
  48181. }
  48182. return true;
  48183. };
  48184. _this.apply = function (scene, updateSelectionTree) {
  48185. var globalPool = scene.meshes.slice(0);
  48186. var globalLength = globalPool.length;
  48187. for (var index = 0; index < globalLength; index++) {
  48188. var currentPool = new Array();
  48189. var current = globalPool[index];
  48190. // Checks
  48191. if (!_this._canBeMerged(current)) {
  48192. continue;
  48193. }
  48194. currentPool.push(current);
  48195. // Find compatible meshes
  48196. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  48197. var otherMesh = globalPool[subIndex];
  48198. if (!_this._canBeMerged(otherMesh)) {
  48199. continue;
  48200. }
  48201. if (otherMesh.material !== current.material) {
  48202. continue;
  48203. }
  48204. if (otherMesh.checkCollisions !== current.checkCollisions) {
  48205. continue;
  48206. }
  48207. currentPool.push(otherMesh);
  48208. globalLength--;
  48209. globalPool.splice(subIndex, 1);
  48210. subIndex--;
  48211. }
  48212. if (currentPool.length < 2) {
  48213. continue;
  48214. }
  48215. // Merge meshes
  48216. BABYLON.Mesh.MergeMeshes(currentPool);
  48217. }
  48218. if (updateSelectionTree != undefined) {
  48219. if (updateSelectionTree) {
  48220. scene.createOrUpdateSelectionOctree();
  48221. }
  48222. }
  48223. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  48224. scene.createOrUpdateSelectionOctree();
  48225. }
  48226. return true;
  48227. };
  48228. return _this;
  48229. }
  48230. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  48231. get: function () {
  48232. return MergeMeshesOptimization._UpdateSelectionTree;
  48233. },
  48234. set: function (value) {
  48235. MergeMeshesOptimization._UpdateSelectionTree = value;
  48236. },
  48237. enumerable: true,
  48238. configurable: true
  48239. });
  48240. return MergeMeshesOptimization;
  48241. }(SceneOptimization));
  48242. MergeMeshesOptimization._UpdateSelectionTree = false;
  48243. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  48244. // Options
  48245. var SceneOptimizerOptions = (function () {
  48246. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  48247. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  48248. if (trackerDuration === void 0) { trackerDuration = 2000; }
  48249. this.targetFrameRate = targetFrameRate;
  48250. this.trackerDuration = trackerDuration;
  48251. this.optimizations = new Array();
  48252. }
  48253. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  48254. var result = new SceneOptimizerOptions(targetFrameRate);
  48255. var priority = 0;
  48256. result.optimizations.push(new MergeMeshesOptimization(priority));
  48257. result.optimizations.push(new ShadowsOptimization(priority));
  48258. result.optimizations.push(new LensFlaresOptimization(priority));
  48259. // Next priority
  48260. priority++;
  48261. result.optimizations.push(new PostProcessesOptimization(priority));
  48262. result.optimizations.push(new ParticlesOptimization(priority));
  48263. // Next priority
  48264. priority++;
  48265. result.optimizations.push(new TextureOptimization(priority, 1024));
  48266. return result;
  48267. };
  48268. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  48269. var result = new SceneOptimizerOptions(targetFrameRate);
  48270. var priority = 0;
  48271. result.optimizations.push(new MergeMeshesOptimization(priority));
  48272. result.optimizations.push(new ShadowsOptimization(priority));
  48273. result.optimizations.push(new LensFlaresOptimization(priority));
  48274. // Next priority
  48275. priority++;
  48276. result.optimizations.push(new PostProcessesOptimization(priority));
  48277. result.optimizations.push(new ParticlesOptimization(priority));
  48278. // Next priority
  48279. priority++;
  48280. result.optimizations.push(new TextureOptimization(priority, 512));
  48281. // Next priority
  48282. priority++;
  48283. result.optimizations.push(new RenderTargetsOptimization(priority));
  48284. // Next priority
  48285. priority++;
  48286. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  48287. return result;
  48288. };
  48289. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  48290. var result = new SceneOptimizerOptions(targetFrameRate);
  48291. var priority = 0;
  48292. result.optimizations.push(new MergeMeshesOptimization(priority));
  48293. result.optimizations.push(new ShadowsOptimization(priority));
  48294. result.optimizations.push(new LensFlaresOptimization(priority));
  48295. // Next priority
  48296. priority++;
  48297. result.optimizations.push(new PostProcessesOptimization(priority));
  48298. result.optimizations.push(new ParticlesOptimization(priority));
  48299. // Next priority
  48300. priority++;
  48301. result.optimizations.push(new TextureOptimization(priority, 256));
  48302. // Next priority
  48303. priority++;
  48304. result.optimizations.push(new RenderTargetsOptimization(priority));
  48305. // Next priority
  48306. priority++;
  48307. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  48308. return result;
  48309. };
  48310. return SceneOptimizerOptions;
  48311. }());
  48312. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  48313. // Scene optimizer tool
  48314. var SceneOptimizer = (function () {
  48315. function SceneOptimizer() {
  48316. }
  48317. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  48318. // TODO: add an epsilon
  48319. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  48320. if (onSuccess) {
  48321. onSuccess();
  48322. }
  48323. return;
  48324. }
  48325. // Apply current level of optimizations
  48326. var allDone = true;
  48327. var noOptimizationApplied = true;
  48328. for (var index = 0; index < options.optimizations.length; index++) {
  48329. var optimization = options.optimizations[index];
  48330. if (optimization.priority === currentPriorityLevel) {
  48331. noOptimizationApplied = false;
  48332. allDone = allDone && optimization.apply(scene);
  48333. }
  48334. }
  48335. // If no optimization was applied, this is a failure :(
  48336. if (noOptimizationApplied) {
  48337. if (onFailure) {
  48338. onFailure();
  48339. }
  48340. return;
  48341. }
  48342. // If all optimizations were done, move to next level
  48343. if (allDone) {
  48344. currentPriorityLevel++;
  48345. }
  48346. // Let's the system running for a specific amount of time before checking FPS
  48347. scene.executeWhenReady(function () {
  48348. setTimeout(function () {
  48349. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  48350. }, options.trackerDuration);
  48351. });
  48352. };
  48353. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  48354. if (!options) {
  48355. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  48356. }
  48357. // Let's the system running for a specific amount of time before checking FPS
  48358. scene.executeWhenReady(function () {
  48359. setTimeout(function () {
  48360. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  48361. }, options.trackerDuration);
  48362. });
  48363. };
  48364. return SceneOptimizer;
  48365. }());
  48366. BABYLON.SceneOptimizer = SceneOptimizer;
  48367. })(BABYLON || (BABYLON = {}));
  48368. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  48369. var BABYLON;
  48370. (function (BABYLON) {
  48371. var Internals;
  48372. (function (Internals) {
  48373. var MeshLODLevel = (function () {
  48374. function MeshLODLevel(distance, mesh) {
  48375. this.distance = distance;
  48376. this.mesh = mesh;
  48377. }
  48378. return MeshLODLevel;
  48379. }());
  48380. Internals.MeshLODLevel = MeshLODLevel;
  48381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48382. })(BABYLON || (BABYLON = {}));
  48383. //# sourceMappingURL=babylon.meshLODLevel.js.map
  48384. var BABYLON;
  48385. (function (BABYLON) {
  48386. var RawTexture = (function (_super) {
  48387. __extends(RawTexture, _super);
  48388. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48389. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48390. if (invertY === void 0) { invertY = false; }
  48391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48392. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48393. _this.format = format;
  48394. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48395. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48396. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48397. return _this;
  48398. }
  48399. RawTexture.prototype.update = function (data) {
  48400. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48401. };
  48402. // Statics
  48403. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48405. if (invertY === void 0) { invertY = false; }
  48406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48407. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48408. };
  48409. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48410. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48411. if (invertY === void 0) { invertY = false; }
  48412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48413. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48414. };
  48415. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48416. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48417. if (invertY === void 0) { invertY = false; }
  48418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48419. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48420. };
  48421. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48422. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48423. if (invertY === void 0) { invertY = false; }
  48424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48425. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  48426. };
  48427. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48428. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48429. if (invertY === void 0) { invertY = false; }
  48430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48431. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  48432. };
  48433. return RawTexture;
  48434. }(BABYLON.Texture));
  48435. BABYLON.RawTexture = RawTexture;
  48436. })(BABYLON || (BABYLON = {}));
  48437. //# sourceMappingURL=babylon.rawTexture.js.map
  48438. /// <reference path="..\Math\babylon.math.ts" />
  48439. var BABYLON;
  48440. (function (BABYLON) {
  48441. var IndexedVector2 = (function (_super) {
  48442. __extends(IndexedVector2, _super);
  48443. function IndexedVector2(original, index) {
  48444. var _this = _super.call(this, original.x, original.y) || this;
  48445. _this.index = index;
  48446. return _this;
  48447. }
  48448. return IndexedVector2;
  48449. }(BABYLON.Vector2));
  48450. var PolygonPoints = (function () {
  48451. function PolygonPoints() {
  48452. this.elements = new Array();
  48453. }
  48454. PolygonPoints.prototype.add = function (originalPoints) {
  48455. var _this = this;
  48456. var result = new Array();
  48457. originalPoints.forEach(function (point) {
  48458. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  48459. var newPoint = new IndexedVector2(point, _this.elements.length);
  48460. result.push(newPoint);
  48461. _this.elements.push(newPoint);
  48462. }
  48463. });
  48464. return result;
  48465. };
  48466. PolygonPoints.prototype.computeBounds = function () {
  48467. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48468. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48469. this.elements.forEach(function (point) {
  48470. // x
  48471. if (point.x < lmin.x) {
  48472. lmin.x = point.x;
  48473. }
  48474. else if (point.x > lmax.x) {
  48475. lmax.x = point.x;
  48476. }
  48477. // y
  48478. if (point.y < lmin.y) {
  48479. lmin.y = point.y;
  48480. }
  48481. else if (point.y > lmax.y) {
  48482. lmax.y = point.y;
  48483. }
  48484. });
  48485. return {
  48486. min: lmin,
  48487. max: lmax,
  48488. width: lmax.x - lmin.x,
  48489. height: lmax.y - lmin.y
  48490. };
  48491. };
  48492. return PolygonPoints;
  48493. }());
  48494. var Polygon = (function () {
  48495. function Polygon() {
  48496. }
  48497. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  48498. return [
  48499. new BABYLON.Vector2(xmin, ymin),
  48500. new BABYLON.Vector2(xmax, ymin),
  48501. new BABYLON.Vector2(xmax, ymax),
  48502. new BABYLON.Vector2(xmin, ymax)
  48503. ];
  48504. };
  48505. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  48506. if (cx === void 0) { cx = 0; }
  48507. if (cy === void 0) { cy = 0; }
  48508. if (numberOfSides === void 0) { numberOfSides = 32; }
  48509. var result = new Array();
  48510. var angle = 0;
  48511. var increment = (Math.PI * 2) / numberOfSides;
  48512. for (var i = 0; i < numberOfSides; i++) {
  48513. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  48514. angle -= increment;
  48515. }
  48516. return result;
  48517. };
  48518. Polygon.Parse = function (input) {
  48519. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  48520. var i, result = [];
  48521. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  48522. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  48523. }
  48524. return result;
  48525. };
  48526. Polygon.StartingAt = function (x, y) {
  48527. return BABYLON.Path2.StartingAt(x, y);
  48528. };
  48529. return Polygon;
  48530. }());
  48531. BABYLON.Polygon = Polygon;
  48532. var PolygonMeshBuilder = (function () {
  48533. function PolygonMeshBuilder(name, contours, scene) {
  48534. this._points = new PolygonPoints();
  48535. this._outlinepoints = new PolygonPoints();
  48536. this._holes = [];
  48537. this._epoints = new Array();
  48538. this._eholes = new Array();
  48539. this._name = name;
  48540. this._scene = scene;
  48541. var points;
  48542. if (contours instanceof BABYLON.Path2) {
  48543. points = contours.getPoints();
  48544. }
  48545. else {
  48546. points = contours;
  48547. }
  48548. this._addToepoint(points);
  48549. this._points.add(points);
  48550. this._outlinepoints.add(points);
  48551. }
  48552. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  48553. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  48554. var p = points_1[_i];
  48555. this._epoints.push(p.x, p.y);
  48556. }
  48557. };
  48558. PolygonMeshBuilder.prototype.addHole = function (hole) {
  48559. this._points.add(hole);
  48560. var holepoints = new PolygonPoints();
  48561. holepoints.add(hole);
  48562. this._holes.push(holepoints);
  48563. this._eholes.push(this._epoints.length / 2);
  48564. this._addToepoint(hole);
  48565. return this;
  48566. };
  48567. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  48568. var _this = this;
  48569. if (updatable === void 0) { updatable = false; }
  48570. var result = new BABYLON.Mesh(this._name, this._scene);
  48571. var normals = [];
  48572. var positions = [];
  48573. var uvs = [];
  48574. var bounds = this._points.computeBounds();
  48575. this._points.elements.forEach(function (p) {
  48576. normals.push(0, 1.0, 0);
  48577. positions.push(p.x, 0, p.y);
  48578. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  48579. });
  48580. var indices = [];
  48581. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  48582. for (var i = 0; i < res.length; i++) {
  48583. indices.push(res[i]);
  48584. }
  48585. if (depth > 0) {
  48586. var positionscount = (positions.length / 3); //get the current pointcount
  48587. this._points.elements.forEach(function (p) {
  48588. normals.push(0, -1.0, 0);
  48589. positions.push(p.x, -depth, p.y);
  48590. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  48591. });
  48592. var totalCount = indices.length;
  48593. for (var i = 0; i < totalCount; i += 3) {
  48594. var i0 = indices[i + 0];
  48595. var i1 = indices[i + 1];
  48596. var i2 = indices[i + 2];
  48597. indices.push(i2 + positionscount);
  48598. indices.push(i1 + positionscount);
  48599. indices.push(i0 + positionscount);
  48600. }
  48601. //Add the sides
  48602. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  48603. this._holes.forEach(function (hole) {
  48604. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  48605. });
  48606. }
  48607. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  48608. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  48609. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  48610. result.setIndices(indices);
  48611. return result;
  48612. };
  48613. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  48614. var StartIndex = positions.length / 3;
  48615. var ulength = 0;
  48616. for (var i = 0; i < points.elements.length; i++) {
  48617. var p = points.elements[i];
  48618. var p1;
  48619. if ((i + 1) > points.elements.length - 1) {
  48620. p1 = points.elements[0];
  48621. }
  48622. else {
  48623. p1 = points.elements[i + 1];
  48624. }
  48625. positions.push(p.x, 0, p.y);
  48626. positions.push(p.x, -depth, p.y);
  48627. positions.push(p1.x, 0, p1.y);
  48628. positions.push(p1.x, -depth, p1.y);
  48629. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  48630. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  48631. var v3 = v2.subtract(v1);
  48632. var v4 = new BABYLON.Vector3(0, 1, 0);
  48633. var vn = BABYLON.Vector3.Cross(v3, v4);
  48634. vn = vn.normalize();
  48635. uvs.push(ulength / bounds.width, 0);
  48636. uvs.push(ulength / bounds.width, 1);
  48637. ulength += v3.length();
  48638. uvs.push((ulength / bounds.width), 0);
  48639. uvs.push((ulength / bounds.width), 1);
  48640. if (!flip) {
  48641. normals.push(-vn.x, -vn.y, -vn.z);
  48642. normals.push(-vn.x, -vn.y, -vn.z);
  48643. normals.push(-vn.x, -vn.y, -vn.z);
  48644. normals.push(-vn.x, -vn.y, -vn.z);
  48645. indices.push(StartIndex);
  48646. indices.push(StartIndex + 1);
  48647. indices.push(StartIndex + 2);
  48648. indices.push(StartIndex + 1);
  48649. indices.push(StartIndex + 3);
  48650. indices.push(StartIndex + 2);
  48651. }
  48652. else {
  48653. normals.push(vn.x, vn.y, vn.z);
  48654. normals.push(vn.x, vn.y, vn.z);
  48655. normals.push(vn.x, vn.y, vn.z);
  48656. normals.push(vn.x, vn.y, vn.z);
  48657. indices.push(StartIndex);
  48658. indices.push(StartIndex + 2);
  48659. indices.push(StartIndex + 1);
  48660. indices.push(StartIndex + 1);
  48661. indices.push(StartIndex + 2);
  48662. indices.push(StartIndex + 3);
  48663. }
  48664. StartIndex += 4;
  48665. }
  48666. ;
  48667. };
  48668. return PolygonMeshBuilder;
  48669. }());
  48670. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  48671. })(BABYLON || (BABYLON = {}));
  48672. //# sourceMappingURL=babylon.polygonMesh.js.map
  48673. var BABYLON;
  48674. (function (BABYLON) {
  48675. var Octree = (function () {
  48676. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  48677. if (maxDepth === void 0) { maxDepth = 2; }
  48678. this.maxDepth = maxDepth;
  48679. this.dynamicContent = new Array();
  48680. this._maxBlockCapacity = maxBlockCapacity || 64;
  48681. this._selectionContent = new BABYLON.SmartArray(1024);
  48682. this._creationFunc = creationFunc;
  48683. }
  48684. // Methods
  48685. Octree.prototype.update = function (worldMin, worldMax, entries) {
  48686. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  48687. };
  48688. Octree.prototype.addMesh = function (entry) {
  48689. for (var index = 0; index < this.blocks.length; index++) {
  48690. var block = this.blocks[index];
  48691. block.addEntry(entry);
  48692. }
  48693. };
  48694. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  48695. this._selectionContent.reset();
  48696. for (var index = 0; index < this.blocks.length; index++) {
  48697. var block = this.blocks[index];
  48698. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  48699. }
  48700. if (allowDuplicate) {
  48701. this._selectionContent.concat(this.dynamicContent);
  48702. }
  48703. else {
  48704. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48705. }
  48706. return this._selectionContent;
  48707. };
  48708. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  48709. this._selectionContent.reset();
  48710. for (var index = 0; index < this.blocks.length; index++) {
  48711. var block = this.blocks[index];
  48712. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  48713. }
  48714. if (allowDuplicate) {
  48715. this._selectionContent.concat(this.dynamicContent);
  48716. }
  48717. else {
  48718. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48719. }
  48720. return this._selectionContent;
  48721. };
  48722. Octree.prototype.intersectsRay = function (ray) {
  48723. this._selectionContent.reset();
  48724. for (var index = 0; index < this.blocks.length; index++) {
  48725. var block = this.blocks[index];
  48726. block.intersectsRay(ray, this._selectionContent);
  48727. }
  48728. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48729. return this._selectionContent;
  48730. };
  48731. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  48732. target.blocks = new Array();
  48733. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  48734. // Segmenting space
  48735. for (var x = 0; x < 2; x++) {
  48736. for (var y = 0; y < 2; y++) {
  48737. for (var z = 0; z < 2; z++) {
  48738. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  48739. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  48740. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  48741. block.addEntries(entries);
  48742. target.blocks.push(block);
  48743. }
  48744. }
  48745. }
  48746. };
  48747. return Octree;
  48748. }());
  48749. Octree.CreationFuncForMeshes = function (entry, block) {
  48750. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48751. block.entries.push(entry);
  48752. }
  48753. };
  48754. Octree.CreationFuncForSubMeshes = function (entry, block) {
  48755. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48756. block.entries.push(entry);
  48757. }
  48758. };
  48759. BABYLON.Octree = Octree;
  48760. })(BABYLON || (BABYLON = {}));
  48761. //# sourceMappingURL=babylon.octree.js.map
  48762. var BABYLON;
  48763. (function (BABYLON) {
  48764. var OctreeBlock = (function () {
  48765. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  48766. this.entries = new Array();
  48767. this._boundingVectors = new Array();
  48768. this._capacity = capacity;
  48769. this._depth = depth;
  48770. this._maxDepth = maxDepth;
  48771. this._creationFunc = creationFunc;
  48772. this._minPoint = minPoint;
  48773. this._maxPoint = maxPoint;
  48774. this._boundingVectors.push(minPoint.clone());
  48775. this._boundingVectors.push(maxPoint.clone());
  48776. this._boundingVectors.push(minPoint.clone());
  48777. this._boundingVectors[2].x = maxPoint.x;
  48778. this._boundingVectors.push(minPoint.clone());
  48779. this._boundingVectors[3].y = maxPoint.y;
  48780. this._boundingVectors.push(minPoint.clone());
  48781. this._boundingVectors[4].z = maxPoint.z;
  48782. this._boundingVectors.push(maxPoint.clone());
  48783. this._boundingVectors[5].z = minPoint.z;
  48784. this._boundingVectors.push(maxPoint.clone());
  48785. this._boundingVectors[6].x = minPoint.x;
  48786. this._boundingVectors.push(maxPoint.clone());
  48787. this._boundingVectors[7].y = minPoint.y;
  48788. }
  48789. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  48790. // Property
  48791. get: function () {
  48792. return this._capacity;
  48793. },
  48794. enumerable: true,
  48795. configurable: true
  48796. });
  48797. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  48798. get: function () {
  48799. return this._minPoint;
  48800. },
  48801. enumerable: true,
  48802. configurable: true
  48803. });
  48804. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  48805. get: function () {
  48806. return this._maxPoint;
  48807. },
  48808. enumerable: true,
  48809. configurable: true
  48810. });
  48811. // Methods
  48812. OctreeBlock.prototype.addEntry = function (entry) {
  48813. if (this.blocks) {
  48814. for (var index = 0; index < this.blocks.length; index++) {
  48815. var block = this.blocks[index];
  48816. block.addEntry(entry);
  48817. }
  48818. return;
  48819. }
  48820. this._creationFunc(entry, this);
  48821. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  48822. this.createInnerBlocks();
  48823. }
  48824. };
  48825. OctreeBlock.prototype.addEntries = function (entries) {
  48826. for (var index = 0; index < entries.length; index++) {
  48827. var mesh = entries[index];
  48828. this.addEntry(mesh);
  48829. }
  48830. };
  48831. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  48832. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  48833. if (this.blocks) {
  48834. for (var index = 0; index < this.blocks.length; index++) {
  48835. var block = this.blocks[index];
  48836. block.select(frustumPlanes, selection, allowDuplicate);
  48837. }
  48838. return;
  48839. }
  48840. if (allowDuplicate) {
  48841. selection.concat(this.entries);
  48842. }
  48843. else {
  48844. selection.concatWithNoDuplicate(this.entries);
  48845. }
  48846. }
  48847. };
  48848. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  48849. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  48850. if (this.blocks) {
  48851. for (var index = 0; index < this.blocks.length; index++) {
  48852. var block = this.blocks[index];
  48853. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  48854. }
  48855. return;
  48856. }
  48857. if (allowDuplicate) {
  48858. selection.concat(this.entries);
  48859. }
  48860. else {
  48861. selection.concatWithNoDuplicate(this.entries);
  48862. }
  48863. }
  48864. };
  48865. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  48866. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  48867. if (this.blocks) {
  48868. for (var index = 0; index < this.blocks.length; index++) {
  48869. var block = this.blocks[index];
  48870. block.intersectsRay(ray, selection);
  48871. }
  48872. return;
  48873. }
  48874. selection.concatWithNoDuplicate(this.entries);
  48875. }
  48876. };
  48877. OctreeBlock.prototype.createInnerBlocks = function () {
  48878. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  48879. };
  48880. return OctreeBlock;
  48881. }());
  48882. BABYLON.OctreeBlock = OctreeBlock;
  48883. })(BABYLON || (BABYLON = {}));
  48884. //# sourceMappingURL=babylon.octreeBlock.js.map
  48885. var BABYLON;
  48886. (function (BABYLON) {
  48887. var BlurPostProcess = (function (_super) {
  48888. __extends(BlurPostProcess, _super);
  48889. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48891. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48892. _this.direction = direction;
  48893. _this.blurWidth = blurWidth;
  48894. _this.onApplyObservable.add(function (effect) {
  48895. effect.setFloat2("screenSize", _this.width, _this.height);
  48896. effect.setVector2("direction", _this.direction);
  48897. effect.setFloat("blurWidth", _this.blurWidth);
  48898. });
  48899. return _this;
  48900. }
  48901. return BlurPostProcess;
  48902. }(BABYLON.PostProcess));
  48903. BABYLON.BlurPostProcess = BlurPostProcess;
  48904. })(BABYLON || (BABYLON = {}));
  48905. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48906. var BABYLON;
  48907. (function (BABYLON) {
  48908. var RefractionPostProcess = (function (_super) {
  48909. __extends(RefractionPostProcess, _super);
  48910. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48911. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48912. _this.color = color;
  48913. _this.depth = depth;
  48914. _this.colorLevel = colorLevel;
  48915. _this.onActivateObservable.add(function (cam) {
  48916. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48917. });
  48918. _this.onApplyObservable.add(function (effect) {
  48919. effect.setColor3("baseColor", _this.color);
  48920. effect.setFloat("depth", _this.depth);
  48921. effect.setFloat("colorLevel", _this.colorLevel);
  48922. effect.setTexture("refractionSampler", _this._refRexture);
  48923. });
  48924. return _this;
  48925. }
  48926. // Methods
  48927. RefractionPostProcess.prototype.dispose = function (camera) {
  48928. if (this._refRexture) {
  48929. this._refRexture.dispose();
  48930. }
  48931. _super.prototype.dispose.call(this, camera);
  48932. };
  48933. return RefractionPostProcess;
  48934. }(BABYLON.PostProcess));
  48935. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48936. })(BABYLON || (BABYLON = {}));
  48937. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48938. var BABYLON;
  48939. (function (BABYLON) {
  48940. var BlackAndWhitePostProcess = (function (_super) {
  48941. __extends(BlackAndWhitePostProcess, _super);
  48942. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48943. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48944. }
  48945. return BlackAndWhitePostProcess;
  48946. }(BABYLON.PostProcess));
  48947. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48948. })(BABYLON || (BABYLON = {}));
  48949. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48950. var BABYLON;
  48951. (function (BABYLON) {
  48952. var ConvolutionPostProcess = (function (_super) {
  48953. __extends(ConvolutionPostProcess, _super);
  48954. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48955. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48956. _this.kernel = kernel;
  48957. _this.onApply = function (effect) {
  48958. effect.setFloat2("screenSize", _this.width, _this.height);
  48959. effect.setArray("kernel", _this.kernel);
  48960. };
  48961. return _this;
  48962. }
  48963. return ConvolutionPostProcess;
  48964. }(BABYLON.PostProcess));
  48965. // Statics
  48966. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48967. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48968. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48969. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48970. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48971. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48972. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48973. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48974. })(BABYLON || (BABYLON = {}));
  48975. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48976. var BABYLON;
  48977. (function (BABYLON) {
  48978. var FilterPostProcess = (function (_super) {
  48979. __extends(FilterPostProcess, _super);
  48980. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48981. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48982. _this.kernelMatrix = kernelMatrix;
  48983. _this.onApply = function (effect) {
  48984. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48985. };
  48986. return _this;
  48987. }
  48988. return FilterPostProcess;
  48989. }(BABYLON.PostProcess));
  48990. BABYLON.FilterPostProcess = FilterPostProcess;
  48991. })(BABYLON || (BABYLON = {}));
  48992. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48993. var BABYLON;
  48994. (function (BABYLON) {
  48995. var FxaaPostProcess = (function (_super) {
  48996. __extends(FxaaPostProcess, _super);
  48997. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48998. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48999. _this.onSizeChangedObservable.add(function () {
  49000. _this.texelWidth = 1.0 / _this.width;
  49001. _this.texelHeight = 1.0 / _this.height;
  49002. });
  49003. _this.onApplyObservable.add(function (effect) {
  49004. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  49005. });
  49006. return _this;
  49007. }
  49008. return FxaaPostProcess;
  49009. }(BABYLON.PostProcess));
  49010. BABYLON.FxaaPostProcess = FxaaPostProcess;
  49011. })(BABYLON || (BABYLON = {}));
  49012. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  49013. var BABYLON;
  49014. (function (BABYLON) {
  49015. var StereoscopicInterlacePostProcess = (function (_super) {
  49016. __extends(StereoscopicInterlacePostProcess, _super);
  49017. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  49018. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  49019. _this._passedProcess = rigCameras[0]._rigPostProcess;
  49020. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49021. _this.onSizeChangedObservable.add(function () {
  49022. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49023. });
  49024. _this.onApplyObservable.add(function (effect) {
  49025. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  49026. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  49027. });
  49028. return _this;
  49029. }
  49030. return StereoscopicInterlacePostProcess;
  49031. }(BABYLON.PostProcess));
  49032. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  49033. })(BABYLON || (BABYLON = {}));
  49034. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  49035. var BABYLON;
  49036. (function (BABYLON) {
  49037. var LensFlare = (function () {
  49038. function LensFlare(size, position, color, imgUrl, system) {
  49039. this.size = size;
  49040. this.position = position;
  49041. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  49042. this.dispose = function () {
  49043. if (this.texture) {
  49044. this.texture.dispose();
  49045. }
  49046. // Remove from scene
  49047. var index = this._system.lensFlares.indexOf(this);
  49048. this._system.lensFlares.splice(index, 1);
  49049. };
  49050. this.color = color || new BABYLON.Color3(1, 1, 1);
  49051. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  49052. this._system = system;
  49053. system.lensFlares.push(this);
  49054. }
  49055. return LensFlare;
  49056. }());
  49057. BABYLON.LensFlare = LensFlare;
  49058. })(BABYLON || (BABYLON = {}));
  49059. //# sourceMappingURL=babylon.lensFlare.js.map
  49060. var BABYLON;
  49061. (function (BABYLON) {
  49062. var LensFlareSystem = (function () {
  49063. function LensFlareSystem(name, emitter, scene) {
  49064. this.name = name;
  49065. this.lensFlares = new Array();
  49066. this.borderLimit = 300;
  49067. this.viewportBorder = 0;
  49068. this.layerMask = 0x0FFFFFFF;
  49069. this._vertexBuffers = {};
  49070. this._isEnabled = true;
  49071. this._scene = scene;
  49072. this._emitter = emitter;
  49073. this.id = name;
  49074. scene.lensFlareSystems.push(this);
  49075. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  49076. var engine = scene.getEngine();
  49077. // VBO
  49078. var vertices = [];
  49079. vertices.push(1, 1);
  49080. vertices.push(-1, 1);
  49081. vertices.push(-1, -1);
  49082. vertices.push(1, -1);
  49083. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49084. // Indices
  49085. var indices = [];
  49086. indices.push(0);
  49087. indices.push(1);
  49088. indices.push(2);
  49089. indices.push(0);
  49090. indices.push(2);
  49091. indices.push(3);
  49092. this._indexBuffer = engine.createIndexBuffer(indices);
  49093. // Effects
  49094. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  49095. }
  49096. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  49097. get: function () {
  49098. return this._isEnabled;
  49099. },
  49100. set: function (value) {
  49101. this._isEnabled = value;
  49102. },
  49103. enumerable: true,
  49104. configurable: true
  49105. });
  49106. LensFlareSystem.prototype.getScene = function () {
  49107. return this._scene;
  49108. };
  49109. LensFlareSystem.prototype.getEmitter = function () {
  49110. return this._emitter;
  49111. };
  49112. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  49113. this._emitter = newEmitter;
  49114. };
  49115. LensFlareSystem.prototype.getEmitterPosition = function () {
  49116. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  49117. };
  49118. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  49119. var position = this.getEmitterPosition();
  49120. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  49121. this._positionX = position.x;
  49122. this._positionY = position.y;
  49123. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  49124. if (this.viewportBorder > 0) {
  49125. globalViewport.x -= this.viewportBorder;
  49126. globalViewport.y -= this.viewportBorder;
  49127. globalViewport.width += this.viewportBorder * 2;
  49128. globalViewport.height += this.viewportBorder * 2;
  49129. position.x += this.viewportBorder;
  49130. position.y += this.viewportBorder;
  49131. this._positionX += this.viewportBorder;
  49132. this._positionY += this.viewportBorder;
  49133. }
  49134. if (position.z > 0) {
  49135. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  49136. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  49137. return true;
  49138. }
  49139. return true;
  49140. }
  49141. return false;
  49142. };
  49143. LensFlareSystem.prototype._isVisible = function () {
  49144. if (!this._isEnabled) {
  49145. return false;
  49146. }
  49147. var emitterPosition = this.getEmitterPosition();
  49148. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  49149. var distance = direction.length();
  49150. direction.normalize();
  49151. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  49152. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  49153. return !pickInfo.hit || pickInfo.distance > distance;
  49154. };
  49155. LensFlareSystem.prototype.render = function () {
  49156. if (!this._effect.isReady())
  49157. return false;
  49158. var engine = this._scene.getEngine();
  49159. var viewport = this._scene.activeCamera.viewport;
  49160. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  49161. // Position
  49162. if (!this.computeEffectivePosition(globalViewport)) {
  49163. return false;
  49164. }
  49165. // Visibility
  49166. if (!this._isVisible()) {
  49167. return false;
  49168. }
  49169. // Intensity
  49170. var awayX;
  49171. var awayY;
  49172. if (this._positionX < this.borderLimit + globalViewport.x) {
  49173. awayX = this.borderLimit + globalViewport.x - this._positionX;
  49174. }
  49175. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  49176. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  49177. }
  49178. else {
  49179. awayX = 0;
  49180. }
  49181. if (this._positionY < this.borderLimit + globalViewport.y) {
  49182. awayY = this.borderLimit + globalViewport.y - this._positionY;
  49183. }
  49184. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  49185. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  49186. }
  49187. else {
  49188. awayY = 0;
  49189. }
  49190. var away = (awayX > awayY) ? awayX : awayY;
  49191. away -= this.viewportBorder;
  49192. if (away > this.borderLimit) {
  49193. away = this.borderLimit;
  49194. }
  49195. var intensity = 1.0 - (away / this.borderLimit);
  49196. if (intensity < 0) {
  49197. return false;
  49198. }
  49199. if (intensity > 1.0) {
  49200. intensity = 1.0;
  49201. }
  49202. if (this.viewportBorder > 0) {
  49203. globalViewport.x += this.viewportBorder;
  49204. globalViewport.y += this.viewportBorder;
  49205. globalViewport.width -= this.viewportBorder * 2;
  49206. globalViewport.height -= this.viewportBorder * 2;
  49207. this._positionX -= this.viewportBorder;
  49208. this._positionY -= this.viewportBorder;
  49209. }
  49210. // Position
  49211. var centerX = globalViewport.x + globalViewport.width / 2;
  49212. var centerY = globalViewport.y + globalViewport.height / 2;
  49213. var distX = centerX - this._positionX;
  49214. var distY = centerY - this._positionY;
  49215. // Effects
  49216. engine.enableEffect(this._effect);
  49217. engine.setState(false);
  49218. engine.setDepthBuffer(false);
  49219. // VBOs
  49220. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49221. // Flares
  49222. for (var index = 0; index < this.lensFlares.length; index++) {
  49223. var flare = this.lensFlares[index];
  49224. engine.setAlphaMode(flare.alphaMode);
  49225. var x = centerX - (distX * flare.position);
  49226. var y = centerY - (distY * flare.position);
  49227. var cw = flare.size;
  49228. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  49229. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  49230. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  49231. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  49232. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  49233. // Texture
  49234. this._effect.setTexture("textureSampler", flare.texture);
  49235. // Color
  49236. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  49237. // Draw order
  49238. engine.draw(true, 0, 6);
  49239. }
  49240. engine.setDepthBuffer(true);
  49241. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49242. return true;
  49243. };
  49244. LensFlareSystem.prototype.dispose = function () {
  49245. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49246. if (vertexBuffer) {
  49247. vertexBuffer.dispose();
  49248. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49249. }
  49250. if (this._indexBuffer) {
  49251. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49252. this._indexBuffer = null;
  49253. }
  49254. while (this.lensFlares.length) {
  49255. this.lensFlares[0].dispose();
  49256. }
  49257. // Remove from scene
  49258. var index = this._scene.lensFlareSystems.indexOf(this);
  49259. this._scene.lensFlareSystems.splice(index, 1);
  49260. };
  49261. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  49262. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  49263. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  49264. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  49265. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  49266. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  49267. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  49268. var parsedFlare = parsedLensFlareSystem.flares[index];
  49269. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  49270. }
  49271. return lensFlareSystem;
  49272. };
  49273. LensFlareSystem.prototype.serialize = function () {
  49274. var serializationObject = {};
  49275. serializationObject.id = this.id;
  49276. serializationObject.name = this.name;
  49277. serializationObject.emitterId = this.getEmitter().id;
  49278. serializationObject.borderLimit = this.borderLimit;
  49279. serializationObject.flares = [];
  49280. for (var index = 0; index < this.lensFlares.length; index++) {
  49281. var flare = this.lensFlares[index];
  49282. serializationObject.flares.push({
  49283. size: flare.size,
  49284. position: flare.position,
  49285. color: flare.color.asArray(),
  49286. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  49287. });
  49288. }
  49289. return serializationObject;
  49290. };
  49291. return LensFlareSystem;
  49292. }());
  49293. BABYLON.LensFlareSystem = LensFlareSystem;
  49294. })(BABYLON || (BABYLON = {}));
  49295. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  49296. /// <reference path="babylon.freeCamera.ts" />
  49297. var BABYLON;
  49298. (function (BABYLON) {
  49299. // We're mainly based on the logic defined into the FreeCamera code
  49300. var DeviceOrientationCamera = (function (_super) {
  49301. __extends(DeviceOrientationCamera, _super);
  49302. function DeviceOrientationCamera(name, position, scene) {
  49303. var _this = _super.call(this, name, position, scene) || this;
  49304. _this._quaternionCache = new BABYLON.Quaternion();
  49305. _this.inputs.addDeviceOrientation();
  49306. return _this;
  49307. }
  49308. DeviceOrientationCamera.prototype.getClassName = function () {
  49309. return "DeviceOrientationCamera";
  49310. };
  49311. DeviceOrientationCamera.prototype._checkInputs = function () {
  49312. _super.prototype._checkInputs.call(this);
  49313. this._quaternionCache.copyFrom(this.rotationQuaternion);
  49314. if (this._initialQuaternion) {
  49315. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49316. }
  49317. };
  49318. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  49319. var _this = this;
  49320. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  49321. //can only work if this camera has a rotation quaternion already.
  49322. if (!this.rotationQuaternion)
  49323. return;
  49324. if (!this._initialQuaternion) {
  49325. this._initialQuaternion = new BABYLON.Quaternion();
  49326. }
  49327. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  49328. ['x', 'y', 'z'].forEach(function (axisName) {
  49329. if (!axis[axisName]) {
  49330. _this._initialQuaternion[axisName] = 0;
  49331. }
  49332. else {
  49333. _this._initialQuaternion[axisName] *= -1;
  49334. }
  49335. });
  49336. this._initialQuaternion.normalize();
  49337. //force rotation update
  49338. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49339. };
  49340. return DeviceOrientationCamera;
  49341. }(BABYLON.FreeCamera));
  49342. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  49343. })(BABYLON || (BABYLON = {}));
  49344. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  49345. var BABYLON;
  49346. (function (BABYLON) {
  49347. var VRDeviceOrientationFreeCamera = (function (_super) {
  49348. __extends(VRDeviceOrientationFreeCamera, _super);
  49349. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49350. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49351. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49352. var _this = _super.call(this, name, position, scene) || this;
  49353. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49354. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49355. return _this;
  49356. }
  49357. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  49358. return "VRDeviceOrientationFreeCamera";
  49359. };
  49360. return VRDeviceOrientationFreeCamera;
  49361. }(BABYLON.DeviceOrientationCamera));
  49362. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  49363. var VRDeviceOrientationGamepadCamera = (function (_super) {
  49364. __extends(VRDeviceOrientationGamepadCamera, _super);
  49365. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49366. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49367. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49368. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  49369. _this.inputs.addGamepad();
  49370. return _this;
  49371. }
  49372. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  49373. return "VRDeviceOrientationGamepadCamera";
  49374. };
  49375. return VRDeviceOrientationGamepadCamera;
  49376. }(VRDeviceOrientationFreeCamera));
  49377. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  49378. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  49379. __extends(VRDeviceOrientationArcRotateCamera, _super);
  49380. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  49381. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49382. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49383. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  49384. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49385. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49386. _this.inputs.addVRDeviceOrientation();
  49387. return _this;
  49388. }
  49389. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  49390. return "VRDeviceOrientationArcRotateCamera";
  49391. };
  49392. return VRDeviceOrientationArcRotateCamera;
  49393. }(BABYLON.ArcRotateCamera));
  49394. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  49395. })(BABYLON || (BABYLON = {}));
  49396. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  49397. /// <reference path="babylon.touchCamera.ts" />
  49398. var BABYLON;
  49399. (function (BABYLON) {
  49400. // We're mainly based on the logic defined into the FreeCamera code
  49401. var UniversalCamera = (function (_super) {
  49402. __extends(UniversalCamera, _super);
  49403. //-- end properties for backward compatibility for inputs
  49404. function UniversalCamera(name, position, scene) {
  49405. var _this = _super.call(this, name, position, scene) || this;
  49406. _this.inputs.addGamepad();
  49407. return _this;
  49408. }
  49409. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49410. //-- Begin properties for backward compatibility for inputs
  49411. get: function () {
  49412. var gamepad = this.inputs.attached["gamepad"];
  49413. if (gamepad)
  49414. return gamepad.gamepadAngularSensibility;
  49415. },
  49416. set: function (value) {
  49417. var gamepad = this.inputs.attached["gamepad"];
  49418. if (gamepad)
  49419. gamepad.gamepadAngularSensibility = value;
  49420. },
  49421. enumerable: true,
  49422. configurable: true
  49423. });
  49424. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49425. get: function () {
  49426. var gamepad = this.inputs.attached["gamepad"];
  49427. if (gamepad)
  49428. return gamepad.gamepadMoveSensibility;
  49429. },
  49430. set: function (value) {
  49431. var gamepad = this.inputs.attached["gamepad"];
  49432. if (gamepad)
  49433. gamepad.gamepadMoveSensibility = value;
  49434. },
  49435. enumerable: true,
  49436. configurable: true
  49437. });
  49438. UniversalCamera.prototype.getClassName = function () {
  49439. return "UniversalCamera";
  49440. };
  49441. return UniversalCamera;
  49442. }(BABYLON.TouchCamera));
  49443. BABYLON.UniversalCamera = UniversalCamera;
  49444. })(BABYLON || (BABYLON = {}));
  49445. //# sourceMappingURL=babylon.universalCamera.js.map
  49446. var BABYLON;
  49447. (function (BABYLON) {
  49448. var Gamepads = (function () {
  49449. function Gamepads(ongamedpadconnected) {
  49450. var _this = this;
  49451. this.babylonGamepads = [];
  49452. this.oneGamepadConnected = false;
  49453. this.isMonitoring = false;
  49454. this.gamepadEventSupported = 'GamepadEvent' in window;
  49455. this.gamepadSupportAvailable = (navigator.getGamepads ||
  49456. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  49457. this._callbackGamepadConnected = ongamedpadconnected;
  49458. if (this.gamepadSupportAvailable) {
  49459. // Checking if the gamepad connected event is supported (like in Firefox)
  49460. if (this.gamepadEventSupported) {
  49461. this._onGamepadConnectedEvent = function (evt) {
  49462. _this._onGamepadConnected(evt);
  49463. };
  49464. this._onGamepadDisonnectedEvent = function (evt) {
  49465. _this._onGamepadDisconnected(evt);
  49466. };
  49467. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49468. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49469. }
  49470. else {
  49471. this._startMonitoringGamepads();
  49472. }
  49473. }
  49474. }
  49475. Gamepads.prototype.dispose = function () {
  49476. if (Gamepads.gamepadDOMInfo) {
  49477. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49478. }
  49479. if (this._onGamepadConnectedEvent) {
  49480. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49481. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49482. this._onGamepadConnectedEvent = null;
  49483. this._onGamepadDisonnectedEvent = null;
  49484. }
  49485. };
  49486. Gamepads.prototype._onGamepadConnected = function (evt) {
  49487. var newGamepad = this._addNewGamepad(evt.gamepad);
  49488. if (this._callbackGamepadConnected)
  49489. this._callbackGamepadConnected(newGamepad);
  49490. this._startMonitoringGamepads();
  49491. };
  49492. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49493. if (!this.oneGamepadConnected) {
  49494. this.oneGamepadConnected = true;
  49495. if (Gamepads.gamepadDOMInfo) {
  49496. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49497. Gamepads.gamepadDOMInfo = null;
  49498. }
  49499. }
  49500. var newGamepad;
  49501. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49502. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49503. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49504. }
  49505. else {
  49506. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49507. }
  49508. this.babylonGamepads.push(newGamepad);
  49509. return newGamepad;
  49510. };
  49511. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  49512. // Remove the gamepad from the list of gamepads to monitor.
  49513. for (var i in this.babylonGamepads) {
  49514. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  49515. this.babylonGamepads.splice(+i, 1);
  49516. break;
  49517. }
  49518. }
  49519. // If no gamepads are left, stop the polling loop.
  49520. if (this.babylonGamepads.length == 0) {
  49521. this._stopMonitoringGamepads();
  49522. }
  49523. };
  49524. Gamepads.prototype._startMonitoringGamepads = function () {
  49525. if (!this.isMonitoring) {
  49526. this.isMonitoring = true;
  49527. this._checkGamepadsStatus();
  49528. }
  49529. };
  49530. Gamepads.prototype._stopMonitoringGamepads = function () {
  49531. this.isMonitoring = false;
  49532. };
  49533. Gamepads.prototype._checkGamepadsStatus = function () {
  49534. var _this = this;
  49535. // updating gamepad objects
  49536. this._updateGamepadObjects();
  49537. for (var i in this.babylonGamepads) {
  49538. this.babylonGamepads[i].update();
  49539. }
  49540. if (this.isMonitoring) {
  49541. if (window.requestAnimationFrame) {
  49542. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49543. }
  49544. else if (window.mozRequestAnimationFrame) {
  49545. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49546. }
  49547. else if (window.webkitRequestAnimationFrame) {
  49548. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49549. }
  49550. }
  49551. };
  49552. // This function is called only on Chrome, which does not yet support
  49553. // connection/disconnection events, but requires you to monitor
  49554. // an array for changes.
  49555. Gamepads.prototype._updateGamepadObjects = function () {
  49556. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49557. for (var i = 0; i < gamepads.length; i++) {
  49558. if (gamepads[i]) {
  49559. if (!(gamepads[i].index in this.babylonGamepads)) {
  49560. var newGamepad = this._addNewGamepad(gamepads[i]);
  49561. if (this._callbackGamepadConnected) {
  49562. this._callbackGamepadConnected(newGamepad);
  49563. }
  49564. }
  49565. else {
  49566. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49567. }
  49568. }
  49569. }
  49570. };
  49571. return Gamepads;
  49572. }());
  49573. BABYLON.Gamepads = Gamepads;
  49574. var StickValues = (function () {
  49575. function StickValues(x, y) {
  49576. this.x = x;
  49577. this.y = y;
  49578. }
  49579. return StickValues;
  49580. }());
  49581. BABYLON.StickValues = StickValues;
  49582. var Gamepad = (function () {
  49583. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49584. if (leftStickX === void 0) { leftStickX = 0; }
  49585. if (leftStickY === void 0) { leftStickY = 1; }
  49586. if (rightStickX === void 0) { rightStickX = 2; }
  49587. if (rightStickY === void 0) { rightStickY = 3; }
  49588. this.id = id;
  49589. this.index = index;
  49590. this.browserGamepad = browserGamepad;
  49591. this._leftStickAxisX = leftStickX;
  49592. this._leftStickAxisY = leftStickY;
  49593. this._rightStickAxisX = rightStickX;
  49594. this._rightStickAxisY = rightStickY;
  49595. if (this.browserGamepad.axes.length >= 2) {
  49596. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49597. }
  49598. if (this.browserGamepad.axes.length >= 4) {
  49599. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49600. }
  49601. }
  49602. Gamepad.prototype.onleftstickchanged = function (callback) {
  49603. this._onleftstickchanged = callback;
  49604. };
  49605. Gamepad.prototype.onrightstickchanged = function (callback) {
  49606. this._onrightstickchanged = callback;
  49607. };
  49608. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49609. get: function () {
  49610. return this._leftStick;
  49611. },
  49612. set: function (newValues) {
  49613. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49614. this._onleftstickchanged(newValues);
  49615. }
  49616. this._leftStick = newValues;
  49617. },
  49618. enumerable: true,
  49619. configurable: true
  49620. });
  49621. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49622. get: function () {
  49623. return this._rightStick;
  49624. },
  49625. set: function (newValues) {
  49626. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49627. this._onrightstickchanged(newValues);
  49628. }
  49629. this._rightStick = newValues;
  49630. },
  49631. enumerable: true,
  49632. configurable: true
  49633. });
  49634. Gamepad.prototype.update = function () {
  49635. if (this._leftStick) {
  49636. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49637. }
  49638. if (this._rightStick) {
  49639. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49640. }
  49641. };
  49642. return Gamepad;
  49643. }());
  49644. BABYLON.Gamepad = Gamepad;
  49645. var GenericPad = (function (_super) {
  49646. __extends(GenericPad, _super);
  49647. function GenericPad(id, index, gamepad) {
  49648. var _this = _super.call(this, id, index, gamepad) || this;
  49649. _this.id = id;
  49650. _this.index = index;
  49651. _this.gamepad = gamepad;
  49652. _this._buttons = new Array(gamepad.buttons.length);
  49653. return _this;
  49654. }
  49655. GenericPad.prototype.onbuttondown = function (callback) {
  49656. this._onbuttondown = callback;
  49657. };
  49658. GenericPad.prototype.onbuttonup = function (callback) {
  49659. this._onbuttonup = callback;
  49660. };
  49661. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49662. if (newValue !== currentValue) {
  49663. if (this._onbuttondown && newValue === 1) {
  49664. this._onbuttondown(buttonIndex);
  49665. }
  49666. if (this._onbuttonup && newValue === 0) {
  49667. this._onbuttonup(buttonIndex);
  49668. }
  49669. }
  49670. return newValue;
  49671. };
  49672. GenericPad.prototype.update = function () {
  49673. _super.prototype.update.call(this);
  49674. for (var index = 0; index < this._buttons.length; index++) {
  49675. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  49676. }
  49677. };
  49678. return GenericPad;
  49679. }(Gamepad));
  49680. BABYLON.GenericPad = GenericPad;
  49681. var Xbox360Button;
  49682. (function (Xbox360Button) {
  49683. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49684. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49685. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49686. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49687. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49688. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49689. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49690. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49691. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49692. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49693. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49694. var Xbox360Dpad;
  49695. (function (Xbox360Dpad) {
  49696. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49697. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49698. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49699. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49700. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49701. var Xbox360Pad = (function (_super) {
  49702. __extends(Xbox360Pad, _super);
  49703. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49704. if (xboxOne === void 0) { xboxOne = false; }
  49705. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49706. _this._leftTrigger = 0;
  49707. _this._rightTrigger = 0;
  49708. _this._buttonA = 0;
  49709. _this._buttonB = 0;
  49710. _this._buttonX = 0;
  49711. _this._buttonY = 0;
  49712. _this._buttonBack = 0;
  49713. _this._buttonStart = 0;
  49714. _this._buttonLB = 0;
  49715. _this._buttonRB = 0;
  49716. _this._buttonLeftStick = 0;
  49717. _this._buttonRightStick = 0;
  49718. _this._dPadUp = 0;
  49719. _this._dPadDown = 0;
  49720. _this._dPadLeft = 0;
  49721. _this._dPadRight = 0;
  49722. _this._isXboxOnePad = false;
  49723. _this._isXboxOnePad = xboxOne;
  49724. return _this;
  49725. }
  49726. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49727. this._onlefttriggerchanged = callback;
  49728. };
  49729. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49730. this._onrighttriggerchanged = callback;
  49731. };
  49732. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49733. get: function () {
  49734. return this._leftTrigger;
  49735. },
  49736. set: function (newValue) {
  49737. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49738. this._onlefttriggerchanged(newValue);
  49739. }
  49740. this._leftTrigger = newValue;
  49741. },
  49742. enumerable: true,
  49743. configurable: true
  49744. });
  49745. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49746. get: function () {
  49747. return this._rightTrigger;
  49748. },
  49749. set: function (newValue) {
  49750. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49751. this._onrighttriggerchanged(newValue);
  49752. }
  49753. this._rightTrigger = newValue;
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49759. this._onbuttondown = callback;
  49760. };
  49761. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49762. this._onbuttonup = callback;
  49763. };
  49764. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49765. this._ondpaddown = callback;
  49766. };
  49767. Xbox360Pad.prototype.ondpadup = function (callback) {
  49768. this._ondpadup = callback;
  49769. };
  49770. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49771. if (newValue !== currentValue) {
  49772. if (this._onbuttondown && newValue === 1) {
  49773. this._onbuttondown(buttonType);
  49774. }
  49775. if (this._onbuttonup && newValue === 0) {
  49776. this._onbuttonup(buttonType);
  49777. }
  49778. }
  49779. return newValue;
  49780. };
  49781. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49782. if (newValue !== currentValue) {
  49783. if (this._ondpaddown && newValue === 1) {
  49784. this._ondpaddown(buttonType);
  49785. }
  49786. if (this._ondpadup && newValue === 0) {
  49787. this._ondpadup(buttonType);
  49788. }
  49789. }
  49790. return newValue;
  49791. };
  49792. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49793. get: function () {
  49794. return this._buttonA;
  49795. },
  49796. set: function (value) {
  49797. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49798. },
  49799. enumerable: true,
  49800. configurable: true
  49801. });
  49802. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  49803. get: function () {
  49804. return this._buttonB;
  49805. },
  49806. set: function (value) {
  49807. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  49808. },
  49809. enumerable: true,
  49810. configurable: true
  49811. });
  49812. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  49813. get: function () {
  49814. return this._buttonX;
  49815. },
  49816. set: function (value) {
  49817. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  49818. },
  49819. enumerable: true,
  49820. configurable: true
  49821. });
  49822. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  49823. get: function () {
  49824. return this._buttonY;
  49825. },
  49826. set: function (value) {
  49827. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  49828. },
  49829. enumerable: true,
  49830. configurable: true
  49831. });
  49832. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  49833. get: function () {
  49834. return this._buttonStart;
  49835. },
  49836. set: function (value) {
  49837. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  49838. },
  49839. enumerable: true,
  49840. configurable: true
  49841. });
  49842. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  49843. get: function () {
  49844. return this._buttonBack;
  49845. },
  49846. set: function (value) {
  49847. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  49848. },
  49849. enumerable: true,
  49850. configurable: true
  49851. });
  49852. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  49853. get: function () {
  49854. return this._buttonLB;
  49855. },
  49856. set: function (value) {
  49857. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  49858. },
  49859. enumerable: true,
  49860. configurable: true
  49861. });
  49862. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  49863. get: function () {
  49864. return this._buttonRB;
  49865. },
  49866. set: function (value) {
  49867. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49868. },
  49869. enumerable: true,
  49870. configurable: true
  49871. });
  49872. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49873. get: function () {
  49874. return this._buttonLeftStick;
  49875. },
  49876. set: function (value) {
  49877. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49878. },
  49879. enumerable: true,
  49880. configurable: true
  49881. });
  49882. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49883. get: function () {
  49884. return this._buttonRightStick;
  49885. },
  49886. set: function (value) {
  49887. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49888. },
  49889. enumerable: true,
  49890. configurable: true
  49891. });
  49892. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49893. get: function () {
  49894. return this._dPadUp;
  49895. },
  49896. set: function (value) {
  49897. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49898. },
  49899. enumerable: true,
  49900. configurable: true
  49901. });
  49902. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49903. get: function () {
  49904. return this._dPadDown;
  49905. },
  49906. set: function (value) {
  49907. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49908. },
  49909. enumerable: true,
  49910. configurable: true
  49911. });
  49912. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49913. get: function () {
  49914. return this._dPadLeft;
  49915. },
  49916. set: function (value) {
  49917. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49918. },
  49919. enumerable: true,
  49920. configurable: true
  49921. });
  49922. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49923. get: function () {
  49924. return this._dPadRight;
  49925. },
  49926. set: function (value) {
  49927. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49928. },
  49929. enumerable: true,
  49930. configurable: true
  49931. });
  49932. Xbox360Pad.prototype.update = function () {
  49933. _super.prototype.update.call(this);
  49934. if (this._isXboxOnePad) {
  49935. this.buttonA = this.browserGamepad.buttons[0].value;
  49936. this.buttonB = this.browserGamepad.buttons[1].value;
  49937. this.buttonX = this.browserGamepad.buttons[2].value;
  49938. this.buttonY = this.browserGamepad.buttons[3].value;
  49939. this.buttonLB = this.browserGamepad.buttons[4].value;
  49940. this.buttonRB = this.browserGamepad.buttons[5].value;
  49941. this.leftTrigger = this.browserGamepad.axes[2];
  49942. this.rightTrigger = this.browserGamepad.axes[5];
  49943. this.buttonBack = this.browserGamepad.buttons[9].value;
  49944. this.buttonStart = this.browserGamepad.buttons[8].value;
  49945. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  49946. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  49947. this.dPadUp = this.browserGamepad.buttons[11].value;
  49948. this.dPadDown = this.browserGamepad.buttons[12].value;
  49949. this.dPadLeft = this.browserGamepad.buttons[13].value;
  49950. this.dPadRight = this.browserGamepad.buttons[14].value;
  49951. }
  49952. else {
  49953. this.buttonA = this.browserGamepad.buttons[0].value;
  49954. this.buttonB = this.browserGamepad.buttons[1].value;
  49955. this.buttonX = this.browserGamepad.buttons[2].value;
  49956. this.buttonY = this.browserGamepad.buttons[3].value;
  49957. this.buttonLB = this.browserGamepad.buttons[4].value;
  49958. this.buttonRB = this.browserGamepad.buttons[5].value;
  49959. this.leftTrigger = this.browserGamepad.buttons[6].value;
  49960. this.rightTrigger = this.browserGamepad.buttons[7].value;
  49961. this.buttonBack = this.browserGamepad.buttons[8].value;
  49962. this.buttonStart = this.browserGamepad.buttons[9].value;
  49963. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  49964. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  49965. this.dPadUp = this.browserGamepad.buttons[12].value;
  49966. this.dPadDown = this.browserGamepad.buttons[13].value;
  49967. this.dPadLeft = this.browserGamepad.buttons[14].value;
  49968. this.dPadRight = this.browserGamepad.buttons[15].value;
  49969. }
  49970. };
  49971. return Xbox360Pad;
  49972. }(Gamepad));
  49973. BABYLON.Xbox360Pad = Xbox360Pad;
  49974. })(BABYLON || (BABYLON = {}));
  49975. //# sourceMappingURL=babylon.gamepads.js.map
  49976. /// <reference path="babylon.universalCamera.ts" />
  49977. var BABYLON;
  49978. (function (BABYLON) {
  49979. // We're mainly based on the logic defined into the FreeCamera code
  49980. var GamepadCamera = (function (_super) {
  49981. __extends(GamepadCamera, _super);
  49982. //-- end properties for backward compatibility for inputs
  49983. function GamepadCamera(name, position, scene) {
  49984. var _this;
  49985. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  49986. _this = _super.call(this, name, position, scene) || this;
  49987. return _this;
  49988. }
  49989. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  49990. //-- Begin properties for backward compatibility for inputs
  49991. get: function () {
  49992. var gamepad = this.inputs.attached["gamepad"];
  49993. if (gamepad)
  49994. return gamepad.gamepadAngularSensibility;
  49995. },
  49996. set: function (value) {
  49997. var gamepad = this.inputs.attached["gamepad"];
  49998. if (gamepad)
  49999. gamepad.gamepadAngularSensibility = value;
  50000. },
  50001. enumerable: true,
  50002. configurable: true
  50003. });
  50004. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50005. get: function () {
  50006. var gamepad = this.inputs.attached["gamepad"];
  50007. if (gamepad)
  50008. return gamepad.gamepadMoveSensibility;
  50009. },
  50010. set: function (value) {
  50011. var gamepad = this.inputs.attached["gamepad"];
  50012. if (gamepad)
  50013. gamepad.gamepadMoveSensibility = value;
  50014. },
  50015. enumerable: true,
  50016. configurable: true
  50017. });
  50018. GamepadCamera.prototype.getClassName = function () {
  50019. return "GamepadCamera";
  50020. };
  50021. return GamepadCamera;
  50022. }(BABYLON.UniversalCamera));
  50023. BABYLON.GamepadCamera = GamepadCamera;
  50024. })(BABYLON || (BABYLON = {}));
  50025. //# sourceMappingURL=babylon.gamepadCamera.js.map
  50026. var BABYLON;
  50027. (function (BABYLON) {
  50028. var Analyser = (function () {
  50029. function Analyser(scene) {
  50030. this.SMOOTHING = 0.75;
  50031. this.FFT_SIZE = 512;
  50032. this.BARGRAPHAMPLITUDE = 256;
  50033. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50034. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50035. this._scene = scene;
  50036. this._audioEngine = BABYLON.Engine.audioEngine;
  50037. if (this._audioEngine.canUseWebAudio) {
  50038. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50039. this._webAudioAnalyser.minDecibels = -140;
  50040. this._webAudioAnalyser.maxDecibels = 0;
  50041. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50042. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50043. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50044. }
  50045. }
  50046. Analyser.prototype.getFrequencyBinCount = function () {
  50047. if (this._audioEngine.canUseWebAudio) {
  50048. return this._webAudioAnalyser.frequencyBinCount;
  50049. }
  50050. else {
  50051. return 0;
  50052. }
  50053. };
  50054. Analyser.prototype.getByteFrequencyData = function () {
  50055. if (this._audioEngine.canUseWebAudio) {
  50056. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50057. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50058. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50059. }
  50060. return this._byteFreqs;
  50061. };
  50062. Analyser.prototype.getByteTimeDomainData = function () {
  50063. if (this._audioEngine.canUseWebAudio) {
  50064. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50065. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50066. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50067. }
  50068. return this._byteTime;
  50069. };
  50070. Analyser.prototype.getFloatFrequencyData = function () {
  50071. if (this._audioEngine.canUseWebAudio) {
  50072. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50073. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50074. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50075. }
  50076. return this._floatFreqs;
  50077. };
  50078. Analyser.prototype.drawDebugCanvas = function () {
  50079. var _this = this;
  50080. if (this._audioEngine.canUseWebAudio) {
  50081. if (!this._debugCanvas) {
  50082. this._debugCanvas = document.createElement("canvas");
  50083. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50084. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50085. this._debugCanvas.style.position = "absolute";
  50086. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50087. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50088. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50089. document.body.appendChild(this._debugCanvas);
  50090. this._registerFunc = function () {
  50091. _this.drawDebugCanvas();
  50092. };
  50093. this._scene.registerBeforeRender(this._registerFunc);
  50094. }
  50095. if (this._registerFunc) {
  50096. var workingArray = this.getByteFrequencyData();
  50097. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50098. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50099. // Draw the frequency domain chart.
  50100. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50101. var value = workingArray[i];
  50102. var percent = value / this.BARGRAPHAMPLITUDE;
  50103. var height = this.DEBUGCANVASSIZE.height * percent;
  50104. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50105. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50106. var hue = i / this.getFrequencyBinCount() * 360;
  50107. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50108. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50109. }
  50110. }
  50111. }
  50112. };
  50113. Analyser.prototype.stopDebugCanvas = function () {
  50114. if (this._debugCanvas) {
  50115. this._scene.unregisterBeforeRender(this._registerFunc);
  50116. this._registerFunc = null;
  50117. document.body.removeChild(this._debugCanvas);
  50118. this._debugCanvas = null;
  50119. this._debugCanvasContext = null;
  50120. }
  50121. };
  50122. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50123. if (this._audioEngine.canUseWebAudio) {
  50124. inputAudioNode.connect(this._webAudioAnalyser);
  50125. this._webAudioAnalyser.connect(outputAudioNode);
  50126. }
  50127. };
  50128. Analyser.prototype.dispose = function () {
  50129. if (this._audioEngine.canUseWebAudio) {
  50130. this._webAudioAnalyser.disconnect();
  50131. }
  50132. };
  50133. return Analyser;
  50134. }());
  50135. BABYLON.Analyser = Analyser;
  50136. })(BABYLON || (BABYLON = {}));
  50137. //# sourceMappingURL=babylon.analyser.js.map
  50138. var BABYLON;
  50139. (function (BABYLON) {
  50140. var DepthRenderer = (function () {
  50141. function DepthRenderer(scene, type) {
  50142. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  50143. var _this = this;
  50144. this._viewMatrix = BABYLON.Matrix.Zero();
  50145. this._projectionMatrix = BABYLON.Matrix.Zero();
  50146. this._transformMatrix = BABYLON.Matrix.Zero();
  50147. this._worldViewProjection = BABYLON.Matrix.Zero();
  50148. this._scene = scene;
  50149. var engine = scene.getEngine();
  50150. // Render target
  50151. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  50152. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50153. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50154. this._depthMap.refreshRate = 1;
  50155. this._depthMap.renderParticles = false;
  50156. this._depthMap.renderList = null;
  50157. // set default depth value to 1.0 (far away)
  50158. this._depthMap.onClearObservable.add(function (engine) {
  50159. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50160. });
  50161. // Custom render function
  50162. var renderSubMesh = function (subMesh) {
  50163. var mesh = subMesh.getRenderingMesh();
  50164. var scene = _this._scene;
  50165. var engine = scene.getEngine();
  50166. // Culling
  50167. engine.setState(subMesh.getMaterial().backFaceCulling);
  50168. // Managing instances
  50169. var batch = mesh._getInstancesRenderList(subMesh._id);
  50170. if (batch.mustReturn) {
  50171. return;
  50172. }
  50173. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50174. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50175. engine.enableEffect(_this._effect);
  50176. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50177. var material = subMesh.getMaterial();
  50178. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50179. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  50180. // Alpha test
  50181. if (material && material.needAlphaTesting()) {
  50182. var alphaTexture = material.getAlphaTestTexture();
  50183. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50184. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50185. }
  50186. // Bones
  50187. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50188. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50189. }
  50190. // Draw
  50191. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50192. }
  50193. };
  50194. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50195. var index;
  50196. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50197. renderSubMesh(opaqueSubMeshes.data[index]);
  50198. }
  50199. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50200. renderSubMesh(alphaTestSubMeshes.data[index]);
  50201. }
  50202. };
  50203. }
  50204. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  50205. var material = subMesh.getMaterial();
  50206. if (material.disableDepthWrite) {
  50207. return false;
  50208. }
  50209. var defines = [];
  50210. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50211. var mesh = subMesh.getMesh();
  50212. var scene = mesh.getScene();
  50213. // Alpha test
  50214. if (material && material.needAlphaTesting()) {
  50215. defines.push("#define ALPHATEST");
  50216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50217. attribs.push(BABYLON.VertexBuffer.UVKind);
  50218. defines.push("#define UV1");
  50219. }
  50220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50221. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50222. defines.push("#define UV2");
  50223. }
  50224. }
  50225. // Bones
  50226. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50227. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50228. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50229. if (mesh.numBoneInfluencers > 4) {
  50230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50232. }
  50233. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50234. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50235. }
  50236. else {
  50237. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50238. }
  50239. // Instances
  50240. if (useInstances) {
  50241. defines.push("#define INSTANCES");
  50242. attribs.push("world0");
  50243. attribs.push("world1");
  50244. attribs.push("world2");
  50245. attribs.push("world3");
  50246. }
  50247. // Get correct effect
  50248. var join = defines.join("\n");
  50249. if (this._cachedDefines !== join) {
  50250. this._cachedDefines = join;
  50251. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  50252. }
  50253. return this._effect.isReady();
  50254. };
  50255. DepthRenderer.prototype.getDepthMap = function () {
  50256. return this._depthMap;
  50257. };
  50258. // Methods
  50259. DepthRenderer.prototype.dispose = function () {
  50260. this._depthMap.dispose();
  50261. };
  50262. return DepthRenderer;
  50263. }());
  50264. BABYLON.DepthRenderer = DepthRenderer;
  50265. })(BABYLON || (BABYLON = {}));
  50266. //# sourceMappingURL=babylon.depthRenderer.js.map
  50267. var BABYLON;
  50268. (function (BABYLON) {
  50269. var SSAORenderingPipeline = (function (_super) {
  50270. __extends(SSAORenderingPipeline, _super);
  50271. /**
  50272. * @constructor
  50273. * @param {string} name - The rendering pipeline name
  50274. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50275. * @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 }
  50276. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50277. */
  50278. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  50279. var _this = _super.call(this, scene.getEngine(), name) || this;
  50280. // Members
  50281. /**
  50282. * The PassPostProcess id in the pipeline that contains the original scene color
  50283. * @type {string}
  50284. */
  50285. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50286. /**
  50287. * The SSAO PostProcess id in the pipeline
  50288. * @type {string}
  50289. */
  50290. _this.SSAORenderEffect = "SSAORenderEffect";
  50291. /**
  50292. * The horizontal blur PostProcess id in the pipeline
  50293. * @type {string}
  50294. */
  50295. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50296. /**
  50297. * The vertical blur PostProcess id in the pipeline
  50298. * @type {string}
  50299. */
  50300. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50301. /**
  50302. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50303. * @type {string}
  50304. */
  50305. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50306. /**
  50307. * The output strength of the SSAO post-process. Default value is 1.0.
  50308. * @type {number}
  50309. */
  50310. _this.totalStrength = 1.0;
  50311. /**
  50312. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  50313. * @type {number}
  50314. */
  50315. _this.radius = 0.0001;
  50316. /**
  50317. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  50318. * Must not be equal to fallOff and superior to fallOff.
  50319. * Default value is 0.975
  50320. * @type {number}
  50321. */
  50322. _this.area = 0.0075;
  50323. /**
  50324. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  50325. * Must not be equal to area and inferior to area.
  50326. * Default value is 0.0
  50327. * @type {number}
  50328. */
  50329. _this.fallOff = 0.000001;
  50330. /**
  50331. * The base color of the SSAO post-process
  50332. * The final result is "base + ssao" between [0, 1]
  50333. * @type {number}
  50334. */
  50335. _this.base = 0.5;
  50336. _this._firstUpdate = true;
  50337. _this._scene = scene;
  50338. // Set up assets
  50339. _this._createRandomTexture();
  50340. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50341. var ssaoRatio = ratio.ssaoRatio || ratio;
  50342. var combineRatio = ratio.combineRatio || ratio;
  50343. _this._ratio = {
  50344. ssaoRatio: ssaoRatio,
  50345. combineRatio: combineRatio
  50346. };
  50347. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50348. _this._createSSAOPostProcess(ssaoRatio);
  50349. _this._createBlurPostProcess(ssaoRatio);
  50350. _this._createSSAOCombinePostProcess(combineRatio);
  50351. // Set up pipeline
  50352. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50353. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50357. // Finish
  50358. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50359. if (cameras)
  50360. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50361. return _this;
  50362. }
  50363. // Public Methods
  50364. /**
  50365. * Returns the horizontal blur PostProcess
  50366. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  50367. */
  50368. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  50369. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  50370. return null;
  50371. };
  50372. /**
  50373. * Returns the vertical blur PostProcess
  50374. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  50375. */
  50376. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  50377. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  50378. return null;
  50379. };
  50380. /**
  50381. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50382. */
  50383. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50384. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50385. for (var i = 0; i < this._scene.cameras.length; i++) {
  50386. var camera = this._scene.cameras[i];
  50387. this._originalColorPostProcess.dispose(camera);
  50388. this._ssaoPostProcess.dispose(camera);
  50389. this._blurHPostProcess.dispose(camera);
  50390. this._blurVPostProcess.dispose(camera);
  50391. this._ssaoCombinePostProcess.dispose(camera);
  50392. }
  50393. this._randomTexture.dispose();
  50394. if (disableDepthRender)
  50395. this._scene.disableDepthRenderer();
  50396. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50397. _super.prototype.dispose.call(this);
  50398. };
  50399. // Private Methods
  50400. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  50401. var _this = this;
  50402. /*
  50403. var samplerOffsets = [
  50404. -8.0, -6.0, -4.0, -2.0,
  50405. 0.0,
  50406. 2.0, 4.0, 6.0, 8.0
  50407. ];
  50408. */
  50409. var samples = 16;
  50410. var samplerOffsets = [];
  50411. for (var i = -8; i < 8; i++) {
  50412. samplerOffsets.push(i * 2);
  50413. }
  50414. 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");
  50415. this._blurHPostProcess.onApply = function (effect) {
  50416. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50417. effect.setTexture("depthSampler", _this._depthTexture);
  50418. if (_this._firstUpdate) {
  50419. effect.setArray("samplerOffsets", samplerOffsets);
  50420. }
  50421. };
  50422. 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");
  50423. this._blurVPostProcess.onApply = function (effect) {
  50424. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50425. effect.setTexture("depthSampler", _this._depthTexture);
  50426. if (_this._firstUpdate) {
  50427. effect.setArray("samplerOffsets", samplerOffsets);
  50428. _this._firstUpdate = false;
  50429. }
  50430. };
  50431. };
  50432. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50433. var _this = this;
  50434. var numSamples = 16;
  50435. var sampleSphere = [
  50436. 0.5381, 0.1856, -0.4319,
  50437. 0.1379, 0.2486, 0.4430,
  50438. 0.3371, 0.5679, -0.0057,
  50439. -0.6999, -0.0451, -0.0019,
  50440. 0.0689, -0.1598, -0.8547,
  50441. 0.0560, 0.0069, -0.1843,
  50442. -0.0146, 0.1402, 0.0762,
  50443. 0.0100, -0.1924, -0.0344,
  50444. -0.3577, -0.5301, -0.4358,
  50445. -0.3169, 0.1063, 0.0158,
  50446. 0.0103, -0.5869, 0.0046,
  50447. -0.0897, -0.4940, 0.3287,
  50448. 0.7119, -0.0154, -0.0918,
  50449. -0.0533, 0.0596, -0.5411,
  50450. 0.0352, -0.0631, 0.5460,
  50451. -0.4776, 0.2847, -0.0271
  50452. ];
  50453. var samplesFactor = 1.0 / numSamples;
  50454. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  50455. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50456. "area", "fallOff", "base", "range", "viewport"
  50457. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50458. var viewport = new BABYLON.Vector2(0, 0);
  50459. this._ssaoPostProcess.onApply = function (effect) {
  50460. if (_this._firstUpdate) {
  50461. effect.setArray3("sampleSphere", sampleSphere);
  50462. effect.setFloat("samplesFactor", samplesFactor);
  50463. effect.setFloat("randTextureTiles", 4.0);
  50464. }
  50465. effect.setFloat("totalStrength", _this.totalStrength);
  50466. effect.setFloat("radius", _this.radius);
  50467. effect.setFloat("area", _this.area);
  50468. effect.setFloat("fallOff", _this.fallOff);
  50469. effect.setFloat("base", _this.base);
  50470. effect.setTexture("textureSampler", _this._depthTexture);
  50471. effect.setTexture("randomSampler", _this._randomTexture);
  50472. };
  50473. };
  50474. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50475. var _this = this;
  50476. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50477. this._ssaoCombinePostProcess.onApply = function (effect) {
  50478. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50479. };
  50480. };
  50481. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  50482. var size = 512;
  50483. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50484. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50485. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50486. var context = this._randomTexture.getContext();
  50487. var rand = function (min, max) {
  50488. return Math.random() * (max - min) + min;
  50489. };
  50490. var randVector = BABYLON.Vector3.Zero();
  50491. for (var x = 0; x < size; x++) {
  50492. for (var y = 0; y < size; y++) {
  50493. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  50494. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  50495. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  50496. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50497. context.fillRect(x, y, 1, 1);
  50498. }
  50499. }
  50500. this._randomTexture.update(false);
  50501. };
  50502. return SSAORenderingPipeline;
  50503. }(BABYLON.PostProcessRenderPipeline));
  50504. __decorate([
  50505. BABYLON.serialize()
  50506. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  50507. __decorate([
  50508. BABYLON.serialize()
  50509. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50510. __decorate([
  50511. BABYLON.serialize()
  50512. ], SSAORenderingPipeline.prototype, "area", void 0);
  50513. __decorate([
  50514. BABYLON.serialize()
  50515. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50516. __decorate([
  50517. BABYLON.serialize()
  50518. ], SSAORenderingPipeline.prototype, "base", void 0);
  50519. __decorate([
  50520. BABYLON.serialize()
  50521. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50522. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50523. })(BABYLON || (BABYLON = {}));
  50524. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50525. var BABYLON;
  50526. (function (BABYLON) {
  50527. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  50528. var VolumetricLightScatteringPostProcess = (function (_super) {
  50529. __extends(VolumetricLightScatteringPostProcess, _super);
  50530. /**
  50531. * @constructor
  50532. * @param {string} name - The post-process name
  50533. * @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)
  50534. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  50535. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  50536. * @param {number} samples - The post-process quality, default 100
  50537. * @param {number} samplingMode - The post-process filtering mode
  50538. * @param {BABYLON.Engine} engine - The babylon engine
  50539. * @param {boolean} reusable - If the post-process is reusable
  50540. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  50541. */
  50542. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  50543. if (samples === void 0) { samples = 100; }
  50544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50545. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  50546. _this._screenCoordinates = BABYLON.Vector2.Zero();
  50547. /**
  50548. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  50549. * @type {Vector3}
  50550. */
  50551. _this.customMeshPosition = BABYLON.Vector3.Zero();
  50552. /**
  50553. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  50554. * @type {boolean}
  50555. */
  50556. _this.useCustomMeshPosition = false;
  50557. /**
  50558. * If the post-process should inverse the light scattering direction
  50559. * @type {boolean}
  50560. */
  50561. _this.invert = true;
  50562. /**
  50563. * Array containing the excluded meshes not rendered in the internal pass
  50564. */
  50565. _this.excludedMeshes = new Array();
  50566. /**
  50567. * Controls the overall intensity of the post-process
  50568. * @type {number}
  50569. */
  50570. _this.exposure = 0.3;
  50571. /**
  50572. * Dissipates each sample's contribution in range [0, 1]
  50573. * @type {number}
  50574. */
  50575. _this.decay = 0.96815;
  50576. /**
  50577. * Controls the overall intensity of each sample
  50578. * @type {number}
  50579. */
  50580. _this.weight = 0.58767;
  50581. /**
  50582. * Controls the density of each sample
  50583. * @type {number}
  50584. */
  50585. _this.density = 0.926;
  50586. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  50587. var engine = scene.getEngine();
  50588. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  50589. // Configure mesh
  50590. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  50591. // Configure
  50592. _this._createPass(scene, ratio.passRatio || ratio);
  50593. _this.onActivate = function (camera) {
  50594. if (!_this.isSupported) {
  50595. _this.dispose(camera);
  50596. }
  50597. _this.onActivate = null;
  50598. };
  50599. _this.onApplyObservable.add(function (effect) {
  50600. _this._updateMeshScreenCoordinates(scene);
  50601. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  50602. effect.setFloat("exposure", _this.exposure);
  50603. effect.setFloat("decay", _this.decay);
  50604. effect.setFloat("weight", _this.weight);
  50605. effect.setFloat("density", _this.density);
  50606. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  50607. });
  50608. return _this;
  50609. }
  50610. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  50611. get: function () {
  50612. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50613. return false;
  50614. },
  50615. set: function (useDiffuseColor) {
  50616. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50617. },
  50618. enumerable: true,
  50619. configurable: true
  50620. });
  50621. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  50622. var mesh = subMesh.getMesh();
  50623. // Render this.mesh as default
  50624. if (mesh === this.mesh) {
  50625. return mesh.material.isReady(mesh);
  50626. }
  50627. var defines = [];
  50628. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50629. var material = subMesh.getMaterial();
  50630. var needUV = false;
  50631. // Alpha test
  50632. if (material) {
  50633. if (material.needAlphaTesting()) {
  50634. defines.push("#define ALPHATEST");
  50635. }
  50636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50637. attribs.push(BABYLON.VertexBuffer.UVKind);
  50638. defines.push("#define UV1");
  50639. }
  50640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50641. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50642. defines.push("#define UV2");
  50643. }
  50644. }
  50645. // Bones
  50646. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50649. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50650. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50651. }
  50652. else {
  50653. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50654. }
  50655. // Instances
  50656. if (useInstances) {
  50657. defines.push("#define INSTANCES");
  50658. attribs.push("world0");
  50659. attribs.push("world1");
  50660. attribs.push("world2");
  50661. attribs.push("world3");
  50662. }
  50663. // Get correct effect
  50664. var join = defines.join("\n");
  50665. if (this._cachedDefines !== join) {
  50666. this._cachedDefines = join;
  50667. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  50668. }
  50669. return this._volumetricLightScatteringPass.isReady();
  50670. };
  50671. /**
  50672. * Sets the new light position for light scattering effect
  50673. * @param {BABYLON.Vector3} The new custom light position
  50674. */
  50675. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  50676. this.customMeshPosition = position;
  50677. };
  50678. /**
  50679. * Returns the light position for light scattering effect
  50680. * @return {BABYLON.Vector3} The custom light position
  50681. */
  50682. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  50683. return this.customMeshPosition;
  50684. };
  50685. /**
  50686. * Disposes the internal assets and detaches the post-process from the camera
  50687. */
  50688. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  50689. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  50690. if (rttIndex !== -1) {
  50691. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  50692. }
  50693. this._volumetricLightScatteringRTT.dispose();
  50694. _super.prototype.dispose.call(this, camera);
  50695. };
  50696. /**
  50697. * Returns the render target texture used by the post-process
  50698. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  50699. */
  50700. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  50701. return this._volumetricLightScatteringRTT;
  50702. };
  50703. // Private methods
  50704. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  50705. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  50706. return true;
  50707. }
  50708. return false;
  50709. };
  50710. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  50711. var _this = this;
  50712. var engine = scene.getEngine();
  50713. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50714. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50715. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50716. this._volumetricLightScatteringRTT.renderList = null;
  50717. this._volumetricLightScatteringRTT.renderParticles = false;
  50718. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  50719. // Custom render function for submeshes
  50720. var renderSubMesh = function (subMesh) {
  50721. var mesh = subMesh.getRenderingMesh();
  50722. if (_this._meshExcluded(mesh)) {
  50723. return;
  50724. }
  50725. var scene = mesh.getScene();
  50726. var engine = scene.getEngine();
  50727. // Culling
  50728. engine.setState(subMesh.getMaterial().backFaceCulling);
  50729. // Managing instances
  50730. var batch = mesh._getInstancesRenderList(subMesh._id);
  50731. if (batch.mustReturn) {
  50732. return;
  50733. }
  50734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50735. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50736. var effect = _this._volumetricLightScatteringPass;
  50737. if (mesh === _this.mesh) {
  50738. effect = subMesh.getMaterial().getEffect();
  50739. }
  50740. engine.enableEffect(effect);
  50741. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  50742. if (mesh === _this.mesh) {
  50743. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  50744. }
  50745. else {
  50746. var material = subMesh.getMaterial();
  50747. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  50748. // Alpha test
  50749. if (material && material.needAlphaTesting()) {
  50750. var alphaTexture = material.getAlphaTestTexture();
  50751. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  50752. if (alphaTexture) {
  50753. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50754. }
  50755. }
  50756. // Bones
  50757. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50758. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50759. }
  50760. }
  50761. // Draw
  50762. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  50763. }
  50764. };
  50765. // Render target texture callbacks
  50766. var savedSceneClearColor;
  50767. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  50768. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  50769. savedSceneClearColor = scene.clearColor;
  50770. scene.clearColor = sceneClearColor;
  50771. });
  50772. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  50773. scene.clearColor = savedSceneClearColor;
  50774. });
  50775. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  50776. var engine = scene.getEngine();
  50777. var index;
  50778. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50779. renderSubMesh(opaqueSubMeshes.data[index]);
  50780. }
  50781. engine.setAlphaTesting(true);
  50782. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50783. renderSubMesh(alphaTestSubMeshes.data[index]);
  50784. }
  50785. engine.setAlphaTesting(false);
  50786. if (transparentSubMeshes.length) {
  50787. // Sort sub meshes
  50788. for (index = 0; index < transparentSubMeshes.length; index++) {
  50789. var submesh = transparentSubMeshes.data[index];
  50790. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  50791. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  50792. }
  50793. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  50794. sortedArray.sort(function (a, b) {
  50795. // Alpha index first
  50796. if (a._alphaIndex > b._alphaIndex) {
  50797. return 1;
  50798. }
  50799. if (a._alphaIndex < b._alphaIndex) {
  50800. return -1;
  50801. }
  50802. // Then distance to camera
  50803. if (a._distanceToCamera < b._distanceToCamera) {
  50804. return 1;
  50805. }
  50806. if (a._distanceToCamera > b._distanceToCamera) {
  50807. return -1;
  50808. }
  50809. return 0;
  50810. });
  50811. // Render sub meshes
  50812. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50813. for (index = 0; index < sortedArray.length; index++) {
  50814. renderSubMesh(sortedArray[index]);
  50815. }
  50816. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50817. }
  50818. };
  50819. };
  50820. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  50821. var transform = scene.getTransformMatrix();
  50822. var meshPosition;
  50823. if (this.useCustomMeshPosition) {
  50824. meshPosition = this.customMeshPosition;
  50825. }
  50826. else if (this.attachedNode) {
  50827. meshPosition = this.attachedNode.position;
  50828. }
  50829. else {
  50830. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  50831. }
  50832. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  50833. this._screenCoordinates.x = pos.x / this._viewPort.width;
  50834. this._screenCoordinates.y = pos.y / this._viewPort.height;
  50835. if (this.invert)
  50836. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  50837. };
  50838. // Static methods
  50839. /**
  50840. * Creates a default mesh for the Volumeric Light Scattering post-process
  50841. * @param {string} The mesh name
  50842. * @param {BABYLON.Scene} The scene where to create the mesh
  50843. * @return {BABYLON.Mesh} the default mesh
  50844. */
  50845. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  50846. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  50847. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  50848. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  50849. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  50850. mesh.material = material;
  50851. return mesh;
  50852. };
  50853. return VolumetricLightScatteringPostProcess;
  50854. }(BABYLON.PostProcess));
  50855. __decorate([
  50856. BABYLON.serializeAsVector3()
  50857. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  50858. __decorate([
  50859. BABYLON.serialize()
  50860. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  50861. __decorate([
  50862. BABYLON.serialize()
  50863. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  50864. __decorate([
  50865. BABYLON.serializeAsMeshReference()
  50866. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  50867. __decorate([
  50868. BABYLON.serialize()
  50869. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  50870. __decorate([
  50871. BABYLON.serialize()
  50872. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  50873. __decorate([
  50874. BABYLON.serialize()
  50875. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  50876. __decorate([
  50877. BABYLON.serialize()
  50878. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  50879. __decorate([
  50880. BABYLON.serialize()
  50881. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  50882. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  50883. })(BABYLON || (BABYLON = {}));
  50884. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  50885. // BABYLON.JS Chromatic Aberration GLSL Shader
  50886. // Author: Olivier Guyot
  50887. // Separates very slightly R, G and B colors on the edges of the screen
  50888. // Inspired by Francois Tarlier & Martins Upitis
  50889. var BABYLON;
  50890. (function (BABYLON) {
  50891. var LensRenderingPipeline = (function (_super) {
  50892. __extends(LensRenderingPipeline, _super);
  50893. /**
  50894. * @constructor
  50895. *
  50896. * Effect parameters are as follow:
  50897. * {
  50898. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50899. * edge_blur: number; // from 0 to x (1 for realism)
  50900. * distortion: number; // from 0 to x (1 for realism)
  50901. * grain_amount: number; // from 0 to 1
  50902. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50903. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50904. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50905. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50906. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50907. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50908. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50909. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50910. * }
  50911. * Note: if an effect parameter is unset, effect is disabled
  50912. *
  50913. * @param {string} name - The rendering pipeline name
  50914. * @param {object} parameters - An object containing all parameters (see above)
  50915. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50916. * @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)
  50917. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50918. */
  50919. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50920. if (ratio === void 0) { ratio = 1.0; }
  50921. var _this = _super.call(this, scene.getEngine(), name) || this;
  50922. // Lens effects can be of the following:
  50923. // - chromatic aberration (slight shift of RGB colors)
  50924. // - blur on the edge of the lens
  50925. // - lens distortion
  50926. // - depth-of-field blur & highlights enhancing
  50927. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50928. // - grain effect (noise or custom texture)
  50929. // Two additional texture samplers are needed:
  50930. // - depth map (for depth-of-field)
  50931. // - grain texture
  50932. /**
  50933. * The chromatic aberration PostProcess id in the pipeline
  50934. * @type {string}
  50935. */
  50936. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50937. /**
  50938. * The highlights enhancing PostProcess id in the pipeline
  50939. * @type {string}
  50940. */
  50941. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  50942. /**
  50943. * The depth-of-field PostProcess id in the pipeline
  50944. * @type {string}
  50945. */
  50946. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  50947. _this._scene = scene;
  50948. // Fetch texture samplers
  50949. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50950. if (parameters.grain_texture) {
  50951. _this._grainTexture = parameters.grain_texture;
  50952. }
  50953. else {
  50954. _this._createGrainTexture();
  50955. }
  50956. // save parameters
  50957. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  50958. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  50959. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  50960. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  50961. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  50962. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  50963. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  50964. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  50965. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  50966. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  50967. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  50968. // Create effects
  50969. _this._createChromaticAberrationPostProcess(ratio);
  50970. _this._createHighlightsPostProcess(ratio);
  50971. _this._createDepthOfFieldPostProcess(ratio / 4);
  50972. // Set up pipeline
  50973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  50974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  50975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  50976. if (_this._highlightsGain === -1) {
  50977. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  50978. }
  50979. // Finish
  50980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50981. if (cameras) {
  50982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50983. }
  50984. return _this;
  50985. }
  50986. // public methods (self explanatory)
  50987. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  50988. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  50989. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  50990. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  50991. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  50992. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  50993. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  50994. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  50995. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  50996. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  50997. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  50998. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  50999. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  51000. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  51001. };
  51002. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  51003. this._highlightsPostProcess.updateEffect();
  51004. };
  51005. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  51006. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  51007. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  51008. this._highlightsGain = amount;
  51009. };
  51010. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  51011. if (this._highlightsGain === -1) {
  51012. this._highlightsGain = 1.0;
  51013. }
  51014. this._highlightsThreshold = amount;
  51015. };
  51016. LensRenderingPipeline.prototype.disableHighlights = function () {
  51017. this._highlightsGain = -1;
  51018. };
  51019. /**
  51020. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  51021. */
  51022. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51023. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51025. this._chromaticAberrationPostProcess = undefined;
  51026. this._highlightsPostProcess = undefined;
  51027. this._depthOfFieldPostProcess = undefined;
  51028. this._grainTexture.dispose();
  51029. if (disableDepthRender)
  51030. this._scene.disableDepthRenderer();
  51031. };
  51032. // colors shifting and distortion
  51033. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  51034. var _this = this;
  51035. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  51036. [], // samplers
  51037. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51038. this._chromaticAberrationPostProcess.onApply = function (effect) {
  51039. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  51040. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51041. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51042. };
  51043. };
  51044. // highlights enhancing
  51045. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  51046. var _this = this;
  51047. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  51048. [], // samplers
  51049. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  51050. this._highlightsPostProcess.onApply = function (effect) {
  51051. effect.setFloat('gain', _this._highlightsGain);
  51052. effect.setFloat('threshold', _this._highlightsThreshold);
  51053. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  51054. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51055. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51056. };
  51057. };
  51058. // colors shifting and distortion
  51059. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  51060. var _this = this;
  51061. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  51062. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  51063. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  51064. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51065. this._depthOfFieldPostProcess.onApply = function (effect) {
  51066. effect.setTexture("depthSampler", _this._depthTexture);
  51067. effect.setTexture("grainSampler", _this._grainTexture);
  51068. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  51069. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  51070. effect.setFloat('grain_amount', _this._grainAmount);
  51071. effect.setBool('blur_noise', _this._blurNoise);
  51072. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51073. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51074. effect.setFloat('distortion', _this._distortion);
  51075. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  51076. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  51077. effect.setFloat('aperture', _this._dofAperture);
  51078. effect.setFloat('darken', _this._dofDarken);
  51079. effect.setFloat('edge_blur', _this._edgeBlur);
  51080. effect.setBool('highlights', (_this._highlightsGain !== -1));
  51081. effect.setFloat('near', _this._scene.activeCamera.minZ);
  51082. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  51083. };
  51084. };
  51085. // creates a black and white random noise texture, 512x512
  51086. LensRenderingPipeline.prototype._createGrainTexture = function () {
  51087. var size = 512;
  51088. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51089. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51090. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51091. var context = this._grainTexture.getContext();
  51092. var rand = function (min, max) {
  51093. return Math.random() * (max - min) + min;
  51094. };
  51095. var value;
  51096. for (var x = 0; x < size; x++) {
  51097. for (var y = 0; y < size; y++) {
  51098. value = Math.floor(rand(0.42, 0.58) * 255);
  51099. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  51100. context.fillRect(x, y, 1, 1);
  51101. }
  51102. }
  51103. this._grainTexture.update(false);
  51104. };
  51105. return LensRenderingPipeline;
  51106. }(BABYLON.PostProcessRenderPipeline));
  51107. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  51108. })(BABYLON || (BABYLON = {}));
  51109. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  51110. //
  51111. // This post-process allows the modification of rendered colors by using
  51112. // a 'look-up table' (LUT). This effect is also called Color Grading.
  51113. //
  51114. // The object needs to be provided an url to a texture containing the color
  51115. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  51116. // Use an image editing software to tweak the LUT to match your needs.
  51117. //
  51118. // For an example of a color LUT, see here:
  51119. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  51120. // For explanations on color grading, see here:
  51121. // http://udn.epicgames.com/Three/ColorGrading.html
  51122. //
  51123. var BABYLON;
  51124. (function (BABYLON) {
  51125. var ColorCorrectionPostProcess = (function (_super) {
  51126. __extends(ColorCorrectionPostProcess, _super);
  51127. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  51128. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  51129. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51130. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  51131. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51132. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51133. _this.onApply = function (effect) {
  51134. effect.setTexture("colorTable", _this._colorTableTexture);
  51135. };
  51136. return _this;
  51137. }
  51138. return ColorCorrectionPostProcess;
  51139. }(BABYLON.PostProcess));
  51140. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  51141. })(BABYLON || (BABYLON = {}));
  51142. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  51143. /// <reference path="babylon.freeCamera.ts" />
  51144. /// <reference path="babylon.arcRotateCamera.ts" />
  51145. /// <reference path="babylon.gamepadCamera.ts" />
  51146. /// <reference path="babylon.universalCamera.ts" />
  51147. var BABYLON;
  51148. (function (BABYLON) {
  51149. var AnaglyphFreeCamera = (function (_super) {
  51150. __extends(AnaglyphFreeCamera, _super);
  51151. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  51152. var _this = _super.call(this, name, position, scene) || this;
  51153. _this.interaxialDistance = interaxialDistance;
  51154. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51155. return _this;
  51156. }
  51157. AnaglyphFreeCamera.prototype.getClassName = function () {
  51158. return "AnaglyphFreeCamera";
  51159. };
  51160. return AnaglyphFreeCamera;
  51161. }(BABYLON.FreeCamera));
  51162. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  51163. var AnaglyphArcRotateCamera = (function (_super) {
  51164. __extends(AnaglyphArcRotateCamera, _super);
  51165. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  51166. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51167. _this.interaxialDistance = interaxialDistance;
  51168. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51169. return _this;
  51170. }
  51171. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  51172. return "AnaglyphArcRotateCamera";
  51173. };
  51174. return AnaglyphArcRotateCamera;
  51175. }(BABYLON.ArcRotateCamera));
  51176. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  51177. var AnaglyphGamepadCamera = (function (_super) {
  51178. __extends(AnaglyphGamepadCamera, _super);
  51179. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  51180. var _this = _super.call(this, name, position, scene) || this;
  51181. _this.interaxialDistance = interaxialDistance;
  51182. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51183. return _this;
  51184. }
  51185. AnaglyphGamepadCamera.prototype.getClassName = function () {
  51186. return "AnaglyphGamepadCamera";
  51187. };
  51188. return AnaglyphGamepadCamera;
  51189. }(BABYLON.GamepadCamera));
  51190. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  51191. var AnaglyphUniversalCamera = (function (_super) {
  51192. __extends(AnaglyphUniversalCamera, _super);
  51193. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  51194. var _this = _super.call(this, name, position, scene) || this;
  51195. _this.interaxialDistance = interaxialDistance;
  51196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51197. return _this;
  51198. }
  51199. AnaglyphUniversalCamera.prototype.getClassName = function () {
  51200. return "AnaglyphUniversalCamera";
  51201. };
  51202. return AnaglyphUniversalCamera;
  51203. }(BABYLON.UniversalCamera));
  51204. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  51205. var StereoscopicFreeCamera = (function (_super) {
  51206. __extends(StereoscopicFreeCamera, _super);
  51207. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51208. var _this = _super.call(this, name, position, scene) || this;
  51209. _this.interaxialDistance = interaxialDistance;
  51210. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51211. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51212. return _this;
  51213. }
  51214. StereoscopicFreeCamera.prototype.getClassName = function () {
  51215. return "StereoscopicFreeCamera";
  51216. };
  51217. return StereoscopicFreeCamera;
  51218. }(BABYLON.FreeCamera));
  51219. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  51220. var StereoscopicArcRotateCamera = (function (_super) {
  51221. __extends(StereoscopicArcRotateCamera, _super);
  51222. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  51223. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51224. _this.interaxialDistance = interaxialDistance;
  51225. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51226. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51227. return _this;
  51228. }
  51229. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  51230. return "StereoscopicArcRotateCamera";
  51231. };
  51232. return StereoscopicArcRotateCamera;
  51233. }(BABYLON.ArcRotateCamera));
  51234. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  51235. var StereoscopicGamepadCamera = (function (_super) {
  51236. __extends(StereoscopicGamepadCamera, _super);
  51237. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51238. var _this = _super.call(this, name, position, scene) || this;
  51239. _this.interaxialDistance = interaxialDistance;
  51240. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51241. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51242. return _this;
  51243. }
  51244. StereoscopicGamepadCamera.prototype.getClassName = function () {
  51245. return "StereoscopicGamepadCamera";
  51246. };
  51247. return StereoscopicGamepadCamera;
  51248. }(BABYLON.GamepadCamera));
  51249. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  51250. var StereoscopicUniversalCamera = (function (_super) {
  51251. __extends(StereoscopicUniversalCamera, _super);
  51252. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51253. var _this = _super.call(this, name, position, scene) || this;
  51254. _this.interaxialDistance = interaxialDistance;
  51255. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51256. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51257. return _this;
  51258. }
  51259. StereoscopicUniversalCamera.prototype.getClassName = function () {
  51260. return "StereoscopicUniversalCamera";
  51261. };
  51262. return StereoscopicUniversalCamera;
  51263. }(BABYLON.UniversalCamera));
  51264. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  51265. })(BABYLON || (BABYLON = {}));
  51266. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  51267. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  51268. var BABYLON;
  51269. (function (BABYLON) {
  51270. var HDRRenderingPipeline = (function (_super) {
  51271. __extends(HDRRenderingPipeline, _super);
  51272. /**
  51273. * @constructor
  51274. * @param {string} name - The rendering pipeline name
  51275. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51276. * @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)
  51277. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  51278. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51279. */
  51280. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  51281. if (originalPostProcess === void 0) { originalPostProcess = null; }
  51282. var _this = _super.call(this, scene.getEngine(), name) || this;
  51283. /**
  51284. * Public members
  51285. */
  51286. // Gaussian Blur
  51287. /**
  51288. * Gaussian blur coefficient
  51289. * @type {number}
  51290. */
  51291. _this.gaussCoeff = 0.3;
  51292. /**
  51293. * Gaussian blur mean
  51294. * @type {number}
  51295. */
  51296. _this.gaussMean = 1.0;
  51297. /**
  51298. * Gaussian blur standard deviation
  51299. * @type {number}
  51300. */
  51301. _this.gaussStandDev = 0.8;
  51302. /**
  51303. * Gaussian blur multiplier. Multiplies the blur effect
  51304. * @type {number}
  51305. */
  51306. _this.gaussMultiplier = 4.0;
  51307. // HDR
  51308. /**
  51309. * Exposure, controls the overall intensity of the pipeline
  51310. * @type {number}
  51311. */
  51312. _this.exposure = 1.0;
  51313. /**
  51314. * Minimum luminance that the post-process can output. Luminance is >= 0
  51315. * @type {number}
  51316. */
  51317. _this.minimumLuminance = 1.0;
  51318. /**
  51319. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  51320. * @type {number}
  51321. */
  51322. _this.maximumLuminance = 1e20;
  51323. /**
  51324. * Increase rate for luminance: eye adaptation speed to dark
  51325. * @type {number}
  51326. */
  51327. _this.luminanceIncreaserate = 0.5;
  51328. /**
  51329. * Decrease rate for luminance: eye adaptation speed to bright
  51330. * @type {number}
  51331. */
  51332. _this.luminanceDecreaseRate = 0.5;
  51333. // Bright pass
  51334. /**
  51335. * Minimum luminance needed to compute HDR
  51336. * @type {number}
  51337. */
  51338. _this.brightThreshold = 0.8;
  51339. _this._needUpdate = true;
  51340. _this._scene = scene;
  51341. // Bright pass
  51342. _this._createBrightPassPostProcess(scene, ratio);
  51343. // Down sample X4
  51344. _this._createDownSampleX4PostProcess(scene, ratio);
  51345. // Create gaussian blur post-processes
  51346. _this._createGaussianBlurPostProcess(scene, ratio);
  51347. // Texture adder
  51348. _this._createTextureAdderPostProcess(scene, ratio);
  51349. // Luminance generator
  51350. _this._createLuminanceGeneratorPostProcess(scene);
  51351. // HDR
  51352. _this._createHDRPostProcess(scene, ratio);
  51353. // Pass postprocess
  51354. if (originalPostProcess === null) {
  51355. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51356. }
  51357. else {
  51358. _this._originalPostProcess = originalPostProcess;
  51359. }
  51360. // Configure pipeline
  51361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  51362. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  51363. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  51364. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  51365. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  51366. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  51367. var addDownSamplerPostProcess = function (id) {
  51368. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  51369. };
  51370. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  51371. addDownSamplerPostProcess(i);
  51372. }
  51373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  51374. // Finish
  51375. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51376. if (cameras !== null) {
  51377. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51378. }
  51379. _this.update();
  51380. return _this;
  51381. }
  51382. /**
  51383. * Tells the pipeline to update its post-processes
  51384. */
  51385. HDRRenderingPipeline.prototype.update = function () {
  51386. this._needUpdate = true;
  51387. };
  51388. /**
  51389. * Returns the current calculated luminance
  51390. */
  51391. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  51392. return this._hdrCurrentLuminance;
  51393. };
  51394. /**
  51395. * Returns the currently drawn luminance
  51396. */
  51397. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  51398. return this._hdrOutputLuminance;
  51399. };
  51400. /**
  51401. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  51402. */
  51403. HDRRenderingPipeline.prototype.dispose = function () {
  51404. for (var i = 0; i < this._scene.cameras.length; i++) {
  51405. var camera = this._scene.cameras[i];
  51406. this._originalPostProcess.dispose(camera);
  51407. this._brightPassPostProcess.dispose(camera);
  51408. this._downSampleX4PostProcess.dispose(camera);
  51409. this._guassianBlurHPostProcess.dispose(camera);
  51410. this._guassianBlurVPostProcess.dispose(camera);
  51411. this._textureAdderPostProcess.dispose(camera);
  51412. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  51413. this._downSamplePostProcesses[j].dispose(camera);
  51414. }
  51415. this._hdrPostProcess.dispose(camera);
  51416. }
  51417. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51418. _super.prototype.dispose.call(this);
  51419. };
  51420. /**
  51421. * Creates the HDR post-process and computes the luminance adaptation
  51422. */
  51423. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  51424. var _this = this;
  51425. var hdrLastLuminance = 0.0;
  51426. this._hdrOutputLuminance = -1.0;
  51427. this._hdrCurrentLuminance = 1.0;
  51428. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  51429. this._hdrPostProcess.onApply = function (effect) {
  51430. if (_this._hdrOutputLuminance < 0.0) {
  51431. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51432. }
  51433. else {
  51434. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  51435. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  51436. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  51437. }
  51438. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  51439. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  51440. }
  51441. else {
  51442. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51443. }
  51444. }
  51445. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  51446. hdrLastLuminance += scene.getEngine().getDeltaTime();
  51447. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51448. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51449. effect.setFloat("exposure", _this.exposure);
  51450. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  51451. _this._needUpdate = false;
  51452. };
  51453. };
  51454. /**
  51455. * Texture Adder post-process
  51456. */
  51457. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  51458. var _this = this;
  51459. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  51460. this._textureAdderPostProcess.onApply = function (effect) {
  51461. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51462. };
  51463. };
  51464. /**
  51465. * Down sample X4 post-process
  51466. */
  51467. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  51468. var _this = this;
  51469. var downSampleX4Offsets = new Array(32);
  51470. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  51471. this._downSampleX4PostProcess.onApply = function (effect) {
  51472. if (_this._needUpdate) {
  51473. var id = 0;
  51474. for (var i = -2; i < 2; i++) {
  51475. for (var j = -2; j < 2; j++) {
  51476. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  51477. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  51478. id += 2;
  51479. }
  51480. }
  51481. }
  51482. effect.setArray2("dsOffsets", downSampleX4Offsets);
  51483. };
  51484. };
  51485. /**
  51486. * Bright pass post-process
  51487. */
  51488. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  51489. var _this = this;
  51490. var brightOffsets = new Array(8);
  51491. var brightPassCallback = function (effect) {
  51492. if (_this._needUpdate) {
  51493. var sU = (1.0 / _this._brightPassPostProcess.width);
  51494. var sV = (1.0 / _this._brightPassPostProcess.height);
  51495. brightOffsets[0] = -0.5 * sU;
  51496. brightOffsets[1] = 0.5 * sV;
  51497. brightOffsets[2] = 0.5 * sU;
  51498. brightOffsets[3] = 0.5 * sV;
  51499. brightOffsets[4] = -0.5 * sU;
  51500. brightOffsets[5] = -0.5 * sV;
  51501. brightOffsets[6] = 0.5 * sU;
  51502. brightOffsets[7] = -0.5 * sV;
  51503. }
  51504. effect.setArray2("dsOffsets", brightOffsets);
  51505. effect.setFloat("brightThreshold", _this.brightThreshold);
  51506. };
  51507. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  51508. this._brightPassPostProcess.onApply = brightPassCallback;
  51509. };
  51510. /**
  51511. * Luminance generator. Creates the luminance post-process and down sample post-processes
  51512. */
  51513. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  51514. var _this = this;
  51515. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  51516. var luminanceOffsets = new Array(8);
  51517. var downSampleOffsets = new Array(18);
  51518. var halfDestPixelSize;
  51519. this._downSamplePostProcesses = new Array(lumSteps);
  51520. // Utils for luminance
  51521. var luminanceUpdateSourceOffsets = function (width, height) {
  51522. var sU = (1.0 / width);
  51523. var sV = (1.0 / height);
  51524. luminanceOffsets[0] = -0.5 * sU;
  51525. luminanceOffsets[1] = 0.5 * sV;
  51526. luminanceOffsets[2] = 0.5 * sU;
  51527. luminanceOffsets[3] = 0.5 * sV;
  51528. luminanceOffsets[4] = -0.5 * sU;
  51529. luminanceOffsets[5] = -0.5 * sV;
  51530. luminanceOffsets[6] = 0.5 * sU;
  51531. luminanceOffsets[7] = -0.5 * sV;
  51532. };
  51533. var luminanceUpdateDestOffsets = function (width, height) {
  51534. var id = 0;
  51535. for (var x = -1; x < 2; x++) {
  51536. for (var y = -1; y < 2; y++) {
  51537. downSampleOffsets[id] = (x) / width;
  51538. downSampleOffsets[id + 1] = (y) / height;
  51539. id += 2;
  51540. }
  51541. }
  51542. };
  51543. // Luminance callback
  51544. var luminanceCallback = function (effect) {
  51545. if (_this._needUpdate) {
  51546. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  51547. }
  51548. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51549. effect.setArray2("lumOffsets", luminanceOffsets);
  51550. };
  51551. // Down sample callbacks
  51552. var downSampleCallback = function (indice) {
  51553. var i = indice;
  51554. return function (effect) {
  51555. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51556. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51557. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  51558. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  51559. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  51560. effect.setArray2("dsOffsets", downSampleOffsets);
  51561. };
  51562. };
  51563. var downSampleAfterRenderCallback = function (effect) {
  51564. // Unpack result
  51565. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  51566. 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);
  51567. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  51568. };
  51569. // Create luminance post-process
  51570. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  51571. 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);
  51572. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  51573. // Create down sample post-processes
  51574. for (var i = lumSteps - 2; i >= 0; i--) {
  51575. var length = Math.pow(3, i);
  51576. ratio = { width: length, height: length };
  51577. var defines = "#define DOWN_SAMPLE\n";
  51578. if (i === 0) {
  51579. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  51580. }
  51581. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  51582. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  51583. if (i === 0) {
  51584. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  51585. }
  51586. }
  51587. };
  51588. /**
  51589. * Gaussian blur post-processes. Horizontal and Vertical
  51590. */
  51591. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  51592. var _this = this;
  51593. var blurOffsetsW = new Array(9);
  51594. var blurOffsetsH = new Array(9);
  51595. var blurWeights = new Array(9);
  51596. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  51597. // Utils for gaussian blur
  51598. var calculateBlurOffsets = function (height) {
  51599. var lastOutputDimensions = {
  51600. width: scene.getEngine().getRenderWidth(),
  51601. height: scene.getEngine().getRenderHeight()
  51602. };
  51603. for (var i = 0; i < 9; i++) {
  51604. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  51605. if (height) {
  51606. blurOffsetsH[i] = value;
  51607. }
  51608. else {
  51609. blurOffsetsW[i] = value;
  51610. }
  51611. }
  51612. };
  51613. var calculateWeights = function () {
  51614. var x = 0.0;
  51615. for (var i = 0; i < 9; i++) {
  51616. x = (i - 4.0) / 4.0;
  51617. 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));
  51618. }
  51619. };
  51620. // Callback
  51621. var gaussianBlurCallback = function (height) {
  51622. return function (effect) {
  51623. if (_this._needUpdate) {
  51624. calculateWeights();
  51625. calculateBlurOffsets(height);
  51626. }
  51627. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  51628. effect.setArray("blurWeights", blurWeights);
  51629. effect.setFloat("multiplier", _this.gaussMultiplier);
  51630. };
  51631. };
  51632. // Create horizontal gaussian blur post-processes
  51633. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  51634. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  51635. // Create vertical gaussian blur post-process
  51636. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  51637. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  51638. };
  51639. return HDRRenderingPipeline;
  51640. }(BABYLON.PostProcessRenderPipeline));
  51641. // Luminance generator
  51642. HDRRenderingPipeline.LUM_STEPS = 6;
  51643. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  51644. })(BABYLON || (BABYLON = {}));
  51645. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  51646. var BABYLON;
  51647. (function (BABYLON) {
  51648. var FaceAdjacencies = (function () {
  51649. function FaceAdjacencies() {
  51650. this.edges = new Array();
  51651. this.edgesConnectedCount = 0;
  51652. }
  51653. return FaceAdjacencies;
  51654. }());
  51655. var EdgesRenderer = (function () {
  51656. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  51657. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  51658. if (epsilon === void 0) { epsilon = 0.95; }
  51659. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  51660. this.edgesWidthScalerForOrthographic = 1000.0;
  51661. this.edgesWidthScalerForPerspective = 50.0;
  51662. this._linesPositions = new Array();
  51663. this._linesNormals = new Array();
  51664. this._linesIndices = new Array();
  51665. this._buffers = {};
  51666. this._checkVerticesInsteadOfIndices = false;
  51667. this._source = source;
  51668. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  51669. this._epsilon = epsilon;
  51670. this._prepareRessources();
  51671. this._generateEdgesLines();
  51672. }
  51673. EdgesRenderer.prototype._prepareRessources = function () {
  51674. if (this._lineShader) {
  51675. return;
  51676. }
  51677. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  51678. attributes: ["position", "normal"],
  51679. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  51680. });
  51681. this._lineShader.disableDepthWrite = true;
  51682. this._lineShader.backFaceCulling = false;
  51683. };
  51684. EdgesRenderer.prototype.dispose = function () {
  51685. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  51686. if (buffer) {
  51687. buffer.dispose();
  51688. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  51689. }
  51690. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  51691. if (buffer) {
  51692. buffer.dispose();
  51693. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  51694. }
  51695. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  51696. this._lineShader.dispose();
  51697. };
  51698. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  51699. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  51700. return 0;
  51701. }
  51702. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  51703. return 1;
  51704. }
  51705. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  51706. return 2;
  51707. }
  51708. return -1;
  51709. };
  51710. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  51711. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  51712. return 0;
  51713. }
  51714. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  51715. return 1;
  51716. }
  51717. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  51718. return 2;
  51719. }
  51720. return -1;
  51721. };
  51722. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  51723. var needToCreateLine;
  51724. if (edge === undefined) {
  51725. needToCreateLine = true;
  51726. }
  51727. else {
  51728. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  51729. needToCreateLine = dotProduct < this._epsilon;
  51730. }
  51731. if (needToCreateLine) {
  51732. var offset = this._linesPositions.length / 3;
  51733. var normal = p0.subtract(p1);
  51734. normal.normalize();
  51735. // Positions
  51736. this._linesPositions.push(p0.x);
  51737. this._linesPositions.push(p0.y);
  51738. this._linesPositions.push(p0.z);
  51739. this._linesPositions.push(p0.x);
  51740. this._linesPositions.push(p0.y);
  51741. this._linesPositions.push(p0.z);
  51742. this._linesPositions.push(p1.x);
  51743. this._linesPositions.push(p1.y);
  51744. this._linesPositions.push(p1.z);
  51745. this._linesPositions.push(p1.x);
  51746. this._linesPositions.push(p1.y);
  51747. this._linesPositions.push(p1.z);
  51748. // Normals
  51749. this._linesNormals.push(p1.x);
  51750. this._linesNormals.push(p1.y);
  51751. this._linesNormals.push(p1.z);
  51752. this._linesNormals.push(-1);
  51753. this._linesNormals.push(p1.x);
  51754. this._linesNormals.push(p1.y);
  51755. this._linesNormals.push(p1.z);
  51756. this._linesNormals.push(1);
  51757. this._linesNormals.push(p0.x);
  51758. this._linesNormals.push(p0.y);
  51759. this._linesNormals.push(p0.z);
  51760. this._linesNormals.push(-1);
  51761. this._linesNormals.push(p0.x);
  51762. this._linesNormals.push(p0.y);
  51763. this._linesNormals.push(p0.z);
  51764. this._linesNormals.push(1);
  51765. // Indices
  51766. this._linesIndices.push(offset);
  51767. this._linesIndices.push(offset + 1);
  51768. this._linesIndices.push(offset + 2);
  51769. this._linesIndices.push(offset);
  51770. this._linesIndices.push(offset + 2);
  51771. this._linesIndices.push(offset + 3);
  51772. }
  51773. };
  51774. EdgesRenderer.prototype._generateEdgesLines = function () {
  51775. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51776. var indices = this._source.getIndices();
  51777. // First let's find adjacencies
  51778. var adjacencies = new Array();
  51779. var faceNormals = new Array();
  51780. var index;
  51781. var faceAdjacencies;
  51782. // Prepare faces
  51783. for (index = 0; index < indices.length; index += 3) {
  51784. faceAdjacencies = new FaceAdjacencies();
  51785. var p0Index = indices[index];
  51786. var p1Index = indices[index + 1];
  51787. var p2Index = indices[index + 2];
  51788. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  51789. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  51790. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  51791. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  51792. faceNormal.normalize();
  51793. faceNormals.push(faceNormal);
  51794. adjacencies.push(faceAdjacencies);
  51795. }
  51796. // Scan
  51797. for (index = 0; index < adjacencies.length; index++) {
  51798. faceAdjacencies = adjacencies[index];
  51799. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  51800. var otherFaceAdjacencies = adjacencies[otherIndex];
  51801. if (faceAdjacencies.edgesConnectedCount === 3) {
  51802. break;
  51803. }
  51804. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  51805. continue;
  51806. }
  51807. var otherP0 = indices[otherIndex * 3];
  51808. var otherP1 = indices[otherIndex * 3 + 1];
  51809. var otherP2 = indices[otherIndex * 3 + 2];
  51810. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  51811. var otherEdgeIndex;
  51812. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  51813. continue;
  51814. }
  51815. switch (edgeIndex) {
  51816. case 0:
  51817. if (this._checkVerticesInsteadOfIndices) {
  51818. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51819. }
  51820. else {
  51821. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  51822. }
  51823. break;
  51824. case 1:
  51825. if (this._checkVerticesInsteadOfIndices) {
  51826. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51827. }
  51828. else {
  51829. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  51830. }
  51831. break;
  51832. case 2:
  51833. if (this._checkVerticesInsteadOfIndices) {
  51834. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51835. }
  51836. else {
  51837. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  51838. }
  51839. break;
  51840. }
  51841. if (otherEdgeIndex === -1) {
  51842. continue;
  51843. }
  51844. faceAdjacencies.edges[edgeIndex] = otherIndex;
  51845. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  51846. faceAdjacencies.edgesConnectedCount++;
  51847. otherFaceAdjacencies.edgesConnectedCount++;
  51848. if (faceAdjacencies.edgesConnectedCount === 3) {
  51849. break;
  51850. }
  51851. }
  51852. }
  51853. }
  51854. // Create lines
  51855. for (index = 0; index < adjacencies.length; index++) {
  51856. // 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
  51857. var current = adjacencies[index];
  51858. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  51859. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  51860. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  51861. }
  51862. // Merge into a single mesh
  51863. var engine = this._source.getScene().getEngine();
  51864. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  51865. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  51866. this._ib = engine.createIndexBuffer(this._linesIndices);
  51867. this._indicesCount = this._linesIndices.length;
  51868. };
  51869. EdgesRenderer.prototype.render = function () {
  51870. if (!this._lineShader.isReady()) {
  51871. return;
  51872. }
  51873. var scene = this._source.getScene();
  51874. var engine = scene.getEngine();
  51875. this._lineShader._preBind();
  51876. // VBOs
  51877. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  51878. scene.resetCachedMaterial();
  51879. this._lineShader.setColor4("color", this._source.edgesColor);
  51880. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  51881. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  51882. }
  51883. else {
  51884. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  51885. }
  51886. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  51887. this._lineShader.bind(this._source.getWorldMatrix());
  51888. // Draw order
  51889. engine.draw(true, 0, this._indicesCount);
  51890. this._lineShader.unbind();
  51891. engine.setDepthWrite(true);
  51892. };
  51893. return EdgesRenderer;
  51894. }());
  51895. BABYLON.EdgesRenderer = EdgesRenderer;
  51896. })(BABYLON || (BABYLON = {}));
  51897. //# sourceMappingURL=babylon.edgesRenderer.js.map
  51898. var BABYLON;
  51899. (function (BABYLON) {
  51900. var TonemappingOperator;
  51901. (function (TonemappingOperator) {
  51902. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  51903. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  51904. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  51905. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  51906. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  51907. ;
  51908. var TonemapPostProcess = (function (_super) {
  51909. __extends(TonemapPostProcess, _super);
  51910. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  51911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51912. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51913. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  51914. _this._operator = _operator;
  51915. _this.exposureAdjustment = exposureAdjustment;
  51916. var defines = "#define ";
  51917. if (_this._operator === TonemappingOperator.Hable)
  51918. defines += "HABLE_TONEMAPPING";
  51919. else if (_this._operator === TonemappingOperator.Reinhard)
  51920. defines += "REINHARD_TONEMAPPING";
  51921. else if (_this._operator === TonemappingOperator.HejiDawson)
  51922. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51923. else if (_this._operator === TonemappingOperator.Photographic)
  51924. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51925. //sadly a second call to create the effect.
  51926. _this.updateEffect(defines);
  51927. _this.onApply = function (effect) {
  51928. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51929. };
  51930. return _this;
  51931. }
  51932. return TonemapPostProcess;
  51933. }(BABYLON.PostProcess));
  51934. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51935. })(BABYLON || (BABYLON = {}));
  51936. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  51937. var BABYLON;
  51938. (function (BABYLON) {
  51939. var ReflectionProbe = (function () {
  51940. function ReflectionProbe(name, size, scene, generateMipMaps) {
  51941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51942. var _this = this;
  51943. this.name = name;
  51944. this._viewMatrix = BABYLON.Matrix.Identity();
  51945. this._target = BABYLON.Vector3.Zero();
  51946. this._add = BABYLON.Vector3.Zero();
  51947. this.invertYAxis = false;
  51948. this.position = BABYLON.Vector3.Zero();
  51949. this._scene = scene;
  51950. this._scene.reflectionProbes.push(this);
  51951. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  51952. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  51953. switch (faceIndex) {
  51954. case 0:
  51955. _this._add.copyFromFloats(1, 0, 0);
  51956. break;
  51957. case 1:
  51958. _this._add.copyFromFloats(-1, 0, 0);
  51959. break;
  51960. case 2:
  51961. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  51962. break;
  51963. case 3:
  51964. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  51965. break;
  51966. case 4:
  51967. _this._add.copyFromFloats(0, 0, 1);
  51968. break;
  51969. case 5:
  51970. _this._add.copyFromFloats(0, 0, -1);
  51971. break;
  51972. }
  51973. if (_this._attachedMesh) {
  51974. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  51975. }
  51976. _this.position.addToRef(_this._add, _this._target);
  51977. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  51978. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  51979. });
  51980. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  51981. scene.updateTransformMatrix(true);
  51982. });
  51983. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  51984. }
  51985. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  51986. get: function () {
  51987. return this._renderTargetTexture.refreshRate;
  51988. },
  51989. set: function (value) {
  51990. this._renderTargetTexture.refreshRate = value;
  51991. },
  51992. enumerable: true,
  51993. configurable: true
  51994. });
  51995. ReflectionProbe.prototype.getScene = function () {
  51996. return this._scene;
  51997. };
  51998. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  51999. get: function () {
  52000. return this._renderTargetTexture;
  52001. },
  52002. enumerable: true,
  52003. configurable: true
  52004. });
  52005. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  52006. get: function () {
  52007. return this._renderTargetTexture.renderList;
  52008. },
  52009. enumerable: true,
  52010. configurable: true
  52011. });
  52012. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  52013. this._attachedMesh = mesh;
  52014. };
  52015. ReflectionProbe.prototype.dispose = function () {
  52016. var index = this._scene.reflectionProbes.indexOf(this);
  52017. if (index !== -1) {
  52018. // Remove from the scene if found
  52019. this._scene.reflectionProbes.splice(index, 1);
  52020. }
  52021. if (this._renderTargetTexture) {
  52022. this._renderTargetTexture.dispose();
  52023. this._renderTargetTexture = null;
  52024. }
  52025. };
  52026. return ReflectionProbe;
  52027. }());
  52028. BABYLON.ReflectionProbe = ReflectionProbe;
  52029. })(BABYLON || (BABYLON = {}));
  52030. //# sourceMappingURL=babylon.reflectionProbe.js.map
  52031. var BABYLON;
  52032. (function (BABYLON) {
  52033. var SolidParticle = (function () {
  52034. /**
  52035. * Creates a Solid Particle object.
  52036. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52037. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52038. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52039. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  52040. * `shapeId` (integer) is the model shape identifier in the SPS.
  52041. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52042. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  52043. */
  52044. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52045. this.idx = 0; // particle global index
  52046. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  52047. this.position = BABYLON.Vector3.Zero(); // position
  52048. this.rotation = BABYLON.Vector3.Zero(); // rotation
  52049. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  52050. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  52051. this.velocity = BABYLON.Vector3.Zero(); // velocity
  52052. this.alive = true; // alive
  52053. this.isVisible = true; // visibility
  52054. this._pos = 0; // index of this particle in the global "positions" array
  52055. this.shapeId = 0; // model shape id
  52056. this.idxInShape = 0; // index of the particle in its shape id
  52057. this.idx = particleIndex;
  52058. this._pos = positionIndex;
  52059. this._model = model;
  52060. this.shapeId = shapeId;
  52061. this.idxInShape = idxInShape;
  52062. this._sps = sps;
  52063. if (modelBoundingInfo) {
  52064. this._modelBoundingInfo = modelBoundingInfo;
  52065. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52066. }
  52067. }
  52068. Object.defineProperty(SolidParticle.prototype, "scale", {
  52069. /**
  52070. * legacy support, changed scale to scaling
  52071. */
  52072. get: function () {
  52073. return this.scaling;
  52074. },
  52075. set: function (scale) {
  52076. this.scaling = scale;
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52082. /**
  52083. * legacy support, changed quaternion to rotationQuaternion
  52084. */
  52085. get: function () {
  52086. return this.rotationQuaternion;
  52087. },
  52088. set: function (q) {
  52089. this.rotationQuaternion = q;
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. /**
  52095. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52096. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52097. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  52098. */
  52099. SolidParticle.prototype.intersectsMesh = function (target) {
  52100. if (!this._boundingInfo || !target._boundingInfo) {
  52101. return false;
  52102. }
  52103. if (this._sps._bSphereOnly) {
  52104. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52105. }
  52106. return this._boundingInfo.intersects(target._boundingInfo, false);
  52107. };
  52108. return SolidParticle;
  52109. }());
  52110. BABYLON.SolidParticle = SolidParticle;
  52111. var ModelShape = (function () {
  52112. /**
  52113. * 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.
  52114. * SPS internal tool, don't use it manually.
  52115. */
  52116. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  52117. this.shapeID = id;
  52118. this._shape = shape;
  52119. this._shapeUV = shapeUV;
  52120. this._positionFunction = posFunction;
  52121. this._vertexFunction = vtxFunction;
  52122. }
  52123. return ModelShape;
  52124. }());
  52125. BABYLON.ModelShape = ModelShape;
  52126. })(BABYLON || (BABYLON = {}));
  52127. //# sourceMappingURL=babylon.solidParticle.js.map
  52128. var BABYLON;
  52129. (function (BABYLON) {
  52130. /**
  52131. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52132. */
  52133. var SolidParticleSystem = (function () {
  52134. /**
  52135. * Creates a SPS (Solid Particle System) object.
  52136. * `name` (String) is the SPS name, this will be the underlying mesh name.
  52137. * `scene` (Scene) is the scene in which the SPS is added.
  52138. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  52139. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  52140. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  52141. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52142. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52143. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52144. */
  52145. function SolidParticleSystem(name, scene, options) {
  52146. // public members
  52147. /**
  52148. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52149. * Example : var p = SPS.particles[i];
  52150. */
  52151. this.particles = new Array();
  52152. /**
  52153. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52154. */
  52155. this.nbParticles = 0;
  52156. /**
  52157. * If the particles must ever face the camera (default false). Useful for planar particles.
  52158. */
  52159. this.billboard = false;
  52160. /**
  52161. * Recompute normals when adding a shape
  52162. */
  52163. this.recomputeNormals = true;
  52164. /**
  52165. * This a counter ofr your own usage. It's not set by any SPS functions.
  52166. */
  52167. this.counter = 0;
  52168. /**
  52169. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52170. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52171. */
  52172. this.vars = {};
  52173. this._positions = new Array();
  52174. this._indices = new Array();
  52175. this._normals = new Array();
  52176. this._colors = new Array();
  52177. this._uvs = new Array();
  52178. this._index = 0; // indices index
  52179. this._updatable = true;
  52180. this._pickable = false;
  52181. this._isVisibilityBoxLocked = false;
  52182. this._alwaysVisible = false;
  52183. this._shapeCounter = 0;
  52184. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  52185. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52186. this._computeParticleColor = true;
  52187. this._computeParticleTexture = true;
  52188. this._computeParticleRotation = true;
  52189. this._computeParticleVertex = false;
  52190. this._computeBoundingBox = false;
  52191. this._cam_axisZ = BABYLON.Vector3.Zero();
  52192. this._cam_axisY = BABYLON.Vector3.Zero();
  52193. this._cam_axisX = BABYLON.Vector3.Zero();
  52194. this._axisX = BABYLON.Axis.X;
  52195. this._axisY = BABYLON.Axis.Y;
  52196. this._axisZ = BABYLON.Axis.Z;
  52197. this._camDir = BABYLON.Vector3.Zero();
  52198. this._rotMatrix = new BABYLON.Matrix();
  52199. this._invertMatrix = new BABYLON.Matrix();
  52200. this._rotated = BABYLON.Vector3.Zero();
  52201. this._quaternion = new BABYLON.Quaternion();
  52202. this._vertex = BABYLON.Vector3.Zero();
  52203. this._normal = BABYLON.Vector3.Zero();
  52204. this._yaw = 0.0;
  52205. this._pitch = 0.0;
  52206. this._roll = 0.0;
  52207. this._halfroll = 0.0;
  52208. this._halfpitch = 0.0;
  52209. this._halfyaw = 0.0;
  52210. this._sinRoll = 0.0;
  52211. this._cosRoll = 0.0;
  52212. this._sinPitch = 0.0;
  52213. this._cosPitch = 0.0;
  52214. this._sinYaw = 0.0;
  52215. this._cosYaw = 0.0;
  52216. this._w = 0.0;
  52217. this._mustUnrotateFixedNormals = false;
  52218. this._minimum = BABYLON.Tmp.Vector3[0];
  52219. this._maximum = BABYLON.Tmp.Vector3[1];
  52220. this._scale = BABYLON.Tmp.Vector3[2];
  52221. this._translation = BABYLON.Tmp.Vector3[3];
  52222. this._minBbox = BABYLON.Tmp.Vector3[4];
  52223. this._maxBbox = BABYLON.Tmp.Vector3[5];
  52224. this._particlesIntersect = false;
  52225. this._bSphereOnly = false;
  52226. this._bSphereRadiusFactor = 1.0;
  52227. this.name = name;
  52228. this._scene = scene;
  52229. this._camera = scene.activeCamera;
  52230. this._pickable = options ? options.isPickable : false;
  52231. this._particlesIntersect = options ? options.particleIntersection : false;
  52232. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52233. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52234. if (options && options.updatable) {
  52235. this._updatable = options.updatable;
  52236. }
  52237. else {
  52238. this._updatable = true;
  52239. }
  52240. if (this._pickable) {
  52241. this.pickedParticles = [];
  52242. }
  52243. }
  52244. /**
  52245. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52246. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52247. */
  52248. SolidParticleSystem.prototype.buildMesh = function () {
  52249. if (this.nbParticles === 0) {
  52250. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52251. this.addShape(triangle, 1);
  52252. triangle.dispose();
  52253. }
  52254. this._positions32 = new Float32Array(this._positions);
  52255. this._uvs32 = new Float32Array(this._uvs);
  52256. this._colors32 = new Float32Array(this._colors);
  52257. if (this.recomputeNormals) {
  52258. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  52259. }
  52260. this._normals32 = new Float32Array(this._normals);
  52261. this._fixedNormal32 = new Float32Array(this._normals);
  52262. if (this._mustUnrotateFixedNormals) {
  52263. this._unrotateFixedNormals();
  52264. }
  52265. var vertexData = new BABYLON.VertexData();
  52266. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52267. vertexData.indices = this._indices;
  52268. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52269. if (this._uvs32) {
  52270. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52271. ;
  52272. }
  52273. if (this._colors32) {
  52274. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52275. }
  52276. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52277. vertexData.applyToMesh(mesh, this._updatable);
  52278. this.mesh = mesh;
  52279. this.mesh.isPickable = this._pickable;
  52280. // free memory
  52281. this._positions = null;
  52282. this._normals = null;
  52283. this._uvs = null;
  52284. this._colors = null;
  52285. if (!this._updatable) {
  52286. this.particles.length = 0;
  52287. }
  52288. return mesh;
  52289. };
  52290. /**
  52291. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52292. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52293. * Thus the particles generated from `digest()` have their property `position` set yet.
  52294. * `mesh` ( Mesh ) is the mesh to be digested
  52295. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  52296. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52297. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52298. */
  52299. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52300. var size = (options && options.facetNb) || 1;
  52301. var number = (options && options.number);
  52302. var delta = (options && options.delta) || 0;
  52303. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52304. var meshInd = mesh.getIndices();
  52305. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52306. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52307. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52308. var f = 0; // facet counter
  52309. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52310. // compute size from number
  52311. if (number) {
  52312. number = (number > totalFacets) ? totalFacets : number;
  52313. size = Math.round(totalFacets / number);
  52314. delta = 0;
  52315. }
  52316. else {
  52317. size = (size > totalFacets) ? totalFacets : size;
  52318. }
  52319. var facetPos = []; // submesh positions
  52320. var facetInd = []; // submesh indices
  52321. var facetUV = []; // submesh UV
  52322. var facetCol = []; // submesh colors
  52323. var barycenter = BABYLON.Tmp.Vector3[0];
  52324. var rand;
  52325. var sizeO = size;
  52326. while (f < totalFacets) {
  52327. size = sizeO + Math.floor((1 + delta) * Math.random());
  52328. if (f > totalFacets - size) {
  52329. size = totalFacets - f;
  52330. }
  52331. // reset temp arrays
  52332. facetPos.length = 0;
  52333. facetInd.length = 0;
  52334. facetUV.length = 0;
  52335. facetCol.length = 0;
  52336. // iterate over "size" facets
  52337. var fi = 0;
  52338. for (var j = f * 3; j < (f + size) * 3; j++) {
  52339. facetInd.push(fi);
  52340. var i = meshInd[j];
  52341. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52342. if (meshUV) {
  52343. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52344. }
  52345. if (meshCol) {
  52346. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52347. }
  52348. fi++;
  52349. }
  52350. // create a model shape for each single particle
  52351. var idx = this.nbParticles;
  52352. var shape = this._posToShape(facetPos);
  52353. var shapeUV = this._uvsToShapeUV(facetUV);
  52354. // compute the barycenter of the shape
  52355. var v;
  52356. for (v = 0; v < shape.length; v++) {
  52357. barycenter.addInPlace(shape[v]);
  52358. }
  52359. barycenter.scaleInPlace(1 / shape.length);
  52360. // shift the shape from its barycenter to the origin
  52361. for (v = 0; v < shape.length; v++) {
  52362. shape[v].subtractInPlace(barycenter);
  52363. }
  52364. var bInfo;
  52365. if (this._particlesIntersect) {
  52366. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52367. }
  52368. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  52369. // add the particle in the SPS
  52370. var currentPos = this._positions.length;
  52371. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52372. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  52373. // initialize the particle position
  52374. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52375. this._index += shape.length;
  52376. idx++;
  52377. this.nbParticles++;
  52378. this._shapeCounter++;
  52379. f += size;
  52380. }
  52381. return this;
  52382. };
  52383. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52384. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52385. var index = 0;
  52386. var idx = 0;
  52387. for (var p = 0; p < this.particles.length; p++) {
  52388. this._particle = this.particles[p];
  52389. this._shape = this._particle._model._shape;
  52390. if (this._particle.rotationQuaternion) {
  52391. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52392. }
  52393. else {
  52394. this._yaw = this._particle.rotation.y;
  52395. this._pitch = this._particle.rotation.x;
  52396. this._roll = this._particle.rotation.z;
  52397. this._quaternionRotationYPR();
  52398. }
  52399. this._quaternionToRotationMatrix();
  52400. this._rotMatrix.invertToRef(this._invertMatrix);
  52401. for (var pt = 0; pt < this._shape.length; pt++) {
  52402. idx = index + pt * 3;
  52403. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52404. this._fixedNormal32[idx] = this._normal.x;
  52405. this._fixedNormal32[idx + 1] = this._normal.y;
  52406. this._fixedNormal32[idx + 2] = this._normal.z;
  52407. }
  52408. index = idx + 3;
  52409. }
  52410. };
  52411. //reset copy
  52412. SolidParticleSystem.prototype._resetCopy = function () {
  52413. this._copy.position.x = 0;
  52414. this._copy.position.y = 0;
  52415. this._copy.position.z = 0;
  52416. this._copy.rotation.x = 0;
  52417. this._copy.rotation.y = 0;
  52418. this._copy.rotation.z = 0;
  52419. this._copy.rotationQuaternion = null;
  52420. this._copy.scaling.x = 1;
  52421. this._copy.scaling.y = 1;
  52422. this._copy.scaling.z = 1;
  52423. this._copy.uvs.x = 0;
  52424. this._copy.uvs.y = 0;
  52425. this._copy.uvs.z = 1;
  52426. this._copy.uvs.w = 1;
  52427. this._copy.color = null;
  52428. };
  52429. // _meshBuilder : inserts the shape model in the global SPS mesh
  52430. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52431. var i;
  52432. var u = 0;
  52433. var c = 0;
  52434. var n = 0;
  52435. this._resetCopy();
  52436. if (options && options.positionFunction) {
  52437. options.positionFunction(this._copy, idx, idxInShape);
  52438. this._mustUnrotateFixedNormals = true;
  52439. }
  52440. if (this._copy.rotationQuaternion) {
  52441. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52442. }
  52443. else {
  52444. this._yaw = this._copy.rotation.y;
  52445. this._pitch = this._copy.rotation.x;
  52446. this._roll = this._copy.rotation.z;
  52447. this._quaternionRotationYPR();
  52448. }
  52449. this._quaternionToRotationMatrix();
  52450. for (i = 0; i < shape.length; i++) {
  52451. this._vertex.x = shape[i].x;
  52452. this._vertex.y = shape[i].y;
  52453. this._vertex.z = shape[i].z;
  52454. if (options && options.vertexFunction) {
  52455. options.vertexFunction(this._copy, this._vertex, i);
  52456. }
  52457. this._vertex.x *= this._copy.scaling.x;
  52458. this._vertex.y *= this._copy.scaling.y;
  52459. this._vertex.z *= this._copy.scaling.z;
  52460. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52461. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52462. if (meshUV) {
  52463. 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);
  52464. u += 2;
  52465. }
  52466. if (this._copy.color) {
  52467. this._color = this._copy.color;
  52468. }
  52469. else if (meshCol && meshCol[c] !== undefined) {
  52470. this._color.r = meshCol[c];
  52471. this._color.g = meshCol[c + 1];
  52472. this._color.b = meshCol[c + 2];
  52473. this._color.a = meshCol[c + 3];
  52474. }
  52475. else {
  52476. this._color.r = 1;
  52477. this._color.g = 1;
  52478. this._color.b = 1;
  52479. this._color.a = 1;
  52480. }
  52481. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52482. c += 4;
  52483. if (!this.recomputeNormals && meshNor) {
  52484. this._normal.x = meshNor[n];
  52485. this._normal.y = meshNor[n + 1];
  52486. this._normal.z = meshNor[n + 2];
  52487. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52488. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52489. n += 3;
  52490. }
  52491. }
  52492. for (i = 0; i < meshInd.length; i++) {
  52493. indices.push(p + meshInd[i]);
  52494. }
  52495. if (this._pickable) {
  52496. var nbfaces = meshInd.length / 3;
  52497. for (i = 0; i < nbfaces; i++) {
  52498. this.pickedParticles.push({ idx: idx, faceId: i });
  52499. }
  52500. }
  52501. return this._copy;
  52502. };
  52503. // returns a shape array from positions array
  52504. SolidParticleSystem.prototype._posToShape = function (positions) {
  52505. var shape = [];
  52506. for (var i = 0; i < positions.length; i += 3) {
  52507. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52508. }
  52509. return shape;
  52510. };
  52511. // returns a shapeUV array from a Vector4 uvs
  52512. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52513. var shapeUV = [];
  52514. if (uvs) {
  52515. for (var i = 0; i < uvs.length; i++)
  52516. shapeUV.push(uvs[i]);
  52517. }
  52518. return shapeUV;
  52519. };
  52520. // adds a new particle object in the particles array
  52521. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  52522. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  52523. this.particles.push(sp);
  52524. return sp;
  52525. };
  52526. /**
  52527. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52528. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52529. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  52530. * `nb` (positive integer) the number of particles to be created from this model
  52531. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  52532. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  52533. */
  52534. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52535. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52536. var meshInd = mesh.getIndices();
  52537. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52538. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52539. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52540. var bbInfo;
  52541. if (this._particlesIntersect) {
  52542. bbInfo = mesh.getBoundingInfo();
  52543. }
  52544. var shape = this._posToShape(meshPos);
  52545. var shapeUV = this._uvsToShapeUV(meshUV);
  52546. var posfunc = options ? options.positionFunction : null;
  52547. var vtxfunc = options ? options.vertexFunction : null;
  52548. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  52549. // particles
  52550. var sp;
  52551. var currentCopy;
  52552. var idx = this.nbParticles;
  52553. for (var i = 0; i < nb; i++) {
  52554. var currentPos = this._positions.length;
  52555. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52556. if (this._updatable) {
  52557. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  52558. sp.position.copyFrom(currentCopy.position);
  52559. sp.rotation.copyFrom(currentCopy.rotation);
  52560. if (currentCopy.rotationQuaternion) {
  52561. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52562. }
  52563. if (currentCopy.color) {
  52564. sp.color.copyFrom(currentCopy.color);
  52565. }
  52566. sp.scaling.copyFrom(currentCopy.scaling);
  52567. sp.uvs.copyFrom(currentCopy.uvs);
  52568. }
  52569. this._index += shape.length;
  52570. idx++;
  52571. }
  52572. this.nbParticles += nb;
  52573. this._shapeCounter++;
  52574. return this._shapeCounter - 1;
  52575. };
  52576. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52577. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52578. this._resetCopy();
  52579. if (particle._model._positionFunction) {
  52580. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52581. }
  52582. if (this._copy.rotationQuaternion) {
  52583. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52584. }
  52585. else {
  52586. this._yaw = this._copy.rotation.y;
  52587. this._pitch = this._copy.rotation.x;
  52588. this._roll = this._copy.rotation.z;
  52589. this._quaternionRotationYPR();
  52590. }
  52591. this._quaternionToRotationMatrix();
  52592. this._shape = particle._model._shape;
  52593. for (var pt = 0; pt < this._shape.length; pt++) {
  52594. this._vertex.x = this._shape[pt].x;
  52595. this._vertex.y = this._shape[pt].y;
  52596. this._vertex.z = this._shape[pt].z;
  52597. if (particle._model._vertexFunction) {
  52598. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52599. }
  52600. this._vertex.x *= this._copy.scaling.x;
  52601. this._vertex.y *= this._copy.scaling.y;
  52602. this._vertex.z *= this._copy.scaling.z;
  52603. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52604. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52605. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52606. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52607. }
  52608. particle.position.x = 0.0;
  52609. particle.position.y = 0.0;
  52610. particle.position.z = 0.0;
  52611. particle.rotation.x = 0.0;
  52612. particle.rotation.y = 0.0;
  52613. particle.rotation.z = 0.0;
  52614. particle.rotationQuaternion = null;
  52615. particle.scaling.x = 1.0;
  52616. particle.scaling.y = 1.0;
  52617. particle.scaling.z = 1.0;
  52618. };
  52619. /**
  52620. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52621. * Returns the SPS.
  52622. */
  52623. SolidParticleSystem.prototype.rebuildMesh = function () {
  52624. for (var p = 0; p < this.particles.length; p++) {
  52625. this._rebuildParticle(this.particles[p]);
  52626. }
  52627. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52628. return this;
  52629. };
  52630. /**
  52631. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52632. * This method calls `updateParticle()` for each particle of the SPS.
  52633. * For an animated SPS, it is usually called within the render loop.
  52634. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52635. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52636. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52637. * Returns the SPS.
  52638. */
  52639. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52640. if (start === void 0) { start = 0; }
  52641. if (end === void 0) { end = this.nbParticles - 1; }
  52642. if (update === void 0) { update = true; }
  52643. if (!this._updatable) {
  52644. return;
  52645. }
  52646. // custom beforeUpdate
  52647. this.beforeUpdateParticles(start, end, update);
  52648. this._cam_axisX.x = 1.0;
  52649. this._cam_axisX.y = 0.0;
  52650. this._cam_axisX.z = 0.0;
  52651. this._cam_axisY.x = 0.0;
  52652. this._cam_axisY.y = 1.0;
  52653. this._cam_axisY.z = 0.0;
  52654. this._cam_axisZ.x = 0.0;
  52655. this._cam_axisZ.y = 0.0;
  52656. this._cam_axisZ.z = 1.0;
  52657. // if the particles will always face the camera
  52658. if (this.billboard) {
  52659. // compute the camera position and un-rotate it by the current mesh rotation
  52660. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  52661. this._quaternionToRotationMatrix();
  52662. this._rotMatrix.invertToRef(this._invertMatrix);
  52663. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  52664. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52665. this._cam_axisZ.normalize();
  52666. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  52667. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  52668. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52669. this._cam_axisY.normalize();
  52670. this._cam_axisX.normalize();
  52671. }
  52672. }
  52673. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52674. var idx = 0; // current position index in the global array positions32
  52675. var index = 0; // position start index in the global array positions32 of the current particle
  52676. var colidx = 0; // current color index in the global array colors32
  52677. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52678. var uvidx = 0; // current uv index in the global array uvs32
  52679. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52680. var pt = 0; // current index in the particle model shape
  52681. if (this.mesh.isFacetDataEnabled) {
  52682. this._computeBoundingBox = true;
  52683. }
  52684. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52685. if (this._computeBoundingBox) {
  52686. if (start == 0 && end == this.nbParticles - 1) {
  52687. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52688. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52689. }
  52690. else {
  52691. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52692. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52693. }
  52694. }
  52695. // particle loop
  52696. index = this.particles[start]._pos;
  52697. var vpos = (index / 3) | 0;
  52698. colorIndex = vpos * 4;
  52699. uvIndex = vpos * 2;
  52700. for (var p = start; p <= end; p++) {
  52701. this._particle = this.particles[p];
  52702. this._shape = this._particle._model._shape;
  52703. this._shapeUV = this._particle._model._shapeUV;
  52704. // call to custom user function to update the particle properties
  52705. this.updateParticle(this._particle);
  52706. if (this._particle.isVisible) {
  52707. // particle rotation matrix
  52708. if (this.billboard) {
  52709. this._particle.rotation.x = 0.0;
  52710. this._particle.rotation.y = 0.0;
  52711. }
  52712. if (this._computeParticleRotation || this.billboard) {
  52713. if (this._particle.rotationQuaternion) {
  52714. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52715. }
  52716. else {
  52717. this._yaw = this._particle.rotation.y;
  52718. this._pitch = this._particle.rotation.x;
  52719. this._roll = this._particle.rotation.z;
  52720. this._quaternionRotationYPR();
  52721. }
  52722. this._quaternionToRotationMatrix();
  52723. }
  52724. // particle vertex loop
  52725. for (pt = 0; pt < this._shape.length; pt++) {
  52726. idx = index + pt * 3;
  52727. colidx = colorIndex + pt * 4;
  52728. uvidx = uvIndex + pt * 2;
  52729. this._vertex.x = this._shape[pt].x;
  52730. this._vertex.y = this._shape[pt].y;
  52731. this._vertex.z = this._shape[pt].z;
  52732. if (this._computeParticleVertex) {
  52733. this.updateParticleVertex(this._particle, this._vertex, pt);
  52734. }
  52735. // positions
  52736. this._vertex.x *= this._particle.scaling.x;
  52737. this._vertex.y *= this._particle.scaling.y;
  52738. this._vertex.z *= this._particle.scaling.z;
  52739. 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];
  52740. 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;
  52741. 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;
  52742. 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;
  52743. 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;
  52744. 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;
  52745. 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;
  52746. if (this._computeBoundingBox) {
  52747. if (this._positions32[idx] < this._minimum.x) {
  52748. this._minimum.x = this._positions32[idx];
  52749. }
  52750. if (this._positions32[idx] > this._maximum.x) {
  52751. this._maximum.x = this._positions32[idx];
  52752. }
  52753. if (this._positions32[idx + 1] < this._minimum.y) {
  52754. this._minimum.y = this._positions32[idx + 1];
  52755. }
  52756. if (this._positions32[idx + 1] > this._maximum.y) {
  52757. this._maximum.y = this._positions32[idx + 1];
  52758. }
  52759. if (this._positions32[idx + 2] < this._minimum.z) {
  52760. this._minimum.z = this._positions32[idx + 2];
  52761. }
  52762. if (this._positions32[idx + 2] > this._maximum.z) {
  52763. this._maximum.z = this._positions32[idx + 2];
  52764. }
  52765. }
  52766. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52767. if (!this._computeParticleVertex) {
  52768. this._normal.x = this._fixedNormal32[idx];
  52769. this._normal.y = this._fixedNormal32[idx + 1];
  52770. this._normal.z = this._fixedNormal32[idx + 2];
  52771. 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]);
  52772. 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]);
  52773. 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]);
  52774. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52775. 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;
  52776. 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;
  52777. }
  52778. if (this._computeParticleColor) {
  52779. this._colors32[colidx] = this._particle.color.r;
  52780. this._colors32[colidx + 1] = this._particle.color.g;
  52781. this._colors32[colidx + 2] = this._particle.color.b;
  52782. this._colors32[colidx + 3] = this._particle.color.a;
  52783. }
  52784. if (this._computeParticleTexture) {
  52785. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52786. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52787. }
  52788. }
  52789. }
  52790. else {
  52791. for (pt = 0; pt < this._shape.length; pt++) {
  52792. idx = index + pt * 3;
  52793. colidx = colorIndex + pt * 4;
  52794. uvidx = uvIndex + pt * 2;
  52795. this._positions32[idx] = this._camera.position.x;
  52796. this._positions32[idx + 1] = this._camera.position.y;
  52797. this._positions32[idx + 2] = this._camera.position.z;
  52798. this._normals32[idx] = 0.0;
  52799. this._normals32[idx + 1] = 0.0;
  52800. this._normals32[idx + 2] = 0.0;
  52801. if (this._computeParticleColor) {
  52802. this._colors32[colidx] = this._particle.color.r;
  52803. this._colors32[colidx + 1] = this._particle.color.g;
  52804. this._colors32[colidx + 2] = this._particle.color.b;
  52805. this._colors32[colidx + 3] = this._particle.color.a;
  52806. }
  52807. if (this._computeParticleTexture) {
  52808. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52809. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52810. }
  52811. }
  52812. }
  52813. // if the particle intersections must be computed : update the bbInfo
  52814. if (this._particlesIntersect) {
  52815. var bInfo = this._particle._boundingInfo;
  52816. var bBox = bInfo.boundingBox;
  52817. var bSphere = bInfo.boundingSphere;
  52818. if (!this._bSphereOnly) {
  52819. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52820. for (var b = 0; b < bBox.vectors.length; b++) {
  52821. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52822. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52823. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52824. 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];
  52825. 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;
  52826. 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;
  52827. 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;
  52828. 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;
  52829. 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;
  52830. 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;
  52831. }
  52832. bBox._update(this.mesh._worldMatrix);
  52833. }
  52834. // place and scale the particle bouding sphere in the SPS local system, then update it
  52835. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52836. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52837. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52838. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52839. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52840. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52841. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52842. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52843. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52844. 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));
  52845. bSphere._update(this.mesh._worldMatrix);
  52846. }
  52847. // increment indexes for the next particle
  52848. index = idx + 3;
  52849. colorIndex = colidx + 4;
  52850. uvIndex = uvidx + 2;
  52851. }
  52852. // if the VBO must be updated
  52853. if (update) {
  52854. if (this._computeParticleColor) {
  52855. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52856. }
  52857. if (this._computeParticleTexture) {
  52858. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52859. }
  52860. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52861. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52862. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52863. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52864. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52865. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  52866. for (var i = 0; i < this._normals32.length; i++) {
  52867. this._fixedNormal32[i] = this._normals32[i];
  52868. }
  52869. }
  52870. if (!this.mesh.areNormalsFrozen) {
  52871. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52872. }
  52873. }
  52874. }
  52875. if (this._computeBoundingBox) {
  52876. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52877. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52878. }
  52879. this.afterUpdateParticles(start, end, update);
  52880. return this;
  52881. };
  52882. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52883. this._halfroll = this._roll * 0.5;
  52884. this._halfpitch = this._pitch * 0.5;
  52885. this._halfyaw = this._yaw * 0.5;
  52886. this._sinRoll = Math.sin(this._halfroll);
  52887. this._cosRoll = Math.cos(this._halfroll);
  52888. this._sinPitch = Math.sin(this._halfpitch);
  52889. this._cosPitch = Math.cos(this._halfpitch);
  52890. this._sinYaw = Math.sin(this._halfyaw);
  52891. this._cosYaw = Math.cos(this._halfyaw);
  52892. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  52893. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  52894. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  52895. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  52896. };
  52897. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52898. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52899. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52900. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52901. this._rotMatrix.m[3] = 0;
  52902. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52903. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52904. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52905. this._rotMatrix.m[7] = 0;
  52906. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52907. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52908. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52909. this._rotMatrix.m[11] = 0;
  52910. this._rotMatrix.m[12] = 0;
  52911. this._rotMatrix.m[13] = 0;
  52912. this._rotMatrix.m[14] = 0;
  52913. this._rotMatrix.m[15] = 1.0;
  52914. };
  52915. /**
  52916. * Disposes the SPS.
  52917. * Returns nothing.
  52918. */
  52919. SolidParticleSystem.prototype.dispose = function () {
  52920. this.mesh.dispose();
  52921. this.vars = null;
  52922. // drop references to internal big arrays for the GC
  52923. this._positions = null;
  52924. this._indices = null;
  52925. this._normals = null;
  52926. this._uvs = null;
  52927. this._colors = null;
  52928. this._positions32 = null;
  52929. this._normals32 = null;
  52930. this._fixedNormal32 = null;
  52931. this._uvs32 = null;
  52932. this._colors32 = null;
  52933. this.pickedParticles = null;
  52934. };
  52935. /**
  52936. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52938. * Returns the SPS.
  52939. */
  52940. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52941. if (!this._isVisibilityBoxLocked) {
  52942. this.mesh.refreshBoundingInfo();
  52943. }
  52944. return this;
  52945. };
  52946. /**
  52947. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52948. * @param size the size (float) of the visibility box
  52949. * note : this doesn't lock the SPS mesh bounding box.
  52950. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52951. */
  52952. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52953. var vis = size / 2;
  52954. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52955. };
  52956. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52957. // getter and setter
  52958. get: function () {
  52959. return this._alwaysVisible;
  52960. },
  52961. /**
  52962. * Sets the SPS as always visible or not
  52963. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52964. */
  52965. set: function (val) {
  52966. this._alwaysVisible = val;
  52967. this.mesh.alwaysSelectAsActiveMesh = val;
  52968. },
  52969. enumerable: true,
  52970. configurable: true
  52971. });
  52972. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52973. get: function () {
  52974. return this._isVisibilityBoxLocked;
  52975. },
  52976. /**
  52977. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52978. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52979. */
  52980. set: function (val) {
  52981. this._isVisibilityBoxLocked = val;
  52982. this.mesh.getBoundingInfo().isLocked = val;
  52983. },
  52984. enumerable: true,
  52985. configurable: true
  52986. });
  52987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52988. // getters
  52989. get: function () {
  52990. return this._computeParticleRotation;
  52991. },
  52992. // Optimizer setters
  52993. /**
  52994. * Tells to `setParticles()` to compute the particle rotations or not.
  52995. * Default value : true. The SPS is faster when it's set to false.
  52996. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52997. */
  52998. set: function (val) {
  52999. this._computeParticleRotation = val;
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53005. get: function () {
  53006. return this._computeParticleColor;
  53007. },
  53008. /**
  53009. * Tells to `setParticles()` to compute the particle colors or not.
  53010. * Default value : true. The SPS is faster when it's set to false.
  53011. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53012. */
  53013. set: function (val) {
  53014. this._computeParticleColor = val;
  53015. },
  53016. enumerable: true,
  53017. configurable: true
  53018. });
  53019. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53020. get: function () {
  53021. return this._computeParticleTexture;
  53022. },
  53023. /**
  53024. * Tells to `setParticles()` to compute the particle textures or not.
  53025. * Default value : true. The SPS is faster when it's set to false.
  53026. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53027. */
  53028. set: function (val) {
  53029. this._computeParticleTexture = val;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53035. get: function () {
  53036. return this._computeParticleVertex;
  53037. },
  53038. /**
  53039. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53040. * Default value : false. The SPS is faster when it's set to false.
  53041. * Note : the particle custom vertex positions aren't stored values.
  53042. */
  53043. set: function (val) {
  53044. this._computeParticleVertex = val;
  53045. },
  53046. enumerable: true,
  53047. configurable: true
  53048. });
  53049. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53050. get: function () {
  53051. return this._computeBoundingBox;
  53052. },
  53053. /**
  53054. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53055. */
  53056. set: function (val) {
  53057. this._computeBoundingBox = val;
  53058. },
  53059. enumerable: true,
  53060. configurable: true
  53061. });
  53062. // =======================================================================
  53063. // Particle behavior logic
  53064. // these following methods may be overwritten by the user to fit his needs
  53065. /**
  53066. * This function does nothing. It may be overwritten to set all the particle first values.
  53067. * The SPS doesn't call this function, you may have to call it by your own.
  53068. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53069. */
  53070. SolidParticleSystem.prototype.initParticles = function () {
  53071. };
  53072. /**
  53073. * This function does nothing. It may be overwritten to recycle a particle.
  53074. * The SPS doesn't call this function, you may have to call it by your own.
  53075. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53076. */
  53077. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53078. return particle;
  53079. };
  53080. /**
  53081. * Updates a particle : this function should be overwritten by the user.
  53082. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53083. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53084. * ex : just set a particle position or velocity and recycle conditions
  53085. */
  53086. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53087. return particle;
  53088. };
  53089. /**
  53090. * Updates a vertex of a particle : it can be overwritten by the user.
  53091. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53092. * @param particle the current particle
  53093. * @param vertex the current index of the current particle
  53094. * @param pt the index of the current vertex in the particle shape
  53095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53096. * ex : just set a vertex particle position
  53097. */
  53098. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53099. return vertex;
  53100. };
  53101. /**
  53102. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53103. * This does nothing and may be overwritten by the user.
  53104. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53105. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53106. * @param update the boolean update value actually passed to setParticles()
  53107. */
  53108. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53109. };
  53110. /**
  53111. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53112. * This will be passed three parameters.
  53113. * This does nothing and may be overwritten by the user.
  53114. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53115. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53116. * @param update the boolean update value actually passed to setParticles()
  53117. */
  53118. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53119. };
  53120. return SolidParticleSystem;
  53121. }());
  53122. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53123. })(BABYLON || (BABYLON = {}));
  53124. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var Internals;
  53128. (function (Internals) {
  53129. var FileFaceOrientation = (function () {
  53130. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53131. this.name = name;
  53132. this.worldAxisForNormal = worldAxisForNormal;
  53133. this.worldAxisForFileX = worldAxisForFileX;
  53134. this.worldAxisForFileY = worldAxisForFileY;
  53135. }
  53136. return FileFaceOrientation;
  53137. }());
  53138. ;
  53139. /**
  53140. * Helper class dealing with the extraction of spherical polynomial dataArray
  53141. * from a cube map.
  53142. */
  53143. var CubeMapToSphericalPolynomialTools = (function () {
  53144. function CubeMapToSphericalPolynomialTools() {
  53145. }
  53146. /**
  53147. * Converts a cubemap to the according Spherical Polynomial data.
  53148. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53149. *
  53150. * @param cubeInfo The Cube map to extract the information from.
  53151. * @return The Spherical Polynomial data.
  53152. */
  53153. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53154. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53155. var totalSolidAngle = 0.0;
  53156. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53157. var du = 2.0 / cubeInfo.size;
  53158. var dv = du;
  53159. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53160. var minUV = du * 0.5 - 1.0;
  53161. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53162. var fileFace = this.FileFaces[faceIndex];
  53163. var dataArray = cubeInfo[fileFace.name];
  53164. var v = minUV;
  53165. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53166. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53167. // Because SP is still linear, so summation is fine in that basis.
  53168. for (var y = 0; y < cubeInfo.size; y++) {
  53169. var u = minUV;
  53170. for (var x = 0; x < cubeInfo.size; x++) {
  53171. // World direction (not normalised)
  53172. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53173. worldDirection.normalize();
  53174. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53175. if (1) {
  53176. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53177. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53178. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53179. var color = new BABYLON.Color3(r, g, b);
  53180. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53181. }
  53182. else {
  53183. if (faceIndex == 0) {
  53184. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53185. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53186. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53187. }
  53188. else if (faceIndex == 1) {
  53189. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53190. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53191. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53192. }
  53193. else if (faceIndex == 2) {
  53194. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53195. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53196. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53197. }
  53198. else if (faceIndex == 3) {
  53199. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53200. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53201. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53202. }
  53203. else if (faceIndex == 4) {
  53204. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53205. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53206. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53207. }
  53208. else if (faceIndex == 5) {
  53209. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53210. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53211. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53212. }
  53213. 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]);
  53214. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53215. }
  53216. totalSolidAngle += deltaSolidAngle;
  53217. u += du;
  53218. }
  53219. v += dv;
  53220. }
  53221. }
  53222. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53223. var correction = correctSolidAngle / totalSolidAngle;
  53224. sphericalHarmonics.scale(correction);
  53225. // Additionally scale by pi -- audit needed
  53226. sphericalHarmonics.scale(1.0 / Math.PI);
  53227. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53228. };
  53229. return CubeMapToSphericalPolynomialTools;
  53230. }());
  53231. CubeMapToSphericalPolynomialTools.FileFaces = [
  53232. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53233. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53234. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53235. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53236. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53237. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53238. ];
  53239. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53240. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53241. })(BABYLON || (BABYLON = {}));
  53242. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  53243. var BABYLON;
  53244. (function (BABYLON) {
  53245. var Internals;
  53246. (function (Internals) {
  53247. /**
  53248. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53249. */
  53250. var PanoramaToCubeMapTools = (function () {
  53251. function PanoramaToCubeMapTools() {
  53252. }
  53253. /**
  53254. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53255. *
  53256. * @param float32Array The source data.
  53257. * @param inputWidth The width of the input panorama.
  53258. * @param inputhHeight The height of the input panorama.
  53259. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53260. * @return The cubemap data
  53261. */
  53262. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53263. if (!float32Array) {
  53264. throw "ConvertPanoramaToCubemap: input cannot be null";
  53265. }
  53266. if (float32Array.length != inputWidth * inputHeight * 3) {
  53267. throw "ConvertPanoramaToCubemap: input size is wrong";
  53268. }
  53269. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53270. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53271. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53272. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53273. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53274. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53275. return {
  53276. front: textureFront,
  53277. back: textureBack,
  53278. left: textureLeft,
  53279. right: textureRight,
  53280. up: textureUp,
  53281. down: textureDown,
  53282. size: size
  53283. };
  53284. };
  53285. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53286. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53287. var textureArray = new Float32Array(buffer);
  53288. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53289. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53290. var dy = 1 / texSize;
  53291. var fy = 0;
  53292. for (var y = 0; y < texSize; y++) {
  53293. var xv1 = faceData[0];
  53294. var xv2 = faceData[2];
  53295. for (var x = 0; x < texSize; x++) {
  53296. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53297. v.normalize();
  53298. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53299. // 3 channels per pixels
  53300. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53301. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53302. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53303. xv1 = xv1.add(rotDX1);
  53304. xv2 = xv2.add(rotDX2);
  53305. }
  53306. fy += dy;
  53307. }
  53308. return textureArray;
  53309. };
  53310. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53311. var theta = Math.atan2(vDir.z, vDir.x);
  53312. var phi = Math.acos(vDir.y);
  53313. while (theta < -Math.PI)
  53314. theta += 2 * Math.PI;
  53315. while (theta > Math.PI)
  53316. theta -= 2 * Math.PI;
  53317. var dx = theta / Math.PI;
  53318. var dy = phi / Math.PI;
  53319. // recenter.
  53320. dx = dx * 0.5 + 0.5;
  53321. var px = Math.round(dx * inputWidth);
  53322. if (px < 0)
  53323. px = 0;
  53324. else if (px >= inputWidth)
  53325. px = inputWidth - 1;
  53326. var py = Math.round(dy * inputHeight);
  53327. if (py < 0)
  53328. py = 0;
  53329. else if (py >= inputHeight)
  53330. py = inputHeight - 1;
  53331. var inputY = (inputHeight - py - 1);
  53332. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53333. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53334. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53335. return {
  53336. r: r,
  53337. g: g,
  53338. b: b
  53339. };
  53340. };
  53341. return PanoramaToCubeMapTools;
  53342. }());
  53343. PanoramaToCubeMapTools.FACE_FRONT = [
  53344. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53345. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53346. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53347. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53348. ];
  53349. PanoramaToCubeMapTools.FACE_BACK = [
  53350. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53351. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53352. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53353. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53354. ];
  53355. PanoramaToCubeMapTools.FACE_RIGHT = [
  53356. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53357. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53358. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53359. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53360. ];
  53361. PanoramaToCubeMapTools.FACE_LEFT = [
  53362. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53363. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53364. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53365. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53366. ];
  53367. PanoramaToCubeMapTools.FACE_DOWN = [
  53368. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53369. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53370. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53371. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53372. ];
  53373. PanoramaToCubeMapTools.FACE_UP = [
  53374. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53375. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53376. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53377. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53378. ];
  53379. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53380. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53381. })(BABYLON || (BABYLON = {}));
  53382. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  53383. var BABYLON;
  53384. (function (BABYLON) {
  53385. var Internals;
  53386. (function (Internals) {
  53387. ;
  53388. /**
  53389. * This groups tools to convert HDR texture to native colors array.
  53390. */
  53391. var HDRTools = (function () {
  53392. function HDRTools() {
  53393. }
  53394. HDRTools.Ldexp = function (mantissa, exponent) {
  53395. if (exponent > 1023) {
  53396. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53397. }
  53398. if (exponent < -1074) {
  53399. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53400. }
  53401. return mantissa * Math.pow(2, exponent);
  53402. };
  53403. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53404. if (exponent > 0) {
  53405. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53406. float32array[index + 0] = red * exponent;
  53407. float32array[index + 1] = green * exponent;
  53408. float32array[index + 2] = blue * exponent;
  53409. }
  53410. else {
  53411. float32array[index + 0] = 0;
  53412. float32array[index + 1] = 0;
  53413. float32array[index + 2] = 0;
  53414. }
  53415. };
  53416. HDRTools.readStringLine = function (uint8array, startIndex) {
  53417. var line = "";
  53418. var character = "";
  53419. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  53420. character = String.fromCharCode(uint8array[i]);
  53421. if (character == "\n") {
  53422. break;
  53423. }
  53424. line += character;
  53425. }
  53426. return line;
  53427. };
  53428. /**
  53429. * Reads header information from an RGBE texture stored in a native array.
  53430. * More information on this format are available here:
  53431. * https://en.wikipedia.org/wiki/RGBE_image_format
  53432. *
  53433. * @param uint8array The binary file stored in native array.
  53434. * @return The header information.
  53435. */
  53436. HDRTools.RGBE_ReadHeader = function (uint8array) {
  53437. var height = 0;
  53438. var width = 0;
  53439. var line = this.readStringLine(uint8array, 0);
  53440. if (line[0] != '#' || line[1] != '?') {
  53441. throw "Bad HDR Format.";
  53442. }
  53443. var endOfHeader = false;
  53444. var findFormat = false;
  53445. var lineIndex = 0;
  53446. do {
  53447. lineIndex += (line.length + 1);
  53448. line = this.readStringLine(uint8array, lineIndex);
  53449. if (line == "FORMAT=32-bit_rle_rgbe") {
  53450. findFormat = true;
  53451. }
  53452. else if (line.length == 0) {
  53453. endOfHeader = true;
  53454. }
  53455. } while (!endOfHeader);
  53456. if (!findFormat) {
  53457. throw "HDR Bad header format, unsupported FORMAT";
  53458. }
  53459. lineIndex += (line.length + 1);
  53460. line = this.readStringLine(uint8array, lineIndex);
  53461. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  53462. var match = sizeRegexp.exec(line);
  53463. // TODO. Support +Y and -X if needed.
  53464. if (match.length < 3) {
  53465. throw "HDR Bad header format, no size";
  53466. }
  53467. width = parseInt(match[2]);
  53468. height = parseInt(match[1]);
  53469. if (width < 8 || width > 0x7fff) {
  53470. throw "HDR Bad header format, unsupported size";
  53471. }
  53472. lineIndex += (line.length + 1);
  53473. return {
  53474. height: height,
  53475. width: width,
  53476. dataPosition: lineIndex
  53477. };
  53478. };
  53479. /**
  53480. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  53481. * This RGBE texture needs to store the information as a panorama.
  53482. *
  53483. * More information on this format are available here:
  53484. * https://en.wikipedia.org/wiki/RGBE_image_format
  53485. *
  53486. * @param buffer The binary file stored in an array buffer.
  53487. * @param size The expected size of the extracted cubemap.
  53488. * @return The Cube Map information.
  53489. */
  53490. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  53491. var uint8array = new Uint8Array(buffer);
  53492. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  53493. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53494. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  53495. return cubeMapData;
  53496. };
  53497. /**
  53498. * Returns the pixels data extracted from an RGBE texture.
  53499. * This pixels will be stored left to right up to down in the R G B order in one array.
  53500. *
  53501. * More information on this format are available here:
  53502. * https://en.wikipedia.org/wiki/RGBE_image_format
  53503. *
  53504. * @param uint8array The binary file stored in an array buffer.
  53505. * @param hdrInfo The header information of the file.
  53506. * @return The pixels data in RGB right to left up to down order.
  53507. */
  53508. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  53509. // Keep for multi format supports.
  53510. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53511. };
  53512. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  53513. var num_scanlines = hdrInfo.height;
  53514. var scanline_width = hdrInfo.width;
  53515. var a, b, c, d, count;
  53516. var dataIndex = hdrInfo.dataPosition;
  53517. var index = 0, endIndex = 0, i = 0;
  53518. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  53519. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  53520. // 3 channels of 4 bytes per pixel in float.
  53521. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  53522. var resultArray = new Float32Array(resultBuffer);
  53523. // read in each successive scanline
  53524. while (num_scanlines > 0) {
  53525. a = uint8array[dataIndex++];
  53526. b = uint8array[dataIndex++];
  53527. c = uint8array[dataIndex++];
  53528. d = uint8array[dataIndex++];
  53529. if (a != 2 || b != 2 || (c & 0x80)) {
  53530. // this file is not run length encoded
  53531. throw "HDR Bad header format, not RLE";
  53532. }
  53533. if (((c << 8) | d) != scanline_width) {
  53534. throw "HDR Bad header format, wrong scan line width";
  53535. }
  53536. index = 0;
  53537. // read each of the four channels for the scanline into the buffer
  53538. for (i = 0; i < 4; i++) {
  53539. endIndex = (i + 1) * scanline_width;
  53540. while (index < endIndex) {
  53541. a = uint8array[dataIndex++];
  53542. b = uint8array[dataIndex++];
  53543. if (a > 128) {
  53544. // a run of the same value
  53545. count = a - 128;
  53546. if ((count == 0) || (count > endIndex - index)) {
  53547. throw "HDR Bad Format, bad scanline data (run)";
  53548. }
  53549. while (count-- > 0) {
  53550. scanLineArray[index++] = b;
  53551. }
  53552. }
  53553. else {
  53554. // a non-run
  53555. count = a;
  53556. if ((count == 0) || (count > endIndex - index)) {
  53557. throw "HDR Bad Format, bad scanline data (non-run)";
  53558. }
  53559. scanLineArray[index++] = b;
  53560. if (--count > 0) {
  53561. for (var j = 0; j < count; j++) {
  53562. scanLineArray[index++] = uint8array[dataIndex++];
  53563. }
  53564. }
  53565. }
  53566. }
  53567. }
  53568. // now convert data from buffer into floats
  53569. for (i = 0; i < scanline_width; i++) {
  53570. a = scanLineArray[i];
  53571. b = scanLineArray[i + scanline_width];
  53572. c = scanLineArray[i + 2 * scanline_width];
  53573. d = scanLineArray[i + 3 * scanline_width];
  53574. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  53575. }
  53576. num_scanlines--;
  53577. }
  53578. return resultArray;
  53579. };
  53580. return HDRTools;
  53581. }());
  53582. Internals.HDRTools = HDRTools;
  53583. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53584. })(BABYLON || (BABYLON = {}));
  53585. //# sourceMappingURL=babylon.tools.hdr.js.map
  53586. //_______________________________________________________________
  53587. // Extracted from CubeMapGen:
  53588. // https://code.google.com/archive/p/cubemapgen/
  53589. //
  53590. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53591. //_______________________________________________________________
  53592. var BABYLON;
  53593. (function (BABYLON) {
  53594. var Internals;
  53595. (function (Internals) {
  53596. /**
  53597. * The bounding box information used during the conversion process.
  53598. */
  53599. var CMGBoundinBox = (function () {
  53600. function CMGBoundinBox() {
  53601. this.min = new BABYLON.Vector3(0, 0, 0);
  53602. this.max = new BABYLON.Vector3(0, 0, 0);
  53603. this.clear();
  53604. }
  53605. CMGBoundinBox.prototype.clear = function () {
  53606. this.min.x = CMGBoundinBox.MAX;
  53607. this.min.y = CMGBoundinBox.MAX;
  53608. this.min.z = CMGBoundinBox.MAX;
  53609. this.max.x = CMGBoundinBox.MIN;
  53610. this.max.y = CMGBoundinBox.MIN;
  53611. this.max.z = CMGBoundinBox.MIN;
  53612. };
  53613. CMGBoundinBox.prototype.augment = function (x, y, z) {
  53614. this.min.x = Math.min(this.min.x, x);
  53615. this.min.y = Math.min(this.min.y, y);
  53616. this.min.z = Math.min(this.min.z, z);
  53617. this.max.x = Math.max(this.max.x, x);
  53618. this.max.y = Math.max(this.max.y, y);
  53619. this.max.z = Math.max(this.max.z, z);
  53620. };
  53621. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  53622. this.min.x = Math.max(this.min.x, x);
  53623. this.min.y = Math.max(this.min.y, y);
  53624. this.min.z = Math.max(this.min.z, z);
  53625. };
  53626. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  53627. this.max.x = Math.min(this.max.x, x);
  53628. this.max.y = Math.min(this.max.y, y);
  53629. this.max.z = Math.min(this.max.z, z);
  53630. };
  53631. CMGBoundinBox.prototype.empty = function () {
  53632. if ((this.min.x > this.max.y) ||
  53633. (this.min.y > this.max.y) ||
  53634. (this.min.z > this.max.y)) {
  53635. return true;
  53636. }
  53637. else {
  53638. return false;
  53639. }
  53640. };
  53641. return CMGBoundinBox;
  53642. }());
  53643. CMGBoundinBox.MAX = Number.MAX_VALUE;
  53644. CMGBoundinBox.MIN = Number.MIN_VALUE;
  53645. /**
  53646. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  53647. * required by the glossinees of a material.
  53648. *
  53649. * This only supports the cosine drop power as well as Warp fixup generation method.
  53650. *
  53651. * This is using the process from CubeMapGen described here:
  53652. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53653. */
  53654. var PMREMGenerator = (function () {
  53655. /**
  53656. * Constructor of the generator.
  53657. *
  53658. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  53659. * @param inputSize The size of the cubemap faces
  53660. * @param outputSize The size of the output cubemap faces
  53661. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  53662. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  53663. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  53664. * @param specularPower The max specular level of the desired cubemap
  53665. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  53666. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  53667. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  53668. */
  53669. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  53670. this.input = input;
  53671. this.inputSize = inputSize;
  53672. this.outputSize = outputSize;
  53673. this.maxNumMipLevels = maxNumMipLevels;
  53674. this.numChannels = numChannels;
  53675. this.isFloat = isFloat;
  53676. this.specularPower = specularPower;
  53677. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  53678. this.excludeBase = excludeBase;
  53679. this.fixup = fixup;
  53680. this._outputSurface = [];
  53681. this._numMipLevels = 0;
  53682. }
  53683. /**
  53684. * Launches the filter process and return the result.
  53685. *
  53686. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  53687. */
  53688. PMREMGenerator.prototype.filterCubeMap = function () {
  53689. // Init cubemap processor
  53690. this.init();
  53691. // Filters the cubemap
  53692. this.filterCubeMapMipChain();
  53693. // Returns the filtered mips.
  53694. return this._outputSurface;
  53695. };
  53696. PMREMGenerator.prototype.init = function () {
  53697. var i;
  53698. var j;
  53699. var mipLevelSize;
  53700. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  53701. if (this.maxNumMipLevels == 0) {
  53702. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  53703. }
  53704. //first miplevel size
  53705. mipLevelSize = this.outputSize;
  53706. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  53707. for (j = 0; j < this.maxNumMipLevels; j++) {
  53708. this._outputSurface.length++;
  53709. this._outputSurface[j] = [];
  53710. //Iterate over faces for output images
  53711. for (i = 0; i < 6; i++) {
  53712. this._outputSurface[j].length++;
  53713. // Initializes a new array for the output.
  53714. if (this.isFloat) {
  53715. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53716. }
  53717. else {
  53718. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53719. }
  53720. }
  53721. //next mip level is half size
  53722. mipLevelSize >>= 1;
  53723. this._numMipLevels++;
  53724. //terminate if mip chain becomes too small
  53725. if (mipLevelSize == 0) {
  53726. this.maxNumMipLevels = j;
  53727. return;
  53728. }
  53729. }
  53730. };
  53731. //--------------------------------------------------------------------------------------
  53732. //Cube map filtering and mip chain generation.
  53733. // the cube map filtereing is specified using a number of parameters:
  53734. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  53735. // indicates the region of the hemisphere to filter over for each tap.
  53736. //
  53737. // Note that the top mip level is also a filtered version of the original input images
  53738. // as well in order to create mip chains for diffuse environment illumination.
  53739. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  53740. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  53741. //
  53742. // Then the mip angle used to genreate the next level of the mip chain from the first level
  53743. // is a_InitialMipAngle
  53744. //
  53745. // The angle for the subsequent levels of the mip chain are specified by their parents
  53746. // filtering angle and a per-level scale and bias
  53747. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  53748. //
  53749. //--------------------------------------------------------------------------------------
  53750. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  53751. // First, take count of the lighting model to modify SpecularPower
  53752. // 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;
  53753. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  53754. //Cone angle start (for generating subsequent mip levels)
  53755. var currentSpecularPower = this.specularPower;
  53756. //Build filter lookup tables based on the source miplevel size
  53757. this.precomputeFilterLookupTables(this.inputSize);
  53758. // Note that we need to filter the first level before generating mipmap
  53759. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  53760. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  53761. // TODO : Write a function to copy and scale the base mipmap in output
  53762. // I am just lazy here and just put a high specular power value, and do some if.
  53763. if (this.excludeBase && (levelIndex == 0)) {
  53764. // 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).
  53765. currentSpecularPower = 100000.0;
  53766. }
  53767. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  53768. var srcCubeImage = this.input;
  53769. var dstCubeImage = this._outputSurface[levelIndex];
  53770. var dstSize = this.outputSize >> levelIndex;
  53771. // Compute required angle.
  53772. var angle = this.getBaseFilterAngle(currentSpecularPower);
  53773. // filter cube surfaces
  53774. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  53775. // fix seams
  53776. if (this.fixup) {
  53777. this.fixupCubeEdges(dstCubeImage, dstSize);
  53778. }
  53779. // Decrease the specular power to generate the mipmap chain
  53780. // TODO : Use another method for Exclude (see first comment at start of the function
  53781. if (this.excludeBase && (levelIndex == 0)) {
  53782. currentSpecularPower = this.specularPower;
  53783. }
  53784. currentSpecularPower *= this.cosinePowerDropPerMip;
  53785. }
  53786. };
  53787. //--------------------------------------------------------------------------------------
  53788. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  53789. // It allow to optimize the texel to access base on the specular power.
  53790. //--------------------------------------------------------------------------------------
  53791. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  53792. // We want to find the alpha such that:
  53793. // cos(alpha)^cosinePower = epsilon
  53794. // That's: acos(epsilon^(1/cosinePower))
  53795. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  53796. var angle = 180.0;
  53797. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  53798. angle *= 180.0 / Math.PI; // Convert to degree
  53799. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  53800. return angle;
  53801. };
  53802. //--------------------------------------------------------------------------------------
  53803. //Builds the following lookup tables prior to filtering:
  53804. // -normalizer cube map
  53805. // -tap weight lookup table
  53806. //
  53807. //--------------------------------------------------------------------------------------
  53808. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  53809. var srcTexelAngle;
  53810. var iCubeFace;
  53811. //clear pre-existing normalizer cube map
  53812. this._normCubeMap = [];
  53813. //Normalized vectors per cubeface and per-texel solid angle
  53814. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  53815. };
  53816. //--------------------------------------------------------------------------------------
  53817. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  53818. //
  53819. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  53820. //
  53821. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  53822. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  53823. // below
  53824. //--------------------------------------------------------------------------------------
  53825. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  53826. var iCubeFace;
  53827. var u;
  53828. var v;
  53829. //iterate over cube faces
  53830. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53831. //First three channels for norm cube, and last channel for solid angle
  53832. this._normCubeMap.push(new Float32Array(size * size * 4));
  53833. //fast texture walk, build normalizer cube map
  53834. var facesData = this.input[iCubeFace];
  53835. for (v = 0; v < size; v++) {
  53836. for (u = 0; u < size; u++) {
  53837. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  53838. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  53839. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  53840. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  53841. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  53842. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  53843. }
  53844. }
  53845. }
  53846. };
  53847. //--------------------------------------------------------------------------------------
  53848. // Convert cubemap face texel coordinates and face idx to 3D vector
  53849. // note the U and V coords are integer coords and range from 0 to size-1
  53850. // this routine can be used to generate a normalizer cube map
  53851. //--------------------------------------------------------------------------------------
  53852. // SL BEGIN
  53853. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  53854. var nvcU;
  53855. var nvcV;
  53856. var tempVec;
  53857. // Change from original AMD code
  53858. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53859. // + 0.5f is for texel center addressing
  53860. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  53861. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  53862. // warp fixup
  53863. if (fixup && size > 1) {
  53864. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  53865. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  53866. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  53867. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  53868. }
  53869. // Get current vector
  53870. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  53871. // U contribution
  53872. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53873. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  53874. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  53875. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  53876. // V contribution and Sum
  53877. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53878. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  53879. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  53880. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  53881. //add face axis
  53882. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  53883. PMREMGenerator._vectorTemp.x += faceAxis[0];
  53884. PMREMGenerator._vectorTemp.y += faceAxis[1];
  53885. PMREMGenerator._vectorTemp.z += faceAxis[2];
  53886. //normalize vector
  53887. PMREMGenerator._vectorTemp.normalize();
  53888. return PMREMGenerator._vectorTemp;
  53889. };
  53890. //--------------------------------------------------------------------------------------
  53891. // Convert 3D vector to cubemap face texel coordinates and face idx
  53892. // note the U and V coords are integer coords and range from 0 to size-1
  53893. // this routine can be used to generate a normalizer cube map
  53894. //
  53895. // returns face IDX and texel coords
  53896. //--------------------------------------------------------------------------------------
  53897. // SL BEGIN
  53898. /*
  53899. Mapping Texture Coordinates to Cube Map Faces
  53900. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  53901. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  53902. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  53903. map arrangement in Pixar's RenderMan package.
  53904. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  53905. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  53906. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  53907. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  53908. the major axis direction). The target column in the table below explains how the major axis direction
  53909. maps to the 2D image of a particular cube map target.
  53910. major axis
  53911. direction target sc tc ma
  53912. ---------- --------------------------------- --- --- ---
  53913. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  53914. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  53915. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  53916. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  53917. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  53918. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  53919. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  53920. an updated (s,t) is calculated as follows
  53921. s = ( sc/|ma| + 1 ) / 2
  53922. t = ( tc/|ma| + 1 ) / 2
  53923. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  53924. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  53925. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  53926. */
  53927. // Note this method return U and V in range from 0 to size-1
  53928. // SL END
  53929. // Store the information in vector3 for convenience (faceindex, u, v)
  53930. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  53931. var maxCoord;
  53932. var faceIdx;
  53933. //absolute value 3
  53934. var absX = Math.abs(x);
  53935. var absY = Math.abs(y);
  53936. var absZ = Math.abs(z);
  53937. if (absX >= absY && absX >= absZ) {
  53938. maxCoord = absX;
  53939. if (x >= 0) {
  53940. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  53941. }
  53942. else {
  53943. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  53944. }
  53945. }
  53946. else if (absY >= absX && absY >= absZ) {
  53947. maxCoord = absY;
  53948. if (y >= 0) {
  53949. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  53950. }
  53951. else {
  53952. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  53953. }
  53954. }
  53955. else {
  53956. maxCoord = absZ;
  53957. if (z >= 0) {
  53958. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  53959. }
  53960. else {
  53961. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  53962. }
  53963. }
  53964. //divide through by max coord so face vector lies on cube face
  53965. var scale = 1 / maxCoord;
  53966. x *= scale;
  53967. y *= scale;
  53968. z *= scale;
  53969. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53970. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  53971. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53972. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  53973. // Modify original AMD code to return value from 0 to Size - 1
  53974. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  53975. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  53976. PMREMGenerator._vectorTemp.x = faceIdx;
  53977. PMREMGenerator._vectorTemp.y = u;
  53978. PMREMGenerator._vectorTemp.z = v;
  53979. return PMREMGenerator._vectorTemp;
  53980. };
  53981. //--------------------------------------------------------------------------------------
  53982. //Original code from Ignacio CastaÒo
  53983. // This formula is from Manne ÷hrstrˆm's thesis.
  53984. // Take two coordiantes in the range [-1, 1] that define a portion of a
  53985. // cube face and return the area of the projection of that portion on the
  53986. // surface of the sphere.
  53987. //--------------------------------------------------------------------------------------
  53988. PMREMGenerator.prototype.areaElement = function (x, y) {
  53989. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  53990. };
  53991. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  53992. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53993. // (+ 0.5f is for texel center addressing)
  53994. u = (2.0 * (u + 0.5) / size) - 1.0;
  53995. v = (2.0 * (v + 0.5) / size) - 1.0;
  53996. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  53997. var invResolution = 1.0 / size;
  53998. // U and V are the -1..1 texture coordinate on the current face.
  53999. // Get projected area for this texel
  54000. var x0 = u - invResolution;
  54001. var y0 = v - invResolution;
  54002. var x1 = u + invResolution;
  54003. var y1 = v + invResolution;
  54004. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  54005. return solidAngle;
  54006. };
  54007. //--------------------------------------------------------------------------------------
  54008. //The key to the speed of these filtering routines is to quickly define a per-face
  54009. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  54010. // Later these pixels are selectively processed based on their dot products to see if
  54011. // they reside within the filtering cone.
  54012. //
  54013. //This is done by computing the smallest per-texel angle to get a conservative estimate
  54014. // of the number of texels needed to be covered in width and height order to filter the
  54015. // region. the bounding box for the center taps face is defined first, and if the
  54016. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  54017. // defined next
  54018. //--------------------------------------------------------------------------------------
  54019. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  54020. // note that pixels within these regions may be rejected
  54021. // based on the anlge
  54022. var iCubeFace;
  54023. var u;
  54024. var v;
  54025. // bounding box per face to specify region to process
  54026. var filterExtents = [];
  54027. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54028. filterExtents.push(new CMGBoundinBox());
  54029. }
  54030. // min angle a src texel can cover (in degrees)
  54031. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  54032. // angle about center tap to define filter cone
  54033. // filter angle is 1/2 the cone angle
  54034. var filterAngle = filterConeAngle / 2.0;
  54035. //ensure filter angle is larger than a texel
  54036. if (filterAngle < srcTexelAngle) {
  54037. filterAngle = srcTexelAngle;
  54038. }
  54039. //ensure filter cone is always smaller than the hemisphere
  54040. if (filterAngle > 90.0) {
  54041. filterAngle = 90.0;
  54042. }
  54043. // the maximum number of texels in 1D the filter cone angle will cover
  54044. // used to determine bounding box size for filter extents
  54045. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  54046. // ensure conservative region always covers at least one texel
  54047. if (filterSize < 1) {
  54048. filterSize = 1;
  54049. }
  54050. // dotProdThresh threshold based on cone angle to determine whether or not taps
  54051. // reside within the cone angle
  54052. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  54053. // process required faces
  54054. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54055. //iterate over dst cube map face texel
  54056. for (v = 0; v < dstSize; v++) {
  54057. for (u = 0; u < dstSize; u++) {
  54058. //get center tap direction
  54059. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  54060. //clear old per-face filter extents
  54061. this.clearFilterExtents(filterExtents);
  54062. //define per-face filter extents
  54063. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  54064. //perform filtering of src faces using filter extents
  54065. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  54066. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  54067. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  54068. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  54069. }
  54070. }
  54071. }
  54072. };
  54073. //--------------------------------------------------------------------------------------
  54074. //Clear filter extents for the 6 cube map faces
  54075. //--------------------------------------------------------------------------------------
  54076. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54077. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54078. filterExtents[iCubeFaces].clear();
  54079. }
  54080. };
  54081. //--------------------------------------------------------------------------------------
  54082. //Define per-face bounding box filter extents
  54083. //
  54084. // These define conservative texel regions in each of the faces the filter can possibly
  54085. // process. When the pixels in the regions are actually processed, the dot product
  54086. // between the tap vector and the center tap vector is used to determine the weight of
  54087. // the tap and whether or not the tap is within the cone.
  54088. //
  54089. //--------------------------------------------------------------------------------------
  54090. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54091. //neighboring face and bleed over amount, and width of BBOX for
  54092. // left, right, top, and bottom edges of this face
  54093. var bleedOverAmount = [0, 0, 0, 0];
  54094. var bleedOverBBoxMin = [0, 0, 0, 0];
  54095. var bleedOverBBoxMax = [0, 0, 0, 0];
  54096. var neighborFace;
  54097. var neighborEdge;
  54098. var oppositeFaceIdx;
  54099. //get face idx, and u, v info from center tap dir
  54100. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54101. var faceIdx = result.x;
  54102. var u = result.y;
  54103. var v = result.z;
  54104. //define bbox size within face
  54105. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54106. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54107. filterExtents[faceIdx].clampMin(0, 0, 0);
  54108. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54109. //u and v extent in face corresponding to center tap
  54110. var minU = filterExtents[faceIdx].min.x;
  54111. var minV = filterExtents[faceIdx].min.y;
  54112. var maxU = filterExtents[faceIdx].max.x;
  54113. var maxV = filterExtents[faceIdx].max.y;
  54114. //bleed over amounts for face across u=0 edge (left)
  54115. bleedOverAmount[0] = (bboxSize - u);
  54116. bleedOverBBoxMin[0] = minV;
  54117. bleedOverBBoxMax[0] = maxV;
  54118. //bleed over amounts for face across u=1 edge (right)
  54119. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54120. bleedOverBBoxMin[1] = minV;
  54121. bleedOverBBoxMax[1] = maxV;
  54122. //bleed over to face across v=0 edge (up)
  54123. bleedOverAmount[2] = (bboxSize - v);
  54124. bleedOverBBoxMin[2] = minU;
  54125. bleedOverBBoxMax[2] = maxU;
  54126. //bleed over to face across v=1 edge (down)
  54127. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54128. bleedOverBBoxMin[3] = minU;
  54129. bleedOverBBoxMax[3] = maxU;
  54130. //compute bleed over regions in neighboring faces
  54131. for (var i = 0; i < 4; i++) {
  54132. if (bleedOverAmount[i] > 0) {
  54133. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54134. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54135. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54136. // be flipped: the cases are
  54137. // if a left edge mates with a left or bottom edge on the neighbor
  54138. // if a top edge mates with a top or right edge on the neighbor
  54139. // if a right edge mates with a right or top edge on the neighbor
  54140. // if a bottom edge mates with a bottom or left edge on the neighbor
  54141. //Seeing as the edges are enumerated as follows
  54142. // left =0
  54143. // right =1
  54144. // top =2
  54145. // bottom =3
  54146. //
  54147. // so if the edge enums are the same, or the sum of the enums == 3,
  54148. // the bbox needs to be flipped
  54149. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54150. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54151. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54152. }
  54153. //The way the bounding box is extended onto the neighboring face
  54154. // depends on which edge of neighboring face abuts with this one
  54155. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54156. case PMREMGenerator.CP_EDGE_LEFT:
  54157. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54158. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54159. break;
  54160. case PMREMGenerator.CP_EDGE_RIGHT:
  54161. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54162. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54163. break;
  54164. case PMREMGenerator.CP_EDGE_TOP:
  54165. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54166. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54167. break;
  54168. case PMREMGenerator.CP_EDGE_BOTTOM:
  54169. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54170. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54171. break;
  54172. }
  54173. //clamp filter extents in non-center tap faces to remain within surface
  54174. filterExtents[neighborFace].clampMin(0, 0, 0);
  54175. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54176. }
  54177. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54178. // from the center tap face, then process the opposite face entirely for now.
  54179. //Note that the cases in which this happens, what usually happens is that
  54180. // more than one edge bleeds onto the opposite face, and the bounding box
  54181. // encompasses the entire cube map face.
  54182. if (bleedOverAmount[i] > srcSize) {
  54183. //determine opposite face
  54184. switch (faceIdx) {
  54185. case PMREMGenerator.CP_FACE_X_POS:
  54186. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54187. break;
  54188. case PMREMGenerator.CP_FACE_X_NEG:
  54189. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54190. break;
  54191. case PMREMGenerator.CP_FACE_Y_POS:
  54192. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54193. break;
  54194. case PMREMGenerator.CP_FACE_Y_NEG:
  54195. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54196. break;
  54197. case PMREMGenerator.CP_FACE_Z_POS:
  54198. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54199. break;
  54200. case PMREMGenerator.CP_FACE_Z_NEG:
  54201. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54202. break;
  54203. default:
  54204. break;
  54205. }
  54206. //just encompass entire face for now
  54207. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54208. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54209. }
  54210. }
  54211. };
  54212. //--------------------------------------------------------------------------------------
  54213. //ProcessFilterExtents
  54214. // Process bounding box in each cube face
  54215. //
  54216. //--------------------------------------------------------------------------------------
  54217. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54218. //accumulators are 64-bit floats in order to have the precision needed
  54219. // over a summation of a large number of pixels
  54220. var dstAccum = [0, 0, 0, 0];
  54221. var weightAccum = 0;
  54222. var k = 0;
  54223. var nSrcChannels = this.numChannels;
  54224. // norm cube map and srcCubeMap have same face width
  54225. var faceWidth = srcSize;
  54226. //amount to add to pointer to move to next scanline in images
  54227. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54228. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54229. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54230. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54231. // iterate over cubefaces
  54232. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54233. //if bbox is non empty
  54234. if (!filterExtents[iFaceIdx].empty()) {
  54235. var uStart = filterExtents[iFaceIdx].min.x;
  54236. var vStart = filterExtents[iFaceIdx].min.y;
  54237. var uEnd = filterExtents[iFaceIdx].max.x;
  54238. var vEnd = filterExtents[iFaceIdx].max.y;
  54239. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54240. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54241. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54242. for (var v = vStart; v <= vEnd; v++) {
  54243. var normCubeRowWalk = 0;
  54244. var srcCubeRowWalk = 0;
  54245. for (var u = uStart; u <= uEnd; u++) {
  54246. //pointer to direction in cube map associated with texel
  54247. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54248. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54249. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54250. //check dot product to see if texel is within cone
  54251. var tapDotProd = texelVectX * centerTapDir.x +
  54252. texelVectY * centerTapDir.y +
  54253. texelVectZ * centerTapDir.z;
  54254. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54255. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54256. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54257. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54258. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54259. // so just adding one to specularpower do the trick.
  54260. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54261. //iterate over channels
  54262. for (k = 0; k < nSrcChannels; k++) {
  54263. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54264. srcCubeRowWalk++;
  54265. }
  54266. weightAccum += weight; //accumulate weight
  54267. }
  54268. else {
  54269. //step across source pixel
  54270. srcCubeRowWalk += nSrcChannels;
  54271. }
  54272. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54273. }
  54274. startIndexNormCubeMap += normCubePitch;
  54275. startIndexSrcCubeMap += srcCubePitch;
  54276. }
  54277. }
  54278. }
  54279. //divide through by weights if weight is non zero
  54280. if (weightAccum != 0.0) {
  54281. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54282. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54283. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54284. if (this.numChannels > 3) {
  54285. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54286. }
  54287. }
  54288. else {
  54289. // otherwise sample nearest
  54290. // get face idx and u, v texel coordinate in face
  54291. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54292. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54293. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54294. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54295. if (this.numChannels > 3) {
  54296. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54297. }
  54298. }
  54299. return PMREMGenerator._vectorTemp;
  54300. };
  54301. //--------------------------------------------------------------------------------------
  54302. // Fixup cube edges
  54303. //
  54304. // average texels on cube map faces across the edges
  54305. // WARP/BENT Method Only.
  54306. //--------------------------------------------------------------------------------------
  54307. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54308. var k;
  54309. var j;
  54310. var i;
  54311. var iFace;
  54312. var iCorner = 0;
  54313. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54314. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54315. // note that if functionality to filter across the three texels for each corner, then
  54316. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54317. var cornerPtr = [
  54318. [[], [], []],
  54319. [[], [], []],
  54320. [[], [], []],
  54321. [[], [], []],
  54322. [[], [], []],
  54323. [[], [], []],
  54324. [[], [], []],
  54325. [[], [], []]
  54326. ];
  54327. //if there is no fixup, or fixup width = 0, do nothing
  54328. if (cubeMapSize < 1) {
  54329. return;
  54330. }
  54331. //special case 1x1 cubemap, average face colors
  54332. if (cubeMapSize == 1) {
  54333. //iterate over channels
  54334. for (k = 0; k < this.numChannels; k++) {
  54335. var accum = 0.0;
  54336. //iterate over faces to accumulate face colors
  54337. for (iFace = 0; iFace < 6; iFace++) {
  54338. accum += cubeMap[iFace][k];
  54339. }
  54340. //compute average over 6 face colors
  54341. accum /= 6.0;
  54342. //iterate over faces to distribute face colors
  54343. for (iFace = 0; iFace < 6; iFace++) {
  54344. cubeMap[iFace][k] = accum;
  54345. }
  54346. }
  54347. return;
  54348. }
  54349. //iterate over faces to collect list of corner texel pointers
  54350. for (iFace = 0; iFace < 6; iFace++) {
  54351. //the 4 corner pointers for this face
  54352. faceCornerStartIndicies[0] = [iFace, 0];
  54353. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54354. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54355. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54356. //iterate over face corners to collect cube corner pointers
  54357. for (iCorner = 0; iCorner < 4; iCorner++) {
  54358. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54359. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54360. cornerNumPtrs[corner]++;
  54361. }
  54362. }
  54363. //iterate over corners to average across corner tap values
  54364. for (iCorner = 0; iCorner < 8; iCorner++) {
  54365. for (k = 0; k < this.numChannels; k++) {
  54366. var cornerTapAccum = 0.0;
  54367. //iterate over corner texels and average results
  54368. for (i = 0; i < 3; i++) {
  54369. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54370. }
  54371. //divide by 3 to compute average of corner tap values
  54372. cornerTapAccum *= (1.0 / 3.0);
  54373. //iterate over corner texels and average results
  54374. for (i = 0; i < 3; i++) {
  54375. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54376. }
  54377. }
  54378. }
  54379. //iterate over the twelve edges of the cube to average across edges
  54380. for (i = 0; i < 12; i++) {
  54381. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54382. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54383. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54384. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54385. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54386. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54387. var edgeWalk = 0;
  54388. var neighborEdgeWalk = 0;
  54389. //Determine walking pointers based on edge type
  54390. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54391. switch (edge) {
  54392. case PMREMGenerator.CP_EDGE_LEFT:
  54393. // no change to faceEdgeStartPtr
  54394. edgeWalk = this.numChannels * cubeMapSize;
  54395. break;
  54396. case PMREMGenerator.CP_EDGE_RIGHT:
  54397. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54398. edgeWalk = this.numChannels * cubeMapSize;
  54399. break;
  54400. case PMREMGenerator.CP_EDGE_TOP:
  54401. // no change to faceEdgeStartPtr
  54402. edgeWalk = this.numChannels;
  54403. break;
  54404. case PMREMGenerator.CP_EDGE_BOTTOM:
  54405. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54406. edgeWalk = this.numChannels;
  54407. break;
  54408. }
  54409. //For certain types of edge abutments, the neighbor edge walk needs to
  54410. // be flipped: the cases are
  54411. // if a left edge mates with a left or bottom edge on the neighbor
  54412. // if a top edge mates with a top or right edge on the neighbor
  54413. // if a right edge mates with a right or top edge on the neighbor
  54414. // if a bottom edge mates with a bottom or left edge on the neighbor
  54415. //Seeing as the edges are enumerated as follows
  54416. // left =0
  54417. // right =1
  54418. // top =2
  54419. // bottom =3
  54420. //
  54421. //If the edge enums are the same, or the sum of the enums == 3,
  54422. // the neighbor edge walk needs to be flipped
  54423. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  54424. switch (neighborEdge) {
  54425. case PMREMGenerator.CP_EDGE_LEFT:
  54426. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  54427. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54428. break;
  54429. case PMREMGenerator.CP_EDGE_RIGHT:
  54430. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54431. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54432. break;
  54433. case PMREMGenerator.CP_EDGE_TOP:
  54434. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54435. neighborEdgeWalk = -this.numChannels;
  54436. break;
  54437. case PMREMGenerator.CP_EDGE_BOTTOM:
  54438. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54439. neighborEdgeWalk = -this.numChannels;
  54440. break;
  54441. }
  54442. }
  54443. else {
  54444. //swapped direction neighbor edge walk
  54445. switch (neighborEdge) {
  54446. case PMREMGenerator.CP_EDGE_LEFT:
  54447. //no change to neighborEdgeStartPtr for this case since it points
  54448. // to the upper left corner already
  54449. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54450. break;
  54451. case PMREMGenerator.CP_EDGE_RIGHT:
  54452. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54453. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54454. break;
  54455. case PMREMGenerator.CP_EDGE_TOP:
  54456. //no change to neighborEdgeStartPtr for this case since it points
  54457. // to the upper left corner already
  54458. neighborEdgeWalk = this.numChannels;
  54459. break;
  54460. case PMREMGenerator.CP_EDGE_BOTTOM:
  54461. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54462. neighborEdgeWalk = this.numChannels;
  54463. break;
  54464. }
  54465. }
  54466. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  54467. //nearby neighborhood
  54468. //step ahead one texel on edge
  54469. edgeStartIndex += edgeWalk;
  54470. neighborEdgeStartIndex += neighborEdgeWalk;
  54471. // note that this loop does not process the corner texels, since they have already been
  54472. // averaged across faces across earlier
  54473. for (j = 1; j < (cubeMapSize - 1); j++) {
  54474. //for each set of taps along edge, average them
  54475. // and rewrite the results into the edges
  54476. for (k = 0; k < this.numChannels; k++) {
  54477. var edgeTap = cubeMap[face][edgeStartIndex + k];
  54478. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  54479. //compute average of tap intensity values
  54480. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  54481. //propagate average of taps to edge taps
  54482. cubeMap[face][edgeStartIndex + k] = avgTap;
  54483. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  54484. }
  54485. edgeStartIndex += edgeWalk;
  54486. neighborEdgeStartIndex += neighborEdgeWalk;
  54487. }
  54488. }
  54489. };
  54490. return PMREMGenerator;
  54491. }());
  54492. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  54493. PMREMGenerator.CP_UDIR = 0;
  54494. PMREMGenerator.CP_VDIR = 1;
  54495. PMREMGenerator.CP_FACEAXIS = 2;
  54496. //used to index cube faces
  54497. PMREMGenerator.CP_FACE_X_POS = 0;
  54498. PMREMGenerator.CP_FACE_X_NEG = 1;
  54499. PMREMGenerator.CP_FACE_Y_POS = 2;
  54500. PMREMGenerator.CP_FACE_Y_NEG = 3;
  54501. PMREMGenerator.CP_FACE_Z_POS = 4;
  54502. PMREMGenerator.CP_FACE_Z_NEG = 5;
  54503. //used to index image edges
  54504. // NOTE.. the actual number corresponding to the edge is important
  54505. // do not change these, or the code will break
  54506. //
  54507. // CP_EDGE_LEFT is u = 0
  54508. // CP_EDGE_RIGHT is u = width-1
  54509. // CP_EDGE_TOP is v = 0
  54510. // CP_EDGE_BOTTOM is v = height-1
  54511. PMREMGenerator.CP_EDGE_LEFT = 0;
  54512. PMREMGenerator.CP_EDGE_RIGHT = 1;
  54513. PMREMGenerator.CP_EDGE_TOP = 2;
  54514. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  54515. //corners of CUBE map (P or N specifys if it corresponds to the
  54516. // positive or negative direction each of X, Y, and Z
  54517. PMREMGenerator.CP_CORNER_NNN = 0;
  54518. PMREMGenerator.CP_CORNER_NNP = 1;
  54519. PMREMGenerator.CP_CORNER_NPN = 2;
  54520. PMREMGenerator.CP_CORNER_NPP = 3;
  54521. PMREMGenerator.CP_CORNER_PNN = 4;
  54522. PMREMGenerator.CP_CORNER_PNP = 5;
  54523. PMREMGenerator.CP_CORNER_PPN = 6;
  54524. PMREMGenerator.CP_CORNER_PPP = 7;
  54525. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  54526. //3x2 matrices that map cube map indexing vectors in 3d
  54527. // (after face selection and divide through by the
  54528. // _ABSOLUTE VALUE_ of the max coord)
  54529. // into NVC space
  54530. //Note this currently assumes the D3D cube face ordering and orientation
  54531. PMREMGenerator._sgFace2DMapping = [
  54532. //XPOS face
  54533. [[0, 0, -1],
  54534. [0, -1, 0],
  54535. [1, 0, 0]],
  54536. //XNEG face
  54537. [[0, 0, 1],
  54538. [0, -1, 0],
  54539. [-1, 0, 0]],
  54540. //YPOS face
  54541. [[1, 0, 0],
  54542. [0, 0, 1],
  54543. [0, 1, 0]],
  54544. //YNEG face
  54545. [[1, 0, 0],
  54546. [0, 0, -1],
  54547. [0, -1, 0]],
  54548. //ZPOS face
  54549. [[1, 0, 0],
  54550. [0, -1, 0],
  54551. [0, 0, 1]],
  54552. //ZNEG face
  54553. [[-1, 0, 0],
  54554. [0, -1, 0],
  54555. [0, 0, -1]],
  54556. ];
  54557. //------------------------------------------------------------------------------
  54558. // D3D cube map face specification
  54559. // mapping from 3D x,y,z cube map lookup coordinates
  54560. // to 2D within face u,v coordinates
  54561. //
  54562. // --------------------> U direction
  54563. // | (within-face texture space)
  54564. // | _____
  54565. // | | |
  54566. // | | +Y |
  54567. // | _____|_____|_____ _____
  54568. // | | | | | |
  54569. // | | -X | +Z | +X | -Z |
  54570. // | |_____|_____|_____|_____|
  54571. // | | |
  54572. // | | -Y |
  54573. // | |_____|
  54574. // |
  54575. // v V direction
  54576. // (within-face texture space)
  54577. //------------------------------------------------------------------------------
  54578. //Information about neighbors and how texture coorrdinates change across faces
  54579. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  54580. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  54581. //Note this currently assumes the D3D cube face ordering and orientation
  54582. PMREMGenerator._sgCubeNgh = [
  54583. //XPOS face
  54584. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54585. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54586. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54587. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  54588. //XNEG face
  54589. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54590. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  54591. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  54592. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  54593. //YPOS face
  54594. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54595. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54596. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54597. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  54598. //YNEG face
  54599. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54600. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54601. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54602. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  54603. //ZPOS face
  54604. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54605. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54606. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54607. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  54608. //ZNEG face
  54609. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54610. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54611. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  54612. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  54613. ];
  54614. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  54615. // this table is used to average over the edges.
  54616. PMREMGenerator._sgCubeEdgeList = [
  54617. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54618. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54619. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54620. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54621. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54622. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54623. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54624. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54625. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  54626. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54627. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54628. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  54629. ];
  54630. //Information about which of the 8 cube corners are correspond to the
  54631. // the 4 corners in each cube face
  54632. // the order is upper left, upper right, lower left, lower right
  54633. PMREMGenerator._sgCubeCornerList = [
  54634. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  54635. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  54636. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  54637. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  54638. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  54639. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  54640. ];
  54641. Internals.PMREMGenerator = PMREMGenerator;
  54642. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54643. })(BABYLON || (BABYLON = {}));
  54644. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  54645. var BABYLON;
  54646. (function (BABYLON) {
  54647. /**
  54648. * This represents a texture coming from an HDR input.
  54649. *
  54650. * The only supported format is currently panorama picture stored in RGBE format.
  54651. * Example of such files can be found on HDRLib: http://hdrlib.com/
  54652. */
  54653. var HDRCubeTexture = (function (_super) {
  54654. __extends(HDRCubeTexture, _super);
  54655. /**
  54656. * Instantiates an HDRTexture from the following parameters.
  54657. *
  54658. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  54659. * @param scene The scene the texture will be used in
  54660. * @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.
  54661. * @param noMipmap Forces to not generate the mipmap if true
  54662. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  54663. * @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)
  54664. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  54665. */
  54666. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  54667. if (noMipmap === void 0) { noMipmap = false; }
  54668. if (generateHarmonics === void 0) { generateHarmonics = true; }
  54669. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  54670. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  54671. if (onLoad === void 0) { onLoad = null; }
  54672. if (onError === void 0) { onError = null; }
  54673. var _this = _super.call(this, scene) || this;
  54674. _this._useInGammaSpace = false;
  54675. _this._generateHarmonics = true;
  54676. _this._isBABYLONPreprocessed = false;
  54677. _this._onLoad = null;
  54678. _this._onError = null;
  54679. /**
  54680. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  54681. */
  54682. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54683. /**
  54684. * The spherical polynomial data extracted from the texture.
  54685. */
  54686. _this.sphericalPolynomial = null;
  54687. /**
  54688. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  54689. * This is usefull at run time to apply the good shader.
  54690. */
  54691. _this.isPMREM = false;
  54692. if (!url) {
  54693. return _this;
  54694. }
  54695. _this.name = url;
  54696. _this.url = url;
  54697. _this.hasAlpha = false;
  54698. _this.isCube = true;
  54699. _this._textureMatrix = BABYLON.Matrix.Identity();
  54700. _this._onLoad = onLoad;
  54701. _this._onError = onError;
  54702. if (size) {
  54703. _this._isBABYLONPreprocessed = false;
  54704. _this._noMipmap = noMipmap;
  54705. _this._size = size;
  54706. _this._useInGammaSpace = useInGammaSpace;
  54707. _this._usePMREMGenerator = usePMREMGenerator &&
  54708. scene.getEngine().getCaps().textureLOD &&
  54709. _this.getScene().getEngine().getCaps().textureFloat &&
  54710. !_this._useInGammaSpace;
  54711. }
  54712. else {
  54713. _this._isBABYLONPreprocessed = true;
  54714. _this._noMipmap = false;
  54715. _this._useInGammaSpace = false;
  54716. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  54717. _this.getScene().getEngine().getCaps().textureFloat &&
  54718. !_this._useInGammaSpace;
  54719. }
  54720. _this.isPMREM = _this._usePMREMGenerator;
  54721. _this._texture = _this._getFromCache(url, _this._noMipmap);
  54722. if (!_this._texture) {
  54723. if (!scene.useDelayedTextureLoading) {
  54724. _this.loadTexture();
  54725. }
  54726. else {
  54727. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54728. }
  54729. }
  54730. return _this;
  54731. }
  54732. /**
  54733. * Occurs when the file is a preprocessed .babylon.hdr file.
  54734. */
  54735. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  54736. var _this = this;
  54737. var mipLevels = 0;
  54738. var floatArrayView = null;
  54739. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  54740. var mips = [];
  54741. var startIndex = 30;
  54742. for (var level = 0; level < mipLevels; level++) {
  54743. mips.push([]);
  54744. // Fill each pixel of the mip level.
  54745. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  54746. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54747. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  54748. mips[level].push(faceData);
  54749. startIndex += faceSize;
  54750. }
  54751. }
  54752. return mips;
  54753. } : null;
  54754. var callback = function (buffer) {
  54755. // Create Native Array Views
  54756. var intArrayView = new Int32Array(buffer);
  54757. floatArrayView = new Float32Array(buffer);
  54758. // Fill header.
  54759. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  54760. _this._size = intArrayView[1]; // CubeMap max mip face size.
  54761. // Update Texture Information.
  54762. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  54763. // Fill polynomial information.
  54764. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  54765. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  54766. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  54767. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  54768. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  54769. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  54770. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  54771. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  54772. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  54773. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  54774. // Fill pixel data.
  54775. mipLevels = intArrayView[29]; // Number of mip levels.
  54776. var startIndex = 30;
  54777. var data = [];
  54778. var faceSize = Math.pow(_this._size, 2) * 3;
  54779. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54780. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  54781. startIndex += faceSize;
  54782. }
  54783. var results = [];
  54784. var byteArray = null;
  54785. // Push each faces.
  54786. for (var k = 0; k < 6; k++) {
  54787. var dataFace = null;
  54788. // If special cases.
  54789. if (!mipmapGenerator) {
  54790. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  54791. dataFace = data[j];
  54792. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54793. // 3 channels of 1 bytes per pixel in bytes.
  54794. var byteBuffer = new ArrayBuffer(faceSize);
  54795. byteArray = new Uint8Array(byteBuffer);
  54796. }
  54797. for (var i = 0; i < _this._size * _this._size; i++) {
  54798. // Put in gamma space if requested.
  54799. if (_this._useInGammaSpace) {
  54800. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54801. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54802. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54803. }
  54804. // Convert to int texture for fallback.
  54805. if (byteArray) {
  54806. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54807. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54808. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54809. // May use luminance instead if the result is not accurate.
  54810. var max = Math.max(Math.max(r, g), b);
  54811. if (max > 255) {
  54812. var scale = 255 / max;
  54813. r *= scale;
  54814. g *= scale;
  54815. b *= scale;
  54816. }
  54817. byteArray[(i * 3) + 0] = r;
  54818. byteArray[(i * 3) + 1] = g;
  54819. byteArray[(i * 3) + 2] = b;
  54820. }
  54821. }
  54822. }
  54823. else {
  54824. dataFace = data[k];
  54825. }
  54826. // Fill the array accordingly.
  54827. if (byteArray) {
  54828. results.push(byteArray);
  54829. }
  54830. else {
  54831. results.push(dataFace);
  54832. }
  54833. }
  54834. return results;
  54835. };
  54836. 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, this._onLoad, this._onError);
  54837. };
  54838. /**
  54839. * Occurs when the file is raw .hdr file.
  54840. */
  54841. HDRCubeTexture.prototype.loadHDRTexture = function () {
  54842. var _this = this;
  54843. var callback = function (buffer) {
  54844. // Extract the raw linear data.
  54845. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  54846. // Generate harmonics if needed.
  54847. if (_this._generateHarmonics) {
  54848. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  54849. }
  54850. var results = [];
  54851. var byteArray = null;
  54852. // Push each faces.
  54853. for (var j = 0; j < 6; j++) {
  54854. // Create uintarray fallback.
  54855. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54856. // 3 channels of 1 bytes per pixel in bytes.
  54857. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  54858. byteArray = new Uint8Array(byteBuffer);
  54859. }
  54860. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  54861. // If special cases.
  54862. if (_this._useInGammaSpace || byteArray) {
  54863. for (var i = 0; i < _this._size * _this._size; i++) {
  54864. // Put in gamma space if requested.
  54865. if (_this._useInGammaSpace) {
  54866. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54867. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54868. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54869. }
  54870. // Convert to int texture for fallback.
  54871. if (byteArray) {
  54872. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54873. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54874. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54875. // May use luminance instead if the result is not accurate.
  54876. var max = Math.max(Math.max(r, g), b);
  54877. if (max > 255) {
  54878. var scale = 255 / max;
  54879. r *= scale;
  54880. g *= scale;
  54881. b *= scale;
  54882. }
  54883. byteArray[(i * 3) + 0] = r;
  54884. byteArray[(i * 3) + 1] = g;
  54885. byteArray[(i * 3) + 2] = b;
  54886. }
  54887. }
  54888. }
  54889. if (byteArray) {
  54890. results.push(byteArray);
  54891. }
  54892. else {
  54893. results.push(dataFace);
  54894. }
  54895. }
  54896. return results;
  54897. };
  54898. var mipmapGenerator = null;
  54899. if (!this._noMipmap &&
  54900. this._usePMREMGenerator) {
  54901. mipmapGenerator = function (data) {
  54902. // Custom setup of the generator matching with the PBR shader values.
  54903. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  54904. return generator.filterCubeMap();
  54905. };
  54906. }
  54907. 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, this._onLoad, this._onError);
  54908. };
  54909. /**
  54910. * Starts the loading process of the texture.
  54911. */
  54912. HDRCubeTexture.prototype.loadTexture = function () {
  54913. if (this._isBABYLONPreprocessed) {
  54914. this.loadBabylonTexture();
  54915. }
  54916. else {
  54917. this.loadHDRTexture();
  54918. }
  54919. };
  54920. HDRCubeTexture.prototype.clone = function () {
  54921. var size = this._isBABYLONPreprocessed ? null : this._size;
  54922. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  54923. // Base texture
  54924. newTexture.level = this.level;
  54925. newTexture.wrapU = this.wrapU;
  54926. newTexture.wrapV = this.wrapV;
  54927. newTexture.coordinatesIndex = this.coordinatesIndex;
  54928. newTexture.coordinatesMode = this.coordinatesMode;
  54929. return newTexture;
  54930. };
  54931. // Methods
  54932. HDRCubeTexture.prototype.delayLoad = function () {
  54933. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54934. return;
  54935. }
  54936. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54937. this._texture = this._getFromCache(this.url, this._noMipmap);
  54938. if (!this._texture) {
  54939. this.loadTexture();
  54940. }
  54941. };
  54942. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  54943. return this._textureMatrix;
  54944. };
  54945. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54946. var texture = null;
  54947. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  54948. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  54949. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  54950. texture.name = parsedTexture.name;
  54951. texture.hasAlpha = parsedTexture.hasAlpha;
  54952. texture.level = parsedTexture.level;
  54953. texture.coordinatesMode = parsedTexture.coordinatesMode;
  54954. }
  54955. return texture;
  54956. };
  54957. HDRCubeTexture.prototype.serialize = function () {
  54958. if (!this.name) {
  54959. return null;
  54960. }
  54961. var serializationObject = {};
  54962. serializationObject.name = this.name;
  54963. serializationObject.hasAlpha = this.hasAlpha;
  54964. serializationObject.isCube = true;
  54965. serializationObject.level = this.level;
  54966. serializationObject.size = this._size;
  54967. serializationObject.coordinatesMode = this.coordinatesMode;
  54968. serializationObject.useInGammaSpace = this._useInGammaSpace;
  54969. serializationObject.generateHarmonics = this._generateHarmonics;
  54970. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  54971. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  54972. serializationObject.customType = "BABYLON.HDRCubeTexture";
  54973. serializationObject.noMipmap = this._noMipmap;
  54974. return serializationObject;
  54975. };
  54976. /**
  54977. * Saves as a file the data contained in the texture in a binary format.
  54978. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54979. * as the spherical used in the lighting.
  54980. * @param url The HDR file url.
  54981. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54982. * @param onError Method called if any error happens during download.
  54983. * @return The packed binary data.
  54984. */
  54985. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  54986. if (onError === void 0) { onError = null; }
  54987. var callback = function (buffer) {
  54988. var data = new Blob([buffer], { type: 'application/octet-stream' });
  54989. // Returns a URL you can use as a href.
  54990. var objUrl = window.URL.createObjectURL(data);
  54991. // Simulates a link to it and click to dowload.
  54992. var a = document.createElement("a");
  54993. document.body.appendChild(a);
  54994. a.style.display = "none";
  54995. a.href = objUrl;
  54996. a.download = "envmap.babylon.hdr";
  54997. a.click();
  54998. };
  54999. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  55000. };
  55001. /**
  55002. * Serializes the data contained in the texture in a binary format.
  55003. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55004. * as the spherical used in the lighting.
  55005. * @param url The HDR file url.
  55006. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55007. * @param onError Method called if any error happens during download.
  55008. * @return The packed binary data.
  55009. */
  55010. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  55011. if (onError === void 0) { onError = null; }
  55012. // Needs the url tho create the texture.
  55013. if (!url) {
  55014. return null;
  55015. }
  55016. // Check Power of two size.
  55017. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  55018. return null;
  55019. }
  55020. var getDataCallback = function (dataBuffer) {
  55021. // Extract the raw linear data.
  55022. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55023. // Generate harmonics if needed.
  55024. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55025. // Generate seamless faces
  55026. var mipGeneratorArray = [];
  55027. // Data are known to be in +X +Y +Z -X -Y -Z
  55028. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  55029. mipGeneratorArray.push(cubeData.right); // +X
  55030. mipGeneratorArray.push(cubeData.left); // -X
  55031. mipGeneratorArray.push(cubeData.up); // +Y
  55032. mipGeneratorArray.push(cubeData.down); // -Y
  55033. mipGeneratorArray.push(cubeData.front); // +Z
  55034. mipGeneratorArray.push(cubeData.back); // -Z
  55035. // Custom setup of the generator matching with the PBR shader values.
  55036. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  55037. var mippedData = generator.filterCubeMap();
  55038. // Compute required byte length.
  55039. var byteLength = 1 * 4; // Raw Data Version int32.
  55040. byteLength += 4; // CubeMap max mip face size int32.
  55041. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  55042. // Add data size.
  55043. byteLength += 4; // Number of mip levels int32.
  55044. for (var level = 0; level < mippedData.length; level++) {
  55045. var mipSize = size >> level;
  55046. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  55047. }
  55048. // Prepare binary structure.
  55049. var buffer = new ArrayBuffer(byteLength);
  55050. var intArrayView = new Int32Array(buffer);
  55051. var floatArrayView = new Float32Array(buffer);
  55052. // Fill header.
  55053. intArrayView[0] = 1; // Version 1.
  55054. intArrayView[1] = size; // CubeMap max mip face size.
  55055. // Fill polynomial information.
  55056. sphericalPolynomial.x.toArray(floatArrayView, 2);
  55057. sphericalPolynomial.y.toArray(floatArrayView, 5);
  55058. sphericalPolynomial.z.toArray(floatArrayView, 8);
  55059. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  55060. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  55061. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  55062. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  55063. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  55064. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  55065. // Fill pixel data.
  55066. intArrayView[29] = mippedData.length; // Number of mip levels.
  55067. var startIndex = 30;
  55068. for (var level = 0; level < mippedData.length; level++) {
  55069. // Fill each pixel of the mip level.
  55070. var faceSize = Math.pow(size >> level, 2) * 3;
  55071. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55072. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55073. startIndex += faceSize;
  55074. }
  55075. }
  55076. // Callback.
  55077. callback(buffer);
  55078. };
  55079. // Download and process.
  55080. BABYLON.Tools.LoadFile(url, function (data) {
  55081. getDataCallback(data);
  55082. }, null, null, true, onError);
  55083. };
  55084. return HDRCubeTexture;
  55085. }(BABYLON.BaseTexture));
  55086. HDRCubeTexture._facesMapping = [
  55087. "right",
  55088. "up",
  55089. "front",
  55090. "left",
  55091. "down",
  55092. "back"
  55093. ];
  55094. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55095. })(BABYLON || (BABYLON = {}));
  55096. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55097. var BABYLON;
  55098. (function (BABYLON) {
  55099. var Debug;
  55100. (function (Debug) {
  55101. /**
  55102. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55103. */
  55104. var SkeletonViewer = (function () {
  55105. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  55106. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  55107. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  55108. this.skeleton = skeleton;
  55109. this.mesh = mesh;
  55110. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  55111. this.renderingGroupId = renderingGroupId;
  55112. this.color = BABYLON.Color3.White();
  55113. this._debugLines = [];
  55114. this._isEnabled = false;
  55115. this._scene = scene;
  55116. this.update();
  55117. this._renderFunction = this.update.bind(this);
  55118. }
  55119. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  55120. get: function () {
  55121. return this._isEnabled;
  55122. },
  55123. set: function (value) {
  55124. if (this._isEnabled === value) {
  55125. return;
  55126. }
  55127. this._isEnabled = value;
  55128. if (value) {
  55129. this._scene.registerBeforeRender(this._renderFunction);
  55130. }
  55131. else {
  55132. this._scene.unregisterBeforeRender(this._renderFunction);
  55133. }
  55134. },
  55135. enumerable: true,
  55136. configurable: true
  55137. });
  55138. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  55139. if (x === void 0) { x = 0; }
  55140. if (y === void 0) { y = 0; }
  55141. if (z === void 0) { z = 0; }
  55142. var tmat = BABYLON.Tmp.Matrix[0];
  55143. var parentBone = bone.getParent();
  55144. tmat.copyFrom(bone.getLocalMatrix());
  55145. if (x !== 0 || y !== 0 || z !== 0) {
  55146. var tmat2 = BABYLON.Tmp.Matrix[1];
  55147. BABYLON.Matrix.IdentityToRef(tmat2);
  55148. tmat2.m[12] = x;
  55149. tmat2.m[13] = y;
  55150. tmat2.m[14] = z;
  55151. tmat2.multiplyToRef(tmat, tmat);
  55152. }
  55153. if (parentBone) {
  55154. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  55155. }
  55156. tmat.multiplyToRef(meshMat, tmat);
  55157. position.x = tmat.m[12];
  55158. position.y = tmat.m[13];
  55159. position.z = tmat.m[14];
  55160. };
  55161. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  55162. var len = bones.length;
  55163. for (var i = 0; i < len; i++) {
  55164. var bone = bones[i];
  55165. var points = this._debugLines[i];
  55166. if (!points) {
  55167. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55168. this._debugLines[i] = points;
  55169. }
  55170. this._getBonePosition(points[0], bone, meshMat);
  55171. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  55172. }
  55173. };
  55174. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  55175. var len = bones.length;
  55176. var boneNum = 0;
  55177. for (var i = len - 1; i >= 0; i--) {
  55178. var childBone = bones[i];
  55179. var parentBone = childBone.getParent();
  55180. if (!parentBone) {
  55181. continue;
  55182. }
  55183. var points = this._debugLines[boneNum];
  55184. if (!points) {
  55185. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55186. this._debugLines[boneNum] = points;
  55187. }
  55188. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  55189. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  55190. boneNum++;
  55191. }
  55192. };
  55193. SkeletonViewer.prototype.update = function () {
  55194. if (this.autoUpdateBonesMatrices) {
  55195. this.skeleton.computeAbsoluteTransforms();
  55196. }
  55197. if (this.skeleton.bones[0].length === undefined) {
  55198. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55199. }
  55200. else {
  55201. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55202. }
  55203. if (!this._debugMesh) {
  55204. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  55205. this._debugMesh.renderingGroupId = this.renderingGroupId;
  55206. }
  55207. else {
  55208. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  55209. }
  55210. this._debugMesh.color = this.color;
  55211. };
  55212. SkeletonViewer.prototype.dispose = function () {
  55213. if (this._debugMesh) {
  55214. this.isEnabled = false;
  55215. this._debugMesh.dispose();
  55216. this._debugMesh = null;
  55217. }
  55218. };
  55219. return SkeletonViewer;
  55220. }());
  55221. Debug.SkeletonViewer = SkeletonViewer;
  55222. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55223. })(BABYLON || (BABYLON = {}));
  55224. //# sourceMappingURL=babylon.skeletonViewer.js.map
  55225. var BABYLON;
  55226. (function (BABYLON) {
  55227. var Debug;
  55228. (function (Debug) {
  55229. var AxesViewer = (function () {
  55230. function AxesViewer(scene, scaleLines) {
  55231. if (scaleLines === void 0) { scaleLines = 1; }
  55232. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55233. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55234. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55235. this.scaleLines = 1;
  55236. this.scaleLines = scaleLines;
  55237. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  55238. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  55239. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  55240. this._xmesh.renderingGroupId = 2;
  55241. this._ymesh.renderingGroupId = 2;
  55242. this._zmesh.renderingGroupId = 2;
  55243. this._xmesh.material.checkReadyOnlyOnce = true;
  55244. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  55245. this._ymesh.material.checkReadyOnlyOnce = true;
  55246. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  55247. this._zmesh.material.checkReadyOnlyOnce = true;
  55248. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  55249. this.scene = scene;
  55250. }
  55251. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  55252. var scaleLines = this.scaleLines;
  55253. var point1 = this._xline[0];
  55254. var point2 = this._xline[1];
  55255. point1.x = position.x;
  55256. point1.y = position.y;
  55257. point1.z = position.z;
  55258. point2.x = point1.x + xaxis.x * scaleLines;
  55259. point2.y = point1.y + xaxis.y * scaleLines;
  55260. point2.z = point1.z + xaxis.z * scaleLines;
  55261. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  55262. point1 = this._yline[0];
  55263. point2 = this._yline[1];
  55264. point1.x = position.x;
  55265. point1.y = position.y;
  55266. point1.z = position.z;
  55267. point2.x = point1.x + yaxis.x * scaleLines;
  55268. point2.y = point1.y + yaxis.y * scaleLines;
  55269. point2.z = point1.z + yaxis.z * scaleLines;
  55270. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  55271. point1 = this._zline[0];
  55272. point2 = this._zline[1];
  55273. point1.x = position.x;
  55274. point1.y = position.y;
  55275. point1.z = position.z;
  55276. point2.x = point1.x + zaxis.x * scaleLines;
  55277. point2.y = point1.y + zaxis.y * scaleLines;
  55278. point2.z = point1.z + zaxis.z * scaleLines;
  55279. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  55280. };
  55281. AxesViewer.prototype.dispose = function () {
  55282. if (this._xmesh) {
  55283. this._xmesh.dispose();
  55284. this._ymesh.dispose();
  55285. this._zmesh.dispose();
  55286. this._xmesh = null;
  55287. this._ymesh = null;
  55288. this._zmesh = null;
  55289. this._xline = null;
  55290. this._yline = null;
  55291. this._zline = null;
  55292. this.scene = null;
  55293. }
  55294. };
  55295. return AxesViewer;
  55296. }());
  55297. Debug.AxesViewer = AxesViewer;
  55298. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55299. })(BABYLON || (BABYLON = {}));
  55300. //# sourceMappingURL=babylon.axesViewer.js.map
  55301. var BABYLON;
  55302. (function (BABYLON) {
  55303. var Debug;
  55304. (function (Debug) {
  55305. var BoneAxesViewer = (function (_super) {
  55306. __extends(BoneAxesViewer, _super);
  55307. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  55308. if (scaleLines === void 0) { scaleLines = 1; }
  55309. var _this = _super.call(this, scene, scaleLines) || this;
  55310. _this.pos = BABYLON.Vector3.Zero();
  55311. _this.xaxis = BABYLON.Vector3.Zero();
  55312. _this.yaxis = BABYLON.Vector3.Zero();
  55313. _this.zaxis = BABYLON.Vector3.Zero();
  55314. _this.mesh = mesh;
  55315. _this.bone = bone;
  55316. return _this;
  55317. }
  55318. BoneAxesViewer.prototype.update = function () {
  55319. var bone = this.bone;
  55320. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  55321. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  55322. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  55323. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  55324. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  55325. };
  55326. BoneAxesViewer.prototype.dispose = function () {
  55327. if (this.pos) {
  55328. this.pos = null;
  55329. this.xaxis = null;
  55330. this.yaxis = null;
  55331. this.zaxis = null;
  55332. this.mesh = null;
  55333. this.bone = null;
  55334. _super.prototype.dispose.call(this);
  55335. }
  55336. };
  55337. return BoneAxesViewer;
  55338. }(Debug.AxesViewer));
  55339. Debug.BoneAxesViewer = BoneAxesViewer;
  55340. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55341. })(BABYLON || (BABYLON = {}));
  55342. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  55343. var BABYLON;
  55344. (function (BABYLON) {
  55345. /**
  55346. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  55347. * It can help converting any input color in a desired output one. This can then be used to create effects
  55348. * from sepia, black and white to sixties or futuristic rendering...
  55349. *
  55350. * The only supported format is currently 3dl.
  55351. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  55352. */
  55353. var ColorGradingTexture = (function (_super) {
  55354. __extends(ColorGradingTexture, _super);
  55355. /**
  55356. * Instantiates a ColorGradingTexture from the following parameters.
  55357. *
  55358. * @param url The location of the color gradind data (currently only supporting 3dl)
  55359. * @param scene The scene the texture will be used in
  55360. */
  55361. function ColorGradingTexture(url, scene) {
  55362. var _this = _super.call(this, scene) || this;
  55363. if (!url) {
  55364. return _this;
  55365. }
  55366. _this._textureMatrix = BABYLON.Matrix.Identity();
  55367. _this.name = url;
  55368. _this.url = url;
  55369. _this.hasAlpha = false;
  55370. _this.isCube = false;
  55371. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55372. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55373. _this.anisotropicFilteringLevel = 1;
  55374. _this._texture = _this._getFromCache(url, true);
  55375. if (!_this._texture) {
  55376. if (!scene.useDelayedTextureLoading) {
  55377. _this.loadTexture();
  55378. }
  55379. else {
  55380. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55381. }
  55382. }
  55383. return _this;
  55384. }
  55385. /**
  55386. * Returns the texture matrix used in most of the material.
  55387. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  55388. */
  55389. ColorGradingTexture.prototype.getTextureMatrix = function () {
  55390. return this._textureMatrix;
  55391. };
  55392. /**
  55393. * Occurs when the file being loaded is a .3dl LUT file.
  55394. */
  55395. ColorGradingTexture.prototype.load3dlTexture = function () {
  55396. var _this = this;
  55397. var mipLevels = 0;
  55398. var floatArrayView = null;
  55399. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55400. this._texture = texture;
  55401. var callback = function (text) {
  55402. var data;
  55403. var tempData;
  55404. var line;
  55405. var lines = text.split('\n');
  55406. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  55407. var maxColor = 0;
  55408. for (var i = 0; i < lines.length; i++) {
  55409. line = lines[i];
  55410. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  55411. continue;
  55412. if (line.indexOf('#') === 0)
  55413. continue;
  55414. var words = line.split(" ");
  55415. if (size === 0) {
  55416. // Number of space + one
  55417. size = words.length;
  55418. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  55419. tempData = new Float32Array(size * size * size * 4);
  55420. continue;
  55421. }
  55422. if (size != 0) {
  55423. var r = Math.max(parseInt(words[0]), 0);
  55424. var g = Math.max(parseInt(words[1]), 0);
  55425. var b = Math.max(parseInt(words[2]), 0);
  55426. maxColor = Math.max(r, maxColor);
  55427. maxColor = Math.max(g, maxColor);
  55428. maxColor = Math.max(b, maxColor);
  55429. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  55430. tempData[pixelStorageIndex + 0] = r;
  55431. tempData[pixelStorageIndex + 1] = g;
  55432. tempData[pixelStorageIndex + 2] = b;
  55433. tempData[pixelStorageIndex + 3] = 0;
  55434. pixelIndexSlice++;
  55435. if (pixelIndexSlice % size == 0) {
  55436. pixelIndexH++;
  55437. pixelIndexSlice = 0;
  55438. if (pixelIndexH % size == 0) {
  55439. pixelIndexW++;
  55440. pixelIndexH = 0;
  55441. }
  55442. }
  55443. }
  55444. }
  55445. for (var i = 0; i < tempData.length; i++) {
  55446. var value = tempData[i];
  55447. data[i] = (value / maxColor * 255);
  55448. }
  55449. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  55450. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  55451. };
  55452. BABYLON.Tools.LoadFile(this.url, callback);
  55453. return this._texture;
  55454. };
  55455. /**
  55456. * Starts the loading process of the texture.
  55457. */
  55458. ColorGradingTexture.prototype.loadTexture = function () {
  55459. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  55460. this.load3dlTexture();
  55461. }
  55462. };
  55463. /**
  55464. * Clones the color gradind texture.
  55465. */
  55466. ColorGradingTexture.prototype.clone = function () {
  55467. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  55468. // Base texture
  55469. newTexture.level = this.level;
  55470. return newTexture;
  55471. };
  55472. /**
  55473. * Called during delayed load for textures.
  55474. */
  55475. ColorGradingTexture.prototype.delayLoad = function () {
  55476. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55477. return;
  55478. }
  55479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55480. this._texture = this._getFromCache(this.url, true);
  55481. if (!this._texture) {
  55482. this.loadTexture();
  55483. }
  55484. };
  55485. /**
  55486. * Binds the color grading to the shader.
  55487. * @param colorGrading The texture to bind
  55488. * @param effect The effect to bind to
  55489. */
  55490. ColorGradingTexture.Bind = function (colorGrading, effect) {
  55491. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  55492. var x = colorGrading.level; // Texture Level
  55493. var y = colorGrading.getSize().height; // Texture Size example with 8
  55494. var z = y - 1.0; // SizeMinusOne 8 - 1
  55495. var w = 1 / y; // Space of 1 slice 1 / 8
  55496. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  55497. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  55498. 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
  55499. 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
  55500. 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
  55501. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  55502. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  55503. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  55504. };
  55505. /**
  55506. * Prepare the list of uniforms associated with the ColorGrading effects.
  55507. * @param uniformsList The list of uniforms used in the effect
  55508. * @param samplersList The list of samplers used in the effect
  55509. */
  55510. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  55511. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  55512. samplersList.push("cameraColorGrading2DSampler");
  55513. };
  55514. /**
  55515. * Parses a color grading texture serialized by Babylon.
  55516. * @param parsedTexture The texture information being parsedTexture
  55517. * @param scene The scene to load the texture in
  55518. * @param rootUrl The root url of the data assets to load
  55519. * @return A color gradind texture
  55520. */
  55521. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55522. var texture = null;
  55523. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55524. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  55525. texture.name = parsedTexture.name;
  55526. texture.level = parsedTexture.level;
  55527. }
  55528. return texture;
  55529. };
  55530. /**
  55531. * Serializes the LUT texture to json format.
  55532. */
  55533. ColorGradingTexture.prototype.serialize = function () {
  55534. if (!this.name) {
  55535. return null;
  55536. }
  55537. var serializationObject = {};
  55538. serializationObject.name = this.name;
  55539. serializationObject.level = this.level;
  55540. serializationObject.customType = "BABYLON.ColorGradingTexture";
  55541. return serializationObject;
  55542. };
  55543. return ColorGradingTexture;
  55544. }(BABYLON.BaseTexture));
  55545. /**
  55546. * Empty line regex stored for GC.
  55547. */
  55548. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  55549. BABYLON.ColorGradingTexture = ColorGradingTexture;
  55550. })(BABYLON || (BABYLON = {}));
  55551. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  55552. var BABYLON;
  55553. (function (BABYLON) {
  55554. /**
  55555. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  55556. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  55557. * 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;
  55558. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  55559. */
  55560. var ColorCurves = (function () {
  55561. function ColorCurves() {
  55562. this._dirty = true;
  55563. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  55564. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  55565. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55566. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  55567. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55568. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  55569. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  55570. this._globalHue = 30;
  55571. this._globalDensity = 0;
  55572. this._globalSaturation = 0;
  55573. this._globalExposure = 0;
  55574. this._highlightsHue = 30;
  55575. this._highlightsDensity = 0;
  55576. this._highlightsSaturation = 0;
  55577. this._highlightsExposure = 0;
  55578. this._midtonesHue = 30;
  55579. this._midtonesDensity = 0;
  55580. this._midtonesSaturation = 0;
  55581. this._midtonesExposure = 0;
  55582. this._shadowsHue = 30;
  55583. this._shadowsDensity = 0;
  55584. this._shadowsSaturation = 0;
  55585. this._shadowsExposure = 0;
  55586. }
  55587. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  55588. /**
  55589. * Gets the global Hue value.
  55590. * 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).
  55591. */
  55592. get: function () {
  55593. return this._globalHue;
  55594. },
  55595. /**
  55596. * Sets the global Hue value.
  55597. * 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).
  55598. */
  55599. set: function (value) {
  55600. this._globalHue = value;
  55601. this._dirty = true;
  55602. },
  55603. enumerable: true,
  55604. configurable: true
  55605. });
  55606. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  55607. /**
  55608. * Gets the global Density value.
  55609. * 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.
  55610. * Values less than zero provide a filter of opposite hue.
  55611. */
  55612. get: function () {
  55613. return this._globalDensity;
  55614. },
  55615. /**
  55616. * Sets the global Density value.
  55617. * 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.
  55618. * Values less than zero provide a filter of opposite hue.
  55619. */
  55620. set: function (value) {
  55621. this._globalDensity = value;
  55622. this._dirty = true;
  55623. },
  55624. enumerable: true,
  55625. configurable: true
  55626. });
  55627. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  55628. /**
  55629. * Gets the global Saturation value.
  55630. * 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.
  55631. */
  55632. get: function () {
  55633. return this._globalSaturation;
  55634. },
  55635. /**
  55636. * Sets the global Saturation value.
  55637. * 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.
  55638. */
  55639. set: function (value) {
  55640. this._globalSaturation = value;
  55641. this._dirty = true;
  55642. },
  55643. enumerable: true,
  55644. configurable: true
  55645. });
  55646. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  55647. /**
  55648. * Gets the highlights Hue value.
  55649. * 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).
  55650. */
  55651. get: function () {
  55652. return this._highlightsHue;
  55653. },
  55654. /**
  55655. * Sets the highlights Hue value.
  55656. * 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).
  55657. */
  55658. set: function (value) {
  55659. this._highlightsHue = value;
  55660. this._dirty = true;
  55661. },
  55662. enumerable: true,
  55663. configurable: true
  55664. });
  55665. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  55666. /**
  55667. * Gets the highlights Density value.
  55668. * 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.
  55669. * Values less than zero provide a filter of opposite hue.
  55670. */
  55671. get: function () {
  55672. return this._highlightsDensity;
  55673. },
  55674. /**
  55675. * Sets the highlights Density value.
  55676. * 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.
  55677. * Values less than zero provide a filter of opposite hue.
  55678. */
  55679. set: function (value) {
  55680. this._highlightsDensity = value;
  55681. this._dirty = true;
  55682. },
  55683. enumerable: true,
  55684. configurable: true
  55685. });
  55686. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  55687. /**
  55688. * Gets the highlights Saturation value.
  55689. * 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.
  55690. */
  55691. get: function () {
  55692. return this._highlightsSaturation;
  55693. },
  55694. /**
  55695. * Sets the highlights Saturation value.
  55696. * 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.
  55697. */
  55698. set: function (value) {
  55699. this._highlightsSaturation = value;
  55700. this._dirty = true;
  55701. },
  55702. enumerable: true,
  55703. configurable: true
  55704. });
  55705. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  55706. /**
  55707. * Gets the highlights Exposure value.
  55708. * 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.
  55709. */
  55710. get: function () {
  55711. return this._highlightsExposure;
  55712. },
  55713. /**
  55714. * Sets the highlights Exposure value.
  55715. * 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.
  55716. */
  55717. set: function (value) {
  55718. this._highlightsExposure = value;
  55719. this._dirty = true;
  55720. },
  55721. enumerable: true,
  55722. configurable: true
  55723. });
  55724. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  55725. /**
  55726. * Gets the midtones Hue value.
  55727. * 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).
  55728. */
  55729. get: function () {
  55730. return this._midtonesHue;
  55731. },
  55732. /**
  55733. * Sets the midtones Hue value.
  55734. * 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).
  55735. */
  55736. set: function (value) {
  55737. this._midtonesHue = value;
  55738. this._dirty = true;
  55739. },
  55740. enumerable: true,
  55741. configurable: true
  55742. });
  55743. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  55744. /**
  55745. * Gets the midtones Density value.
  55746. * 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.
  55747. * Values less than zero provide a filter of opposite hue.
  55748. */
  55749. get: function () {
  55750. return this._midtonesDensity;
  55751. },
  55752. /**
  55753. * Sets the midtones Density value.
  55754. * 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.
  55755. * Values less than zero provide a filter of opposite hue.
  55756. */
  55757. set: function (value) {
  55758. this._midtonesDensity = value;
  55759. this._dirty = true;
  55760. },
  55761. enumerable: true,
  55762. configurable: true
  55763. });
  55764. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  55765. /**
  55766. * Gets the midtones Saturation value.
  55767. * 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.
  55768. */
  55769. get: function () {
  55770. return this._midtonesSaturation;
  55771. },
  55772. /**
  55773. * Sets the midtones Saturation value.
  55774. * 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.
  55775. */
  55776. set: function (value) {
  55777. this._midtonesSaturation = value;
  55778. this._dirty = true;
  55779. },
  55780. enumerable: true,
  55781. configurable: true
  55782. });
  55783. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  55784. /**
  55785. * Gets the midtones Exposure value.
  55786. * 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.
  55787. */
  55788. get: function () {
  55789. return this._midtonesExposure;
  55790. },
  55791. /**
  55792. * Sets the midtones Exposure value.
  55793. * 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.
  55794. */
  55795. set: function (value) {
  55796. this._midtonesExposure = value;
  55797. this._dirty = true;
  55798. },
  55799. enumerable: true,
  55800. configurable: true
  55801. });
  55802. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  55803. /**
  55804. * Gets the shadows Hue value.
  55805. * 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).
  55806. */
  55807. get: function () {
  55808. return this._shadowsHue;
  55809. },
  55810. /**
  55811. * Sets the shadows Hue value.
  55812. * 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).
  55813. */
  55814. set: function (value) {
  55815. this._shadowsHue = value;
  55816. this._dirty = true;
  55817. },
  55818. enumerable: true,
  55819. configurable: true
  55820. });
  55821. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  55822. /**
  55823. * Gets the shadows Density value.
  55824. * 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.
  55825. * Values less than zero provide a filter of opposite hue.
  55826. */
  55827. get: function () {
  55828. return this._shadowsDensity;
  55829. },
  55830. /**
  55831. * Sets the shadows Density value.
  55832. * 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.
  55833. * Values less than zero provide a filter of opposite hue.
  55834. */
  55835. set: function (value) {
  55836. this._shadowsDensity = value;
  55837. this._dirty = true;
  55838. },
  55839. enumerable: true,
  55840. configurable: true
  55841. });
  55842. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  55843. /**
  55844. * Gets the shadows Saturation value.
  55845. * 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.
  55846. */
  55847. get: function () {
  55848. return this._shadowsSaturation;
  55849. },
  55850. /**
  55851. * Sets the shadows Saturation value.
  55852. * 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.
  55853. */
  55854. set: function (value) {
  55855. this._shadowsSaturation = value;
  55856. this._dirty = true;
  55857. },
  55858. enumerable: true,
  55859. configurable: true
  55860. });
  55861. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  55862. /**
  55863. * Gets the shadows Exposure value.
  55864. * 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.
  55865. */
  55866. get: function () {
  55867. return this._shadowsExposure;
  55868. },
  55869. /**
  55870. * Sets the shadows Exposure value.
  55871. * 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.
  55872. */
  55873. set: function (value) {
  55874. this._shadowsExposure = value;
  55875. this._dirty = true;
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. /**
  55881. * Binds the color curves to the shader.
  55882. * @param colorCurves The color curve to bind
  55883. * @param effect The effect to bind to
  55884. */
  55885. ColorCurves.Bind = function (colorCurves, effect) {
  55886. if (colorCurves._dirty) {
  55887. colorCurves._dirty = false;
  55888. // Fill in global info.
  55889. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  55890. // Compute highlights info.
  55891. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  55892. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  55893. // Compute midtones info.
  55894. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  55895. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  55896. // Compute shadows info.
  55897. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  55898. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  55899. // Compute deltas (neutral is midtones).
  55900. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  55901. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  55902. }
  55903. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  55904. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  55905. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  55906. };
  55907. /**
  55908. * Prepare the list of uniforms associated with the ColorCurves effects.
  55909. * @param uniformsList The list of uniforms used in the effect
  55910. */
  55911. ColorCurves.PrepareUniforms = function (uniformsList) {
  55912. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  55913. };
  55914. /**
  55915. * Returns color grading data based on a hue, density, saturation and exposure value.
  55916. * @param filterHue The hue of the color filter.
  55917. * @param filterDensity The density of the color filter.
  55918. * @param saturation The saturation.
  55919. * @param exposure The exposure.
  55920. * @param result The result data container.
  55921. */
  55922. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  55923. if (hue == null) {
  55924. return;
  55925. }
  55926. hue = ColorCurves.clamp(hue, 0, 360);
  55927. density = ColorCurves.clamp(density, -100, 100);
  55928. saturation = ColorCurves.clamp(saturation, -100, 100);
  55929. exposure = ColorCurves.clamp(exposure, -100, 100);
  55930. // Remap the slider/config filter density with non-linear mapping and also scale by half
  55931. // so that the maximum filter density is only 50% control. This provides fine control
  55932. // for small values and reasonable range.
  55933. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  55934. density *= 0.5;
  55935. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  55936. if (density < 0) {
  55937. density *= -1;
  55938. hue = (hue + 180) % 360;
  55939. }
  55940. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  55941. result.scaleToRef(2, result);
  55942. result.a = 1 + 0.01 * saturation;
  55943. };
  55944. /**
  55945. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  55946. * @param value The input slider value in range [-100,100].
  55947. * @returns Adjusted value.
  55948. */
  55949. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  55950. value /= 100;
  55951. var x = Math.abs(value);
  55952. x = Math.pow(x, 2);
  55953. if (value < 0) {
  55954. x *= -1;
  55955. }
  55956. x *= 100;
  55957. return x;
  55958. };
  55959. /**
  55960. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  55961. * @param hue The hue (H) input.
  55962. * @param saturation The saturation (S) input.
  55963. * @param brightness The brightness (B) input.
  55964. * @result An RGBA color represented as Vector4.
  55965. */
  55966. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  55967. var h = ColorCurves.clamp(hue, 0, 360);
  55968. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  55969. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  55970. if (s === 0) {
  55971. result.r = v;
  55972. result.g = v;
  55973. result.b = v;
  55974. }
  55975. else {
  55976. // sector 0 to 5
  55977. h /= 60;
  55978. var i = Math.floor(h);
  55979. // fractional part of h
  55980. var f = h - i;
  55981. var p = v * (1 - s);
  55982. var q = v * (1 - s * f);
  55983. var t = v * (1 - s * (1 - f));
  55984. switch (i) {
  55985. case 0:
  55986. result.r = v;
  55987. result.g = t;
  55988. result.b = p;
  55989. break;
  55990. case 1:
  55991. result.r = q;
  55992. result.g = v;
  55993. result.b = p;
  55994. break;
  55995. case 2:
  55996. result.r = p;
  55997. result.g = v;
  55998. result.b = t;
  55999. break;
  56000. case 3:
  56001. result.r = p;
  56002. result.g = q;
  56003. result.b = v;
  56004. break;
  56005. case 4:
  56006. result.r = t;
  56007. result.g = p;
  56008. result.b = v;
  56009. break;
  56010. default:
  56011. result.r = v;
  56012. result.g = p;
  56013. result.b = q;
  56014. break;
  56015. }
  56016. }
  56017. result.a = 1;
  56018. };
  56019. /**
  56020. * Returns a value clamped between min and max
  56021. * @param value The value to clamp
  56022. * @param min The minimum of value
  56023. * @param max The maximum of value
  56024. * @returns The clamped value.
  56025. */
  56026. ColorCurves.clamp = function (value, min, max) {
  56027. return Math.min(Math.max(value, min), max);
  56028. };
  56029. /**
  56030. * Clones the current color curve instance.
  56031. * @return The cloned curves
  56032. */
  56033. ColorCurves.prototype.clone = function () {
  56034. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  56035. };
  56036. /**
  56037. * Serializes the current color curve instance to a json representation.
  56038. * @return a JSON representation
  56039. */
  56040. ColorCurves.prototype.serialize = function () {
  56041. return BABYLON.SerializationHelper.Serialize(this);
  56042. };
  56043. /**
  56044. * Parses the color curve from a json representation.
  56045. * @param source the JSON source to parse
  56046. * @return The parsed curves
  56047. */
  56048. ColorCurves.Parse = function (source) {
  56049. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  56050. };
  56051. return ColorCurves;
  56052. }());
  56053. __decorate([
  56054. BABYLON.serialize()
  56055. ], ColorCurves.prototype, "_globalHue", void 0);
  56056. __decorate([
  56057. BABYLON.serialize()
  56058. ], ColorCurves.prototype, "_globalDensity", void 0);
  56059. __decorate([
  56060. BABYLON.serialize()
  56061. ], ColorCurves.prototype, "_globalSaturation", void 0);
  56062. __decorate([
  56063. BABYLON.serialize()
  56064. ], ColorCurves.prototype, "_globalExposure", void 0);
  56065. __decorate([
  56066. BABYLON.serialize()
  56067. ], ColorCurves.prototype, "_highlightsHue", void 0);
  56068. __decorate([
  56069. BABYLON.serialize()
  56070. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  56071. __decorate([
  56072. BABYLON.serialize()
  56073. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56074. __decorate([
  56075. BABYLON.serialize()
  56076. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56077. __decorate([
  56078. BABYLON.serialize()
  56079. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56080. __decorate([
  56081. BABYLON.serialize()
  56082. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56083. __decorate([
  56084. BABYLON.serialize()
  56085. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56086. __decorate([
  56087. BABYLON.serialize()
  56088. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56089. BABYLON.ColorCurves = ColorCurves;
  56090. })(BABYLON || (BABYLON = {}));
  56091. //# sourceMappingURL=babylon.colorCurves.js.map
  56092. var BABYLON;
  56093. (function (BABYLON) {
  56094. var PBRMaterialDefines = (function (_super) {
  56095. __extends(PBRMaterialDefines, _super);
  56096. function PBRMaterialDefines() {
  56097. var _this = _super.call(this) || this;
  56098. _this.ALBEDO = false;
  56099. _this.AMBIENT = false;
  56100. _this.OPACITY = false;
  56101. _this.OPACITYRGB = false;
  56102. _this.REFLECTION = false;
  56103. _this.EMISSIVE = false;
  56104. _this.REFLECTIVITY = false;
  56105. _this.BUMP = false;
  56106. _this.PARALLAX = false;
  56107. _this.PARALLAXOCCLUSION = false;
  56108. _this.SPECULAROVERALPHA = false;
  56109. _this.CLIPPLANE = false;
  56110. _this.ALPHATEST = false;
  56111. _this.ALPHAFROMALBEDO = false;
  56112. _this.POINTSIZE = false;
  56113. _this.FOG = false;
  56114. _this.SPECULARTERM = false;
  56115. _this.OPACITYFRESNEL = false;
  56116. _this.EMISSIVEFRESNEL = false;
  56117. _this.FRESNEL = false;
  56118. _this.NORMAL = false;
  56119. _this.UV1 = false;
  56120. _this.UV2 = false;
  56121. _this.VERTEXCOLOR = false;
  56122. _this.VERTEXALPHA = false;
  56123. _this.NUM_BONE_INFLUENCERS = 0;
  56124. _this.BonesPerMesh = 0;
  56125. _this.INSTANCES = false;
  56126. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  56127. _this.MICROSURFACEAUTOMATIC = false;
  56128. _this.EMISSIVEASILLUMINATION = false;
  56129. _this.LINKEMISSIVEWITHALBEDO = false;
  56130. _this.LIGHTMAP = false;
  56131. _this.USELIGHTMAPASSHADOWMAP = false;
  56132. _this.REFLECTIONMAP_3D = false;
  56133. _this.REFLECTIONMAP_SPHERICAL = false;
  56134. _this.REFLECTIONMAP_PLANAR = false;
  56135. _this.REFLECTIONMAP_CUBIC = false;
  56136. _this.REFLECTIONMAP_PROJECTION = false;
  56137. _this.REFLECTIONMAP_SKYBOX = false;
  56138. _this.REFLECTIONMAP_EXPLICIT = false;
  56139. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  56140. _this.INVERTCUBICMAP = false;
  56141. _this.LOGARITHMICDEPTH = false;
  56142. _this.CAMERATONEMAP = false;
  56143. _this.CAMERACONTRAST = false;
  56144. _this.CAMERACOLORGRADING = false;
  56145. _this.CAMERACOLORCURVES = false;
  56146. _this.OVERLOADEDVALUES = false;
  56147. _this.OVERLOADEDSHADOWVALUES = false;
  56148. _this.USESPHERICALFROMREFLECTIONMAP = false;
  56149. _this.REFRACTION = false;
  56150. _this.REFRACTIONMAP_3D = false;
  56151. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  56152. _this.REFRACTIONMAPINLINEARSPACE = false;
  56153. _this.LODBASEDMICROSFURACE = false;
  56154. _this.USEPHYSICALLIGHTFALLOFF = false;
  56155. _this.RADIANCEOVERALPHA = false;
  56156. _this.USEPMREMREFLECTION = false;
  56157. _this.USEPMREMREFRACTION = false;
  56158. _this.OPENGLNORMALMAP = false;
  56159. _this.INVERTNORMALMAPX = false;
  56160. _this.INVERTNORMALMAPY = false;
  56161. _this.SHADOWFULLFLOAT = false;
  56162. _this.METALLICWORKFLOW = false;
  56163. _this.METALLICROUGHNESSMAP = false;
  56164. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  56165. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  56166. _this.rebuild();
  56167. return _this;
  56168. }
  56169. return PBRMaterialDefines;
  56170. }(BABYLON.MaterialDefines));
  56171. /**
  56172. * The Physically based material of BJS.
  56173. *
  56174. * This offers the main features of a standard PBR material.
  56175. * For more information, please refer to the documentation :
  56176. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  56177. */
  56178. var PBRMaterial = (function (_super) {
  56179. __extends(PBRMaterial, _super);
  56180. /**
  56181. * Instantiates a new PBRMaterial instance.
  56182. *
  56183. * @param name The material name
  56184. * @param scene The scene the material will be use in.
  56185. */
  56186. function PBRMaterial(name, scene) {
  56187. var _this = _super.call(this, name, scene) || this;
  56188. /**
  56189. * Intensity of the direct lights e.g. the four lights available in your scene.
  56190. * This impacts both the direct diffuse and specular highlights.
  56191. */
  56192. _this.directIntensity = 1.0;
  56193. /**
  56194. * Intensity of the emissive part of the material.
  56195. * This helps controlling the emissive effect without modifying the emissive color.
  56196. */
  56197. _this.emissiveIntensity = 1.0;
  56198. /**
  56199. * Intensity of the environment e.g. how much the environment will light the object
  56200. * either through harmonics for rough material or through the refelction for shiny ones.
  56201. */
  56202. _this.environmentIntensity = 1.0;
  56203. /**
  56204. * This is a special control allowing the reduction of the specular highlights coming from the
  56205. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  56206. */
  56207. _this.specularIntensity = 1.0;
  56208. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  56209. /**
  56210. * Debug Control allowing disabling the bump map on this material.
  56211. */
  56212. _this.disableBumpMap = false;
  56213. /**
  56214. * Debug Control helping enforcing or dropping the darkness of shadows.
  56215. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  56216. */
  56217. _this.overloadedShadowIntensity = 1.0;
  56218. /**
  56219. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  56220. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  56221. */
  56222. _this.overloadedShadeIntensity = 1.0;
  56223. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  56224. /**
  56225. * The camera exposure used on this material.
  56226. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  56227. * This corresponds to a photographic exposure.
  56228. */
  56229. _this.cameraExposure = 1.0;
  56230. /**
  56231. * The camera contrast used on this material.
  56232. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  56233. */
  56234. _this.cameraContrast = 1.0;
  56235. /**
  56236. * Color Grading 2D Lookup Texture.
  56237. * This allows special effects like sepia, black and white to sixties rendering style.
  56238. */
  56239. _this.cameraColorGradingTexture = null;
  56240. /**
  56241. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56242. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56243. * 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;
  56244. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56245. */
  56246. _this.cameraColorCurves = null;
  56247. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  56248. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  56249. /**
  56250. * Debug Control allowing to overload the ambient color.
  56251. * This as to be use with the overloadedAmbientIntensity parameter.
  56252. */
  56253. _this.overloadedAmbient = BABYLON.Color3.White();
  56254. /**
  56255. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  56256. */
  56257. _this.overloadedAmbientIntensity = 0.0;
  56258. /**
  56259. * Debug Control allowing to overload the albedo color.
  56260. * This as to be use with the overloadedAlbedoIntensity parameter.
  56261. */
  56262. _this.overloadedAlbedo = BABYLON.Color3.White();
  56263. /**
  56264. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  56265. */
  56266. _this.overloadedAlbedoIntensity = 0.0;
  56267. /**
  56268. * Debug Control allowing to overload the reflectivity color.
  56269. * This as to be use with the overloadedReflectivityIntensity parameter.
  56270. */
  56271. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  56272. /**
  56273. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  56274. */
  56275. _this.overloadedReflectivityIntensity = 0.0;
  56276. /**
  56277. * Debug Control allowing to overload the emissive color.
  56278. * This as to be use with the overloadedEmissiveIntensity parameter.
  56279. */
  56280. _this.overloadedEmissive = BABYLON.Color3.White();
  56281. /**
  56282. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  56283. */
  56284. _this.overloadedEmissiveIntensity = 0.0;
  56285. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  56286. /**
  56287. * Debug Control allowing to overload the reflection color.
  56288. * This as to be use with the overloadedReflectionIntensity parameter.
  56289. */
  56290. _this.overloadedReflection = BABYLON.Color3.White();
  56291. /**
  56292. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  56293. */
  56294. _this.overloadedReflectionIntensity = 0.0;
  56295. /**
  56296. * Debug Control allowing to overload the microsurface.
  56297. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  56298. */
  56299. _this.overloadedMicroSurface = 0.0;
  56300. /**
  56301. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  56302. */
  56303. _this.overloadedMicroSurfaceIntensity = 0.0;
  56304. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  56305. /**
  56306. * AKA Occlusion Texture Intensity in other nomenclature.
  56307. */
  56308. _this.ambientTextureStrength = 1.0;
  56309. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  56310. /**
  56311. * AKA Diffuse Color in other nomenclature.
  56312. */
  56313. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  56314. /**
  56315. * AKA Specular Color in other nomenclature.
  56316. */
  56317. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  56318. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  56319. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  56320. /**
  56321. * AKA Glossiness in other nomenclature.
  56322. */
  56323. _this.microSurface = 0.9;
  56324. /**
  56325. * source material index of refraction (IOR)' / 'destination material IOR.
  56326. */
  56327. _this.indexOfRefraction = 0.66;
  56328. /**
  56329. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  56330. */
  56331. _this.invertRefractionY = false;
  56332. /**
  56333. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  56334. * Materials half opaque for instance using refraction could benefit from this control.
  56335. */
  56336. _this.linkRefractionWithTransparency = false;
  56337. /**
  56338. * The emissive and albedo are linked to never be more than one (Energy conservation).
  56339. */
  56340. _this.linkEmissiveWithAlbedo = false;
  56341. _this.useLightmapAsShadowmap = false;
  56342. /**
  56343. * In this mode, the emissive informtaion will always be added to the lighting once.
  56344. * A light for instance can be thought as emissive.
  56345. */
  56346. _this.useEmissiveAsIllumination = false;
  56347. /**
  56348. * Secifies that the alpha is coming form the albedo channel alpha channel.
  56349. */
  56350. _this.useAlphaFromAlbedoTexture = false;
  56351. /**
  56352. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  56353. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  56354. */
  56355. _this.useSpecularOverAlpha = true;
  56356. /**
  56357. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  56358. */
  56359. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  56360. /**
  56361. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  56362. */
  56363. _this.useRoughnessFromMetallicTextureAlpha = true;
  56364. /**
  56365. * Specifies if the metallic texture contains the roughness information in its green channel.
  56366. */
  56367. _this.useRoughnessFromMetallicTextureGreen = false;
  56368. /**
  56369. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  56370. * The material will try to infer what glossiness each pixel should be.
  56371. */
  56372. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  56373. /**
  56374. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  56375. * the creation of the material.
  56376. */
  56377. _this.useScalarInLinearSpace = false;
  56378. /**
  56379. * BJS is using an harcoded light falloff based on a manually sets up range.
  56380. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  56381. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  56382. */
  56383. _this.usePhysicalLightFalloff = true;
  56384. /**
  56385. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  56386. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  56387. */
  56388. _this.useRadianceOverAlpha = true;
  56389. /**
  56390. * Allows using the bump map in parallax mode.
  56391. */
  56392. _this.useParallax = false;
  56393. /**
  56394. * Allows using the bump map in parallax occlusion mode.
  56395. */
  56396. _this.useParallaxOcclusion = false;
  56397. /**
  56398. * Controls the scale bias of the parallax mode.
  56399. */
  56400. _this.parallaxScaleBias = 0.05;
  56401. /**
  56402. * If sets to true, disables all the lights affecting the material.
  56403. */
  56404. _this.disableLighting = false;
  56405. /**
  56406. * Number of Simultaneous lights allowed on the material.
  56407. */
  56408. _this.maxSimultaneousLights = 4;
  56409. /**
  56410. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  56411. */
  56412. _this.invertNormalMapX = false;
  56413. /**
  56414. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  56415. */
  56416. _this.invertNormalMapY = false;
  56417. _this._renderTargets = new BABYLON.SmartArray(16);
  56418. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  56419. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  56420. _this._tempColor = new BABYLON.Color3();
  56421. _this._defines = new PBRMaterialDefines();
  56422. _this._cachedDefines = new PBRMaterialDefines();
  56423. _this._myScene = null;
  56424. _this._myShadowGenerator = null;
  56425. _this._cachedDefines.BonesPerMesh = -1;
  56426. _this.getRenderTargetTextures = function () {
  56427. _this._renderTargets.reset();
  56428. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  56429. _this._renderTargets.push(_this.reflectionTexture);
  56430. }
  56431. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  56432. _this._renderTargets.push(_this.refractionTexture);
  56433. }
  56434. return _this._renderTargets;
  56435. };
  56436. return _this;
  56437. }
  56438. PBRMaterial.prototype.getClassName = function () {
  56439. return "PBRMaterial";
  56440. };
  56441. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  56442. get: function () {
  56443. return this._useLogarithmicDepth;
  56444. },
  56445. set: function (value) {
  56446. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  56447. },
  56448. enumerable: true,
  56449. configurable: true
  56450. });
  56451. PBRMaterial.prototype.needAlphaBlending = function () {
  56452. if (this.linkRefractionWithTransparency) {
  56453. return false;
  56454. }
  56455. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  56456. };
  56457. PBRMaterial.prototype.needAlphaTesting = function () {
  56458. if (this.linkRefractionWithTransparency) {
  56459. return false;
  56460. }
  56461. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  56462. };
  56463. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  56464. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  56465. };
  56466. PBRMaterial.prototype.getAlphaTestTexture = function () {
  56467. return this.albedoTexture;
  56468. };
  56469. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56470. if (!mesh) {
  56471. return true;
  56472. }
  56473. if (this._defines.INSTANCES !== useInstances) {
  56474. return false;
  56475. }
  56476. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  56477. return true;
  56478. }
  56479. return false;
  56480. };
  56481. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  56482. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  56483. };
  56484. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  56485. if (!useScalarInLinear) {
  56486. color.toLinearSpaceToRef(ref);
  56487. }
  56488. else {
  56489. ref.r = color.r;
  56490. ref.g = color.g;
  56491. ref.b = color.b;
  56492. }
  56493. };
  56494. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  56495. var lightIndex = 0;
  56496. var depthValuesAlreadySet = false;
  56497. for (var index = 0; index < scene.lights.length; index++) {
  56498. var light = scene.lights[index];
  56499. if (!light.isEnabled()) {
  56500. continue;
  56501. }
  56502. if (!light.canAffectMesh(mesh)) {
  56503. continue;
  56504. }
  56505. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  56506. // GAMMA CORRECTION.
  56507. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  56508. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  56509. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  56510. if (defines["SPECULARTERM"]) {
  56511. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  56512. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  56513. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  56514. }
  56515. // Shadows
  56516. if (scene.shadowsEnabled) {
  56517. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  56518. }
  56519. lightIndex++;
  56520. if (lightIndex === maxSimultaneousLights)
  56521. break;
  56522. }
  56523. };
  56524. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  56525. if (this.isFrozen) {
  56526. if (this._wasPreviouslyReady) {
  56527. return true;
  56528. }
  56529. }
  56530. var scene = this.getScene();
  56531. var engine = scene.getEngine();
  56532. var needNormals = false;
  56533. var needUVs = false;
  56534. this._defines.reset();
  56535. if (scene.lightsEnabled && !this.disableLighting) {
  56536. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  56537. }
  56538. if (!this.checkReadyOnEveryCall) {
  56539. if (this._renderId === scene.getRenderId()) {
  56540. if (this._checkCache(scene, mesh, useInstances)) {
  56541. return true;
  56542. }
  56543. }
  56544. }
  56545. if (scene.texturesEnabled) {
  56546. if (scene.getEngine().getCaps().textureLOD) {
  56547. this._defines.LODBASEDMICROSFURACE = true;
  56548. }
  56549. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56550. if (!this.albedoTexture.isReady()) {
  56551. return false;
  56552. }
  56553. else {
  56554. needUVs = true;
  56555. this._defines.ALBEDO = true;
  56556. }
  56557. }
  56558. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  56559. if (!this.ambientTexture.isReady()) {
  56560. return false;
  56561. }
  56562. else {
  56563. needUVs = true;
  56564. this._defines.AMBIENT = true;
  56565. }
  56566. }
  56567. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  56568. if (!this.opacityTexture.isReady()) {
  56569. return false;
  56570. }
  56571. else {
  56572. needUVs = true;
  56573. this._defines.OPACITY = true;
  56574. if (this.opacityTexture.getAlphaFromRGB) {
  56575. this._defines.OPACITYRGB = true;
  56576. }
  56577. }
  56578. }
  56579. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  56580. if (!this.reflectionTexture.isReady()) {
  56581. return false;
  56582. }
  56583. else {
  56584. needNormals = true;
  56585. this._defines.REFLECTION = true;
  56586. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  56587. this._defines.INVERTCUBICMAP = true;
  56588. }
  56589. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  56590. switch (this.reflectionTexture.coordinatesMode) {
  56591. case BABYLON.Texture.CUBIC_MODE:
  56592. case BABYLON.Texture.INVCUBIC_MODE:
  56593. this._defines.REFLECTIONMAP_CUBIC = true;
  56594. break;
  56595. case BABYLON.Texture.EXPLICIT_MODE:
  56596. this._defines.REFLECTIONMAP_EXPLICIT = true;
  56597. break;
  56598. case BABYLON.Texture.PLANAR_MODE:
  56599. this._defines.REFLECTIONMAP_PLANAR = true;
  56600. break;
  56601. case BABYLON.Texture.PROJECTION_MODE:
  56602. this._defines.REFLECTIONMAP_PROJECTION = true;
  56603. break;
  56604. case BABYLON.Texture.SKYBOX_MODE:
  56605. this._defines.REFLECTIONMAP_SKYBOX = true;
  56606. break;
  56607. case BABYLON.Texture.SPHERICAL_MODE:
  56608. this._defines.REFLECTIONMAP_SPHERICAL = true;
  56609. break;
  56610. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  56611. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  56612. break;
  56613. }
  56614. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  56615. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  56616. needNormals = true;
  56617. if (this.reflectionTexture.isPMREM) {
  56618. this._defines.USEPMREMREFLECTION = true;
  56619. }
  56620. }
  56621. }
  56622. }
  56623. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  56624. if (!this.lightmapTexture.isReady()) {
  56625. return false;
  56626. }
  56627. else {
  56628. needUVs = true;
  56629. this._defines.LIGHTMAP = true;
  56630. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  56631. }
  56632. }
  56633. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  56634. if (!this.emissiveTexture.isReady()) {
  56635. return false;
  56636. }
  56637. else {
  56638. needUVs = true;
  56639. this._defines.EMISSIVE = true;
  56640. }
  56641. }
  56642. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  56643. if (this.metallicTexture) {
  56644. if (!this.metallicTexture.isReady()) {
  56645. return false;
  56646. }
  56647. else {
  56648. needUVs = true;
  56649. this._defines.METALLICWORKFLOW = true;
  56650. this._defines.METALLICROUGHNESSMAP = true;
  56651. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  56652. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  56653. }
  56654. }
  56655. else if (this.reflectivityTexture) {
  56656. if (!this.reflectivityTexture.isReady()) {
  56657. return false;
  56658. }
  56659. else {
  56660. needUVs = true;
  56661. this._defines.REFLECTIVITY = true;
  56662. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  56663. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  56664. }
  56665. }
  56666. }
  56667. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  56668. if (!this.bumpTexture.isReady()) {
  56669. return false;
  56670. }
  56671. else {
  56672. needUVs = true;
  56673. this._defines.BUMP = true;
  56674. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56675. this._defines.PARALLAX = true;
  56676. if (this.useParallaxOcclusion) {
  56677. this._defines.PARALLAXOCCLUSION = true;
  56678. }
  56679. }
  56680. if (this.invertNormalMapX) {
  56681. this._defines.INVERTNORMALMAPX = true;
  56682. }
  56683. if (this.invertNormalMapY) {
  56684. this._defines.INVERTNORMALMAPY = true;
  56685. }
  56686. if (scene._mirroredCameraPosition) {
  56687. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  56688. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  56689. }
  56690. }
  56691. }
  56692. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  56693. if (!this.refractionTexture.isReady()) {
  56694. return false;
  56695. }
  56696. else {
  56697. needUVs = true;
  56698. this._defines.REFRACTION = true;
  56699. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  56700. if (this.linkRefractionWithTransparency) {
  56701. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  56702. }
  56703. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  56704. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  56705. if (this.refractionTexture.isPMREM) {
  56706. this._defines.USEPMREMREFRACTION = true;
  56707. }
  56708. }
  56709. }
  56710. }
  56711. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  56712. if (!this.cameraColorGradingTexture.isReady()) {
  56713. return false;
  56714. }
  56715. else {
  56716. this._defines.CAMERACOLORGRADING = true;
  56717. }
  56718. }
  56719. }
  56720. // Effect
  56721. if (scene.clipPlane) {
  56722. this._defines.CLIPPLANE = true;
  56723. }
  56724. if (engine.getAlphaTesting()) {
  56725. this._defines.ALPHATEST = true;
  56726. }
  56727. if (this._shouldUseAlphaFromAlbedoTexture()) {
  56728. this._defines.ALPHAFROMALBEDO = true;
  56729. }
  56730. if (this.useEmissiveAsIllumination) {
  56731. this._defines.EMISSIVEASILLUMINATION = true;
  56732. }
  56733. if (this.linkEmissiveWithAlbedo) {
  56734. this._defines.LINKEMISSIVEWITHALBEDO = true;
  56735. }
  56736. if (this.useLogarithmicDepth) {
  56737. this._defines.LOGARITHMICDEPTH = true;
  56738. }
  56739. if (this.cameraContrast != 1) {
  56740. this._defines.CAMERACONTRAST = true;
  56741. }
  56742. if (this.cameraExposure != 1) {
  56743. this._defines.CAMERATONEMAP = true;
  56744. }
  56745. if (this.cameraColorCurves) {
  56746. this._defines.CAMERACOLORCURVES = true;
  56747. }
  56748. if (this.overloadedShadeIntensity != 1 ||
  56749. this.overloadedShadowIntensity != 1) {
  56750. this._defines.OVERLOADEDSHADOWVALUES = true;
  56751. }
  56752. if (this.overloadedMicroSurfaceIntensity > 0 ||
  56753. this.overloadedEmissiveIntensity > 0 ||
  56754. this.overloadedReflectivityIntensity > 0 ||
  56755. this.overloadedAlbedoIntensity > 0 ||
  56756. this.overloadedAmbientIntensity > 0 ||
  56757. this.overloadedReflectionIntensity > 0) {
  56758. this._defines.OVERLOADEDVALUES = true;
  56759. }
  56760. // Point size
  56761. if (this.pointsCloud || scene.forcePointsCloud) {
  56762. this._defines.POINTSIZE = true;
  56763. }
  56764. // Fog
  56765. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56766. this._defines.FOG = true;
  56767. }
  56768. if (BABYLON.StandardMaterial.FresnelEnabled) {
  56769. // Fresnel
  56770. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  56771. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56772. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  56773. this._defines.OPACITYFRESNEL = true;
  56774. }
  56775. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56776. this._defines.EMISSIVEFRESNEL = true;
  56777. }
  56778. needNormals = true;
  56779. this._defines.FRESNEL = true;
  56780. }
  56781. }
  56782. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  56783. this._defines.SPECULAROVERALPHA = true;
  56784. }
  56785. if (this.usePhysicalLightFalloff) {
  56786. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  56787. }
  56788. if (this.useRadianceOverAlpha) {
  56789. this._defines.RADIANCEOVERALPHA = true;
  56790. }
  56791. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  56792. this._defines.METALLICWORKFLOW = true;
  56793. }
  56794. // Attribs
  56795. if (mesh) {
  56796. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56797. this._defines.NORMAL = true;
  56798. }
  56799. if (needUVs) {
  56800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56801. this._defines.UV1 = true;
  56802. }
  56803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56804. this._defines.UV2 = true;
  56805. }
  56806. }
  56807. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56808. this._defines.VERTEXCOLOR = true;
  56809. if (mesh.hasVertexAlpha) {
  56810. this._defines.VERTEXALPHA = true;
  56811. }
  56812. }
  56813. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56814. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  56815. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  56816. }
  56817. // Instances
  56818. if (useInstances) {
  56819. this._defines.INSTANCES = true;
  56820. }
  56821. }
  56822. // Get correct effect
  56823. if (!this._defines.isEqual(this._cachedDefines)) {
  56824. this._defines.cloneTo(this._cachedDefines);
  56825. scene.resetCachedMaterial();
  56826. // Fallbacks
  56827. var fallbacks = new BABYLON.EffectFallbacks();
  56828. if (this._defines.REFLECTION) {
  56829. fallbacks.addFallback(0, "REFLECTION");
  56830. }
  56831. if (this._defines.REFRACTION) {
  56832. fallbacks.addFallback(0, "REFRACTION");
  56833. }
  56834. if (this._defines.REFLECTIVITY) {
  56835. fallbacks.addFallback(0, "REFLECTIVITY");
  56836. }
  56837. if (this._defines.BUMP) {
  56838. fallbacks.addFallback(0, "BUMP");
  56839. }
  56840. if (this._defines.PARALLAX) {
  56841. fallbacks.addFallback(1, "PARALLAX");
  56842. }
  56843. if (this._defines.PARALLAXOCCLUSION) {
  56844. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  56845. }
  56846. if (this._defines.SPECULAROVERALPHA) {
  56847. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  56848. }
  56849. if (this._defines.FOG) {
  56850. fallbacks.addFallback(1, "FOG");
  56851. }
  56852. if (this._defines.POINTSIZE) {
  56853. fallbacks.addFallback(0, "POINTSIZE");
  56854. }
  56855. if (this._defines.LOGARITHMICDEPTH) {
  56856. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  56857. }
  56858. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  56859. if (this._defines.SPECULARTERM) {
  56860. fallbacks.addFallback(0, "SPECULARTERM");
  56861. }
  56862. if (this._defines.OPACITYFRESNEL) {
  56863. fallbacks.addFallback(1, "OPACITYFRESNEL");
  56864. }
  56865. if (this._defines.EMISSIVEFRESNEL) {
  56866. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  56867. }
  56868. if (this._defines.FRESNEL) {
  56869. fallbacks.addFallback(3, "FRESNEL");
  56870. }
  56871. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  56872. fallbacks.addCPUSkinningFallback(0, mesh);
  56873. }
  56874. //Attributes
  56875. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56876. if (this._defines.NORMAL) {
  56877. attribs.push(BABYLON.VertexBuffer.NormalKind);
  56878. }
  56879. if (this._defines.UV1) {
  56880. attribs.push(BABYLON.VertexBuffer.UVKind);
  56881. }
  56882. if (this._defines.UV2) {
  56883. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56884. }
  56885. if (this._defines.VERTEXCOLOR) {
  56886. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56887. }
  56888. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  56889. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  56890. // Legacy browser patch
  56891. var join = this._defines.toString();
  56892. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  56893. "vFogInfos", "vFogColor", "pointSize",
  56894. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  56895. "mBones",
  56896. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  56897. "depthValues",
  56898. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  56899. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  56900. "logarithmicDepthConstant",
  56901. "vSphericalX", "vSphericalY", "vSphericalZ",
  56902. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  56903. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  56904. "vMicrosurfaceTextureLods",
  56905. "vCameraInfos"
  56906. ];
  56907. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  56908. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  56909. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  56910. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  56911. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  56912. }
  56913. if (!this._effect.isReady()) {
  56914. return false;
  56915. }
  56916. this._renderId = scene.getRenderId();
  56917. this._wasPreviouslyReady = true;
  56918. if (mesh) {
  56919. if (!mesh._materialDefines) {
  56920. mesh._materialDefines = new PBRMaterialDefines();
  56921. }
  56922. this._defines.cloneTo(mesh._materialDefines);
  56923. }
  56924. return true;
  56925. };
  56926. PBRMaterial.prototype.unbind = function () {
  56927. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  56928. this._effect.setTexture("reflection2DSampler", null);
  56929. }
  56930. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  56931. this._effect.setTexture("refraction2DSampler", null);
  56932. }
  56933. _super.prototype.unbind.call(this);
  56934. };
  56935. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56936. this._effect.setMatrix("world", world);
  56937. };
  56938. PBRMaterial.prototype.bind = function (world, mesh) {
  56939. this._myScene = this.getScene();
  56940. // Matrices
  56941. this.bindOnlyWorldMatrix(world);
  56942. // Bones
  56943. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  56944. if (this._myScene.getCachedMaterial() !== this) {
  56945. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  56946. if (BABYLON.StandardMaterial.FresnelEnabled) {
  56947. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  56948. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  56949. }
  56950. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56951. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  56952. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  56953. }
  56954. }
  56955. // Textures
  56956. if (this._myScene.texturesEnabled) {
  56957. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56958. this._effect.setTexture("albedoSampler", this.albedoTexture);
  56959. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  56960. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  56961. }
  56962. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  56963. this._effect.setTexture("ambientSampler", this.ambientTexture);
  56964. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  56965. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  56966. }
  56967. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  56968. this._effect.setTexture("opacitySampler", this.opacityTexture);
  56969. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  56970. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  56971. }
  56972. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  56973. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  56974. if (this.reflectionTexture.isCube) {
  56975. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  56976. }
  56977. else {
  56978. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  56979. }
  56980. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  56981. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  56982. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  56983. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  56984. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  56985. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  56986. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  56987. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  56988. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  56989. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  56990. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  56991. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  56992. }
  56993. }
  56994. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  56995. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  56996. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  56997. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  56998. }
  56999. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57000. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  57001. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  57002. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  57003. }
  57004. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57005. if (this.metallicTexture) {
  57006. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  57007. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  57008. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  57009. }
  57010. else if (this.reflectivityTexture) {
  57011. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  57012. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  57013. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  57014. }
  57015. }
  57016. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57017. this._effect.setTexture("bumpSampler", this.bumpTexture);
  57018. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  57019. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  57020. }
  57021. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57022. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  57023. var depth = 1.0;
  57024. if (this.refractionTexture.isCube) {
  57025. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  57026. }
  57027. else {
  57028. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  57029. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  57030. if (this.refractionTexture.depth) {
  57031. depth = this.refractionTexture.depth;
  57032. }
  57033. }
  57034. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  57035. }
  57036. if ((this.reflectionTexture || this.refractionTexture)) {
  57037. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  57038. }
  57039. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  57040. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  57041. }
  57042. }
  57043. // Clip plane
  57044. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  57045. // Point size
  57046. if (this.pointsCloud) {
  57047. this._effect.setFloat("pointSize", this.pointSize);
  57048. }
  57049. // Colors
  57050. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  57051. if (this._defines.METALLICWORKFLOW) {
  57052. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  57053. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  57054. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  57055. }
  57056. else {
  57057. // GAMMA CORRECTION.
  57058. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  57059. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  57060. }
  57061. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  57062. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  57063. // GAMMA CORRECTION.
  57064. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  57065. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  57066. // GAMMA CORRECTION.
  57067. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  57068. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  57069. }
  57070. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  57071. // GAMMA CORRECTION.
  57072. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  57073. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  57074. // Lights
  57075. if (this._myScene.lightsEnabled && !this.disableLighting) {
  57076. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  57077. }
  57078. // View
  57079. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  57080. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  57081. }
  57082. // Fog
  57083. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  57084. this._lightingInfos.x = this.directIntensity;
  57085. this._lightingInfos.y = this.emissiveIntensity;
  57086. this._lightingInfos.z = this.environmentIntensity;
  57087. this._lightingInfos.w = this.specularIntensity;
  57088. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  57089. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  57090. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  57091. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  57092. this._cameraInfos.x = this.cameraExposure;
  57093. this._cameraInfos.y = this.cameraContrast;
  57094. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  57095. if (this.cameraColorCurves) {
  57096. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  57097. }
  57098. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  57099. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  57100. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  57101. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  57102. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  57103. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  57104. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  57105. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  57106. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  57107. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  57108. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  57109. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  57110. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  57111. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  57112. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  57113. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  57114. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  57115. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  57116. // Log. depth
  57117. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  57118. }
  57119. _super.prototype.bind.call(this, world, mesh);
  57120. this._myScene = null;
  57121. };
  57122. PBRMaterial.prototype.getAnimatables = function () {
  57123. var results = [];
  57124. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  57125. results.push(this.albedoTexture);
  57126. }
  57127. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  57128. results.push(this.ambientTexture);
  57129. }
  57130. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  57131. results.push(this.opacityTexture);
  57132. }
  57133. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  57134. results.push(this.reflectionTexture);
  57135. }
  57136. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  57137. results.push(this.emissiveTexture);
  57138. }
  57139. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  57140. results.push(this.metallicTexture);
  57141. }
  57142. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  57143. results.push(this.reflectivityTexture);
  57144. }
  57145. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  57146. results.push(this.bumpTexture);
  57147. }
  57148. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  57149. results.push(this.lightmapTexture);
  57150. }
  57151. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  57152. results.push(this.refractionTexture);
  57153. }
  57154. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  57155. results.push(this.cameraColorGradingTexture);
  57156. }
  57157. return results;
  57158. };
  57159. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57160. if (forceDisposeTextures) {
  57161. if (this.albedoTexture) {
  57162. this.albedoTexture.dispose();
  57163. }
  57164. if (this.ambientTexture) {
  57165. this.ambientTexture.dispose();
  57166. }
  57167. if (this.opacityTexture) {
  57168. this.opacityTexture.dispose();
  57169. }
  57170. if (this.reflectionTexture) {
  57171. this.reflectionTexture.dispose();
  57172. }
  57173. if (this.emissiveTexture) {
  57174. this.emissiveTexture.dispose();
  57175. }
  57176. if (this.metallicTexture) {
  57177. this.metallicTexture.dispose();
  57178. }
  57179. if (this.reflectivityTexture) {
  57180. this.reflectivityTexture.dispose();
  57181. }
  57182. if (this.bumpTexture) {
  57183. this.bumpTexture.dispose();
  57184. }
  57185. if (this.lightmapTexture) {
  57186. this.lightmapTexture.dispose();
  57187. }
  57188. if (this.refractionTexture) {
  57189. this.refractionTexture.dispose();
  57190. }
  57191. if (this.cameraColorGradingTexture) {
  57192. this.cameraColorGradingTexture.dispose();
  57193. }
  57194. }
  57195. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57196. };
  57197. PBRMaterial.prototype.clone = function (name) {
  57198. var _this = this;
  57199. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  57200. };
  57201. PBRMaterial.prototype.serialize = function () {
  57202. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57203. serializationObject.customType = "BABYLON.PBRMaterial";
  57204. return serializationObject;
  57205. };
  57206. // Statics
  57207. PBRMaterial.Parse = function (source, scene, rootUrl) {
  57208. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  57209. };
  57210. return PBRMaterial;
  57211. }(BABYLON.Material));
  57212. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  57213. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  57214. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  57215. PBRMaterial._scaledReflection = new BABYLON.Color3();
  57216. __decorate([
  57217. BABYLON.serialize()
  57218. ], PBRMaterial.prototype, "directIntensity", void 0);
  57219. __decorate([
  57220. BABYLON.serialize()
  57221. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  57222. __decorate([
  57223. BABYLON.serialize()
  57224. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  57225. __decorate([
  57226. BABYLON.serialize()
  57227. ], PBRMaterial.prototype, "specularIntensity", void 0);
  57228. __decorate([
  57229. BABYLON.serialize()
  57230. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  57231. __decorate([
  57232. BABYLON.serialize()
  57233. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  57234. __decorate([
  57235. BABYLON.serialize()
  57236. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  57237. __decorate([
  57238. BABYLON.serialize()
  57239. ], PBRMaterial.prototype, "cameraExposure", void 0);
  57240. __decorate([
  57241. BABYLON.serialize()
  57242. ], PBRMaterial.prototype, "cameraContrast", void 0);
  57243. __decorate([
  57244. BABYLON.serializeAsTexture()
  57245. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  57246. __decorate([
  57247. BABYLON.serializeAsColorCurves()
  57248. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  57249. __decorate([
  57250. BABYLON.serializeAsColor3()
  57251. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  57252. __decorate([
  57253. BABYLON.serialize()
  57254. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  57255. __decorate([
  57256. BABYLON.serializeAsColor3()
  57257. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  57258. __decorate([
  57259. BABYLON.serialize()
  57260. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  57261. __decorate([
  57262. BABYLON.serializeAsColor3()
  57263. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  57264. __decorate([
  57265. BABYLON.serialize()
  57266. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  57267. __decorate([
  57268. BABYLON.serializeAsColor3()
  57269. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  57270. __decorate([
  57271. BABYLON.serialize()
  57272. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  57273. __decorate([
  57274. BABYLON.serializeAsColor3()
  57275. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  57276. __decorate([
  57277. BABYLON.serialize()
  57278. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  57279. __decorate([
  57280. BABYLON.serialize()
  57281. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  57282. __decorate([
  57283. BABYLON.serialize()
  57284. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  57285. __decorate([
  57286. BABYLON.serializeAsTexture()
  57287. ], PBRMaterial.prototype, "albedoTexture", void 0);
  57288. __decorate([
  57289. BABYLON.serializeAsTexture()
  57290. ], PBRMaterial.prototype, "ambientTexture", void 0);
  57291. __decorate([
  57292. BABYLON.serialize()
  57293. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  57294. __decorate([
  57295. BABYLON.serializeAsTexture()
  57296. ], PBRMaterial.prototype, "opacityTexture", void 0);
  57297. __decorate([
  57298. BABYLON.serializeAsTexture()
  57299. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  57300. __decorate([
  57301. BABYLON.serializeAsTexture()
  57302. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  57303. __decorate([
  57304. BABYLON.serializeAsTexture()
  57305. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  57306. __decorate([
  57307. BABYLON.serializeAsTexture()
  57308. ], PBRMaterial.prototype, "metallicTexture", void 0);
  57309. __decorate([
  57310. BABYLON.serialize()
  57311. ], PBRMaterial.prototype, "metallic", void 0);
  57312. __decorate([
  57313. BABYLON.serialize()
  57314. ], PBRMaterial.prototype, "roughness", void 0);
  57315. __decorate([
  57316. BABYLON.serializeAsTexture()
  57317. ], PBRMaterial.prototype, "bumpTexture", void 0);
  57318. __decorate([
  57319. BABYLON.serializeAsTexture()
  57320. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  57321. __decorate([
  57322. BABYLON.serializeAsTexture()
  57323. ], PBRMaterial.prototype, "refractionTexture", void 0);
  57324. __decorate([
  57325. BABYLON.serializeAsColor3("ambient")
  57326. ], PBRMaterial.prototype, "ambientColor", void 0);
  57327. __decorate([
  57328. BABYLON.serializeAsColor3("albedo")
  57329. ], PBRMaterial.prototype, "albedoColor", void 0);
  57330. __decorate([
  57331. BABYLON.serializeAsColor3("reflectivity")
  57332. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  57333. __decorate([
  57334. BABYLON.serializeAsColor3("reflection")
  57335. ], PBRMaterial.prototype, "reflectionColor", void 0);
  57336. __decorate([
  57337. BABYLON.serializeAsColor3("emissive")
  57338. ], PBRMaterial.prototype, "emissiveColor", void 0);
  57339. __decorate([
  57340. BABYLON.serialize()
  57341. ], PBRMaterial.prototype, "microSurface", void 0);
  57342. __decorate([
  57343. BABYLON.serialize()
  57344. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  57345. __decorate([
  57346. BABYLON.serialize()
  57347. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  57348. __decorate([
  57349. BABYLON.serializeAsFresnelParameters()
  57350. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  57351. __decorate([
  57352. BABYLON.serializeAsFresnelParameters()
  57353. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  57354. __decorate([
  57355. BABYLON.serialize()
  57356. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  57357. __decorate([
  57358. BABYLON.serialize()
  57359. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  57360. __decorate([
  57361. BABYLON.serialize()
  57362. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  57363. __decorate([
  57364. BABYLON.serialize()
  57365. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  57366. __decorate([
  57367. BABYLON.serialize()
  57368. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  57369. __decorate([
  57370. BABYLON.serialize()
  57371. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  57372. __decorate([
  57373. BABYLON.serialize()
  57374. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  57375. __decorate([
  57376. BABYLON.serialize()
  57377. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  57378. __decorate([
  57379. BABYLON.serialize()
  57380. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  57381. __decorate([
  57382. BABYLON.serialize()
  57383. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  57384. __decorate([
  57385. BABYLON.serialize()
  57386. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  57387. __decorate([
  57388. BABYLON.serialize()
  57389. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  57390. __decorate([
  57391. BABYLON.serialize()
  57392. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  57393. __decorate([
  57394. BABYLON.serialize()
  57395. ], PBRMaterial.prototype, "useParallax", void 0);
  57396. __decorate([
  57397. BABYLON.serialize()
  57398. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  57399. __decorate([
  57400. BABYLON.serialize()
  57401. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  57402. __decorate([
  57403. BABYLON.serialize()
  57404. ], PBRMaterial.prototype, "disableLighting", void 0);
  57405. __decorate([
  57406. BABYLON.serialize()
  57407. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  57408. __decorate([
  57409. BABYLON.serialize()
  57410. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  57411. __decorate([
  57412. BABYLON.serialize()
  57413. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  57414. __decorate([
  57415. BABYLON.serialize()
  57416. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  57417. BABYLON.PBRMaterial = PBRMaterial;
  57418. })(BABYLON || (BABYLON = {}));
  57419. //# sourceMappingURL=babylon.pbrMaterial.js.map
  57420. var BABYLON;
  57421. (function (BABYLON) {
  57422. var DebugLayer = (function () {
  57423. function DebugLayer(scene) {
  57424. this._scene = scene;
  57425. }
  57426. /** Creates the inspector window. */
  57427. DebugLayer.prototype._createInspector = function (popup) {
  57428. if (!this._inspector) {
  57429. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  57430. } // else nothing to do,; instance is already existing
  57431. };
  57432. DebugLayer.prototype.isVisible = function () {
  57433. return false;
  57434. };
  57435. DebugLayer.prototype.hide = function () {
  57436. if (this._inspector) {
  57437. this._inspector.dispose();
  57438. this._inspector = null;
  57439. }
  57440. };
  57441. DebugLayer.prototype.show = function (popup) {
  57442. if (typeof INSPECTOR == 'undefined') {
  57443. // Load inspector and add it to the DOM
  57444. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  57445. }
  57446. else {
  57447. // Otherwise creates the inspector
  57448. this._createInspector(popup);
  57449. }
  57450. };
  57451. return DebugLayer;
  57452. }());
  57453. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  57454. BABYLON.DebugLayer = DebugLayer;
  57455. })(BABYLON || (BABYLON = {}));
  57456. //# sourceMappingURL=babylon.debugLayer.js.map
  57457. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  57458. var BABYLON;
  57459. (function (BABYLON) {
  57460. var StandardRenderingPipeline = (function (_super) {
  57461. __extends(StandardRenderingPipeline, _super);
  57462. /**
  57463. * @constructor
  57464. * @param {string} name - The rendering pipeline name
  57465. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57466. * @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)
  57467. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57468. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57469. */
  57470. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57471. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57472. var _this = _super.call(this, scene.getEngine(), name) || this;
  57473. _this.downSampleX4PostProcess = null;
  57474. _this.brightPassPostProcess = null;
  57475. _this.gaussianBlurHPostProcesses = [];
  57476. _this.gaussianBlurVPostProcesses = [];
  57477. _this.textureAdderPostProcess = null;
  57478. _this.textureAdderFinalPostProcess = null;
  57479. _this.lensFlarePostProcess = null;
  57480. _this.lensFlareComposePostProcess = null;
  57481. _this.depthOfFieldPostProcess = null;
  57482. // Values
  57483. _this.brightThreshold = 1.0;
  57484. _this.blurWidth = 2.0;
  57485. _this.gaussianCoefficient = 0.25;
  57486. _this.gaussianMean = 1.0;
  57487. _this.gaussianStandardDeviation = 1.0;
  57488. _this.exposure = 1.0;
  57489. _this.lensTexture = null;
  57490. _this.lensColorTexture = null;
  57491. _this.lensFlareStrength = 20.0;
  57492. _this.lensFlareGhostDispersal = 1.4;
  57493. _this.lensFlareHaloWidth = 0.7;
  57494. _this.lensFlareDistortionStrength = 16.0;
  57495. _this.lensStarTexture = null;
  57496. _this.lensFlareDirtTexture = null;
  57497. _this.depthOfFieldDistance = 10.0;
  57498. // IAnimatable
  57499. _this.animations = [];
  57500. _this._depthRenderer = null;
  57501. // Getters and setters
  57502. _this._depthOfFieldEnabled = true;
  57503. _this._lensFlareEnabled = true;
  57504. // Initialize
  57505. _this._scene = scene;
  57506. // Create pass post-processe
  57507. if (!originalPostProcess) {
  57508. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  57509. }
  57510. else {
  57511. _this.originalPostProcess = originalPostProcess;
  57512. }
  57513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57514. // Create down sample X4 post-process
  57515. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  57516. // Create bright pass post-process
  57517. _this._createBrightPassPostProcess(scene, ratio / 2);
  57518. // Create gaussian blur post-processes (down sampling blurs)
  57519. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  57520. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  57521. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  57522. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  57523. // Create texture adder post-process
  57524. _this._createTextureAdderPostProcess(scene, ratio);
  57525. // Create depth-of-field source post-process
  57526. _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);
  57527. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57528. // Create lens flare post-process
  57529. _this._createLensFlarePostProcess(scene, ratio);
  57530. // Create gaussian blur used by depth-of-field
  57531. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  57532. // Create depth-of-field post-process
  57533. _this._createDepthOfFieldPostProcess(scene, ratio);
  57534. // Finish
  57535. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57536. if (cameras !== null) {
  57537. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57538. }
  57539. // Deactivate
  57540. _this.LensFlareEnabled = false;
  57541. _this.DepthOfFieldEnabled = false;
  57542. return _this;
  57543. }
  57544. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57545. get: function () {
  57546. return this._depthOfFieldEnabled;
  57547. },
  57548. set: function (enabled) {
  57549. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  57550. if (enabled && !this._depthOfFieldEnabled) {
  57551. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57552. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57553. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57554. this._depthRenderer = this._scene.enableDepthRenderer();
  57555. }
  57556. else if (!enabled && this._depthOfFieldEnabled) {
  57557. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57558. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57559. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57560. }
  57561. this._depthOfFieldEnabled = enabled;
  57562. },
  57563. enumerable: true,
  57564. configurable: true
  57565. });
  57566. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57567. get: function () {
  57568. return this._lensFlareEnabled;
  57569. },
  57570. set: function (enabled) {
  57571. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  57572. if (enabled && !this._lensFlareEnabled) {
  57573. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57574. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57575. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57576. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57577. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57578. }
  57579. else if (!enabled && this._lensFlareEnabled) {
  57580. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57581. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57582. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57583. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57584. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57585. }
  57586. this._lensFlareEnabled = enabled;
  57587. },
  57588. enumerable: true,
  57589. configurable: true
  57590. });
  57591. // Down Sample X4 Post-Processs
  57592. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57593. var _this = this;
  57594. var downSampleX4Offsets = new Array(32);
  57595. 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);
  57596. this.downSampleX4PostProcess.onApply = function (effect) {
  57597. var id = 0;
  57598. for (var i = -2; i < 2; i++) {
  57599. for (var j = -2; j < 2; j++) {
  57600. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  57601. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  57602. id += 2;
  57603. }
  57604. }
  57605. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57606. };
  57607. // Add to pipeline
  57608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  57609. };
  57610. // Brightpass Post-Process
  57611. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57612. var _this = this;
  57613. var brightOffsets = new Array(8);
  57614. 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);
  57615. this.brightPassPostProcess.onApply = function (effect) {
  57616. var sU = (1.0 / _this.brightPassPostProcess.width);
  57617. var sV = (1.0 / _this.brightPassPostProcess.height);
  57618. brightOffsets[0] = -0.5 * sU;
  57619. brightOffsets[1] = 0.5 * sV;
  57620. brightOffsets[2] = 0.5 * sU;
  57621. brightOffsets[3] = 0.5 * sV;
  57622. brightOffsets[4] = -0.5 * sU;
  57623. brightOffsets[5] = -0.5 * sV;
  57624. brightOffsets[6] = 0.5 * sU;
  57625. brightOffsets[7] = -0.5 * sV;
  57626. effect.setArray2("dsOffsets", brightOffsets);
  57627. effect.setFloat("brightThreshold", _this.brightThreshold);
  57628. };
  57629. // Add to pipeline
  57630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  57631. };
  57632. // Create gaussian blur H&V post-processes
  57633. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  57634. var _this = this;
  57635. var blurOffsets = new Array(9);
  57636. var blurWeights = new Array(9);
  57637. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  57638. var callback = function (height) {
  57639. return function (effect) {
  57640. // Weights
  57641. var x = 0.0;
  57642. for (var i = 0; i < 9; i++) {
  57643. x = (i - 4.0) / 4.0;
  57644. blurWeights[i] =
  57645. _this.gaussianCoefficient
  57646. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  57647. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  57648. }
  57649. var lastOutputDimensions = {
  57650. width: scene.getEngine().getRenderWidth(),
  57651. height: scene.getEngine().getRenderHeight()
  57652. };
  57653. for (var i = 0; i < 9; i++) {
  57654. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57655. blurOffsets[i] = value;
  57656. }
  57657. effect.setArray("blurOffsets", blurOffsets);
  57658. effect.setArray("blurWeights", blurWeights);
  57659. effect.setFloat("blurWidth", _this.blurWidth);
  57660. };
  57661. };
  57662. // Create horizontal gaussian blur post-processes
  57663. 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);
  57664. gaussianBlurHPostProcess.onApply = callback(false);
  57665. // Create vertical gaussian blur post-process
  57666. 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);
  57667. gaussianBlurVPostProcess.onApply = callback(true);
  57668. // Add to pipeline
  57669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  57670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  57671. // Finish
  57672. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  57673. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  57674. };
  57675. // Create texture adder post-process
  57676. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57677. var _this = this;
  57678. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  57679. 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);
  57680. this.textureAdderPostProcess.onApply = function (effect) {
  57681. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  57682. effect.setTexture("lensSampler", _this.lensTexture);
  57683. effect.setFloat("exposure", _this.exposure);
  57684. };
  57685. // Add to pipeline
  57686. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  57687. };
  57688. // Create lens flare post-process
  57689. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  57690. var _this = this;
  57691. 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);
  57692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  57693. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  57694. 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);
  57695. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  57696. var resolution = new BABYLON.Vector2(0, 0);
  57697. // Lens flare
  57698. this.lensFlarePostProcess.onApply = function (effect) {
  57699. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  57700. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  57701. effect.setFloat("strength", _this.lensFlareStrength);
  57702. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  57703. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  57704. // Shift
  57705. resolution.x = _this.lensFlarePostProcess.width;
  57706. resolution.y = _this.lensFlarePostProcess.height;
  57707. effect.setVector2("resolution", resolution);
  57708. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  57709. };
  57710. // Compose
  57711. 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);
  57712. 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);
  57713. this.lensFlareComposePostProcess.onApply = function (effect) {
  57714. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57715. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  57716. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  57717. // Lens start rotation matrix
  57718. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  57719. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  57720. 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));
  57721. camRot *= 4.0;
  57722. 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);
  57723. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  57724. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  57725. };
  57726. };
  57727. // Create depth-of-field post-process
  57728. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  57729. var _this = this;
  57730. 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);
  57731. this.depthOfFieldPostProcess.onApply = function (effect) {
  57732. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57733. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  57734. effect.setFloat("distance", _this.depthOfFieldDistance);
  57735. };
  57736. // Add to pipeline
  57737. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  57738. };
  57739. // Dispose
  57740. StandardRenderingPipeline.prototype.dispose = function () {
  57741. for (var i = 0; i < this._scene.cameras.length; i++) {
  57742. var camera = this._scene.cameras[i];
  57743. this.originalPostProcess.dispose(camera);
  57744. this.downSampleX4PostProcess.dispose(camera);
  57745. this.brightPassPostProcess.dispose(camera);
  57746. this.textureAdderPostProcess.dispose(camera);
  57747. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  57748. this.gaussianBlurHPostProcesses[j].dispose(camera);
  57749. }
  57750. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  57751. this.gaussianBlurVPostProcesses[j].dispose(camera);
  57752. }
  57753. this.textureAdderFinalPostProcess.dispose(camera);
  57754. this.lensFlarePostProcess.dispose(camera);
  57755. this.lensFlareComposePostProcess.dispose(camera);
  57756. this.depthOfFieldPostProcess.dispose(camera);
  57757. }
  57758. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57759. _super.prototype.dispose.call(this);
  57760. };
  57761. return StandardRenderingPipeline;
  57762. }(BABYLON.PostProcessRenderPipeline));
  57763. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  57764. })(BABYLON || (BABYLON = {}));
  57765. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  57766. 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\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\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\nvFogDistance=viewPos;\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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\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}"};
  57767. 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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\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,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}\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+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\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"};
  57768. 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(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var p=!1,P=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(p=!0,P=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P);y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(p){var x=P*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!==(d&c.collisionGroup)&&c._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){F.Vector3[0].x=t.y*i.z-t.z*i.y,F.Vector3[0].y=t.z*i.x-t.x*i.z,F.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(F.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=F.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){return this.width=t,this.height=i,this},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function i(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.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)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){var t=new i((-this.x),(-this.y),(-this.z),this.w);return t},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},i.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i((-t.x),(-t.y),(-t.z),t.w)},i.Identity=function(){return new i(0,0,0,1)},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=F.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},i}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.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])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=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,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];\nreturn this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.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]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,F.Matrix[0]),a.FromRotationMatrixToRef(F.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t),this},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.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])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,F.Matrix[1]),i.toRotationMatrix(F.Matrix[0]),F.Matrix[1].multiplyToRef(F.Matrix[0],o),o.setTranslation(n)},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.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)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.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 i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.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]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[a.Zero(),a.Zero()],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A;var F=function(){function t(){}return t}();F.Vector3=[e.Zero()],F.Matrix=[u.Zero(),u.Zero()],F.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  57769. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  57770. module.exports = BABYLON;
  57771. };